livedesk 0.1.450 → 0.1.451
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/bin/livedesk.js +4 -0
- package/client/bin/livedesk-client.js +2 -0
- package/client/package.json +1 -1
- package/client/src/runtime/client-runtime-server.js +19 -4
- package/hub/package.json +1 -1
- package/hub/src/agents/agent-manager.js +5 -2
- package/hub/src/agents/codex-agent-runtime.js +10 -13
- package/package.json +2 -2
- package/web/dist/assets/{index-BPpXtm8K.css → index-9QTFmh8R.css} +1 -1
- package/web/dist/assets/{index-vBxXkd_R.js → index-BFwWY4pa.js} +1 -1
- package/web/dist/index.html +2 -2
|
@@ -9,7 +9,7 @@ Error generating stack: `+o.message+`
|
|
|
9
9
|
`).replace(zS,"")}function Dv(e,t){return t=Ev(t),Ev(e)===t}function Qt(e,t,r,o,f,p){switch(r){case"children":typeof o=="string"?t==="body"||t==="textarea"&&o===""||lr(e,o):(typeof o=="number"||typeof o=="bigint")&&t!=="body"&&lr(e,""+o);break;case"className":Us(e,"class",o);break;case"tabIndex":Us(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":Us(e,r,o);break;case"style":Gr(e,o,p);break;case"data":if(t!=="object"){Us(e,"data",o);break}case"src":case"href":if(o===""&&(t!=="a"||r!=="href")){e.removeAttribute(r);break}if(o==null||typeof o=="function"||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(r);break}o=Fl(""+o),e.setAttribute(r,o);break;case"action":case"formAction":if(typeof o=="function"){e.setAttribute(r,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof p=="function"&&(r==="formAction"?(t!=="input"&&Qt(e,t,"name",f.name,f,null),Qt(e,t,"formEncType",f.formEncType,f,null),Qt(e,t,"formMethod",f.formMethod,f,null),Qt(e,t,"formTarget",f.formTarget,f,null)):(Qt(e,t,"encType",f.encType,f,null),Qt(e,t,"method",f.method,f,null),Qt(e,t,"target",f.target,f,null)));if(o==null||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(r);break}o=Fl(""+o),e.setAttribute(r,o);break;case"onClick":o!=null&&(e.onclick=qa);break;case"onScroll":o!=null&&Lt("scroll",e);break;case"onScrollEnd":o!=null&&Lt("scrollend",e);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(r=o.__html,r!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=r}}break;case"multiple":e.multiple=o&&typeof o!="function"&&typeof o!="symbol";break;case"muted":e.muted=o&&typeof o!="function"&&typeof o!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(o==null||typeof o=="function"||typeof o=="boolean"||typeof o=="symbol"){e.removeAttribute("xlink:href");break}r=Fl(""+o),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",r);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(r,""+o):e.removeAttribute(r);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":o&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(r,""):e.removeAttribute(r);break;case"capture":case"download":o===!0?e.setAttribute(r,""):o!==!1&&o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(r,o):e.removeAttribute(r);break;case"cols":case"rows":case"size":case"span":o!=null&&typeof o!="function"&&typeof o!="symbol"&&!isNaN(o)&&1<=o?e.setAttribute(r,o):e.removeAttribute(r);break;case"rowSpan":case"start":o==null||typeof o=="function"||typeof o=="symbol"||isNaN(o)?e.removeAttribute(r):e.setAttribute(r,o);break;case"popover":Lt("beforetoggle",e),Lt("toggle",e),zi(e,"popover",o);break;case"xlinkActuate":un(e,"http://www.w3.org/1999/xlink","xlink:actuate",o);break;case"xlinkArcrole":un(e,"http://www.w3.org/1999/xlink","xlink:arcrole",o);break;case"xlinkRole":un(e,"http://www.w3.org/1999/xlink","xlink:role",o);break;case"xlinkShow":un(e,"http://www.w3.org/1999/xlink","xlink:show",o);break;case"xlinkTitle":un(e,"http://www.w3.org/1999/xlink","xlink:title",o);break;case"xlinkType":un(e,"http://www.w3.org/1999/xlink","xlink:type",o);break;case"xmlBase":un(e,"http://www.w3.org/XML/1998/namespace","xml:base",o);break;case"xmlLang":un(e,"http://www.w3.org/XML/1998/namespace","xml:lang",o);break;case"xmlSpace":un(e,"http://www.w3.org/XML/1998/namespace","xml:space",o);break;case"is":zi(e,"is",o);break;case"innerText":case"textContent":break;default:(!(2<r.length)||r[0]!=="o"&&r[0]!=="O"||r[1]!=="n"&&r[1]!=="N")&&(r=Pl.get(r)||r,zi(e,r,o))}}function Xm(e,t,r,o,f,p){switch(r){case"style":Gr(e,o,p);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(r=o.__html,r!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=r}}break;case"children":typeof o=="string"?lr(e,o):(typeof o=="number"||typeof o=="bigint")&&lr(e,""+o);break;case"onScroll":o!=null&&Lt("scroll",e);break;case"onScrollEnd":o!=null&&Lt("scrollend",e);break;case"onClick":o!=null&&(e.onclick=qa);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Ht.hasOwnProperty(r))e:{if(r[0]==="o"&&r[1]==="n"&&(f=r.endsWith("Capture"),t=r.slice(2,f?r.length-7:void 0),p=e[Ee]||null,p=p!=null?p[r]:null,typeof p=="function"&&e.removeEventListener(t,p,f),typeof o=="function")){typeof p!="function"&&p!==null&&(r in e?e[r]=null:e.hasAttribute(r)&&e.removeAttribute(r)),e.addEventListener(t,o,f);break e}r in e?e[r]=o:o===!0?e.setAttribute(r,""):zi(e,r,o)}}}function pa(e,t,r){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Lt("error",e),Lt("load",e);var o=!1,f=!1,p;for(p in r)if(r.hasOwnProperty(p)){var S=r[p];if(S!=null)switch(p){case"src":o=!0;break;case"srcSet":f=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Qt(e,t,p,S,r,null)}}f&&Qt(e,t,"srcSet",r.srcSet,r,null),o&&Qt(e,t,"src",r.src,r,null);return;case"input":Lt("invalid",e);var R=p=S=f=null,q=null,ue=null;for(o in r)if(r.hasOwnProperty(o)){var we=r[o];if(we!=null)switch(o){case"name":f=we;break;case"type":S=we;break;case"checked":q=we;break;case"defaultChecked":ue=we;break;case"value":p=we;break;case"defaultValue":R=we;break;case"children":case"dangerouslySetInnerHTML":if(we!=null)throw Error(l(137,t));break;default:Qt(e,t,o,we,r,null)}}_c(e,p,R,q,ue,S,f,!1);return;case"select":Lt("invalid",e),o=S=p=null;for(f in r)if(r.hasOwnProperty(f)&&(R=r[f],R!=null))switch(f){case"value":p=R;break;case"defaultValue":S=R;break;case"multiple":o=R;default:Qt(e,t,f,R,r,null)}t=p,r=S,e.multiple=!!o,t!=null?xn(e,!!o,t,!1):r!=null&&xn(e,!!o,r,!0);return;case"textarea":Lt("invalid",e),p=f=o=null;for(S in r)if(r.hasOwnProperty(S)&&(R=r[S],R!=null))switch(S){case"value":o=R;break;case"defaultValue":f=R;break;case"children":p=R;break;case"dangerouslySetInnerHTML":if(R!=null)throw Error(l(91));break;default:Qt(e,t,S,R,r,null)}qr(e,o,f,p);return;case"option":for(q in r)r.hasOwnProperty(q)&&(o=r[q],o!=null)&&(q==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":Qt(e,t,q,o,r,null));return;case"dialog":Lt("beforetoggle",e),Lt("toggle",e),Lt("cancel",e),Lt("close",e);break;case"iframe":case"object":Lt("load",e);break;case"video":case"audio":for(o=0;o<xu.length;o++)Lt(xu[o],e);break;case"image":Lt("error",e),Lt("load",e);break;case"details":Lt("toggle",e);break;case"embed":case"source":case"link":Lt("error",e),Lt("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(ue in r)if(r.hasOwnProperty(ue)&&(o=r[ue],o!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Qt(e,t,ue,o,r,null)}return;default:if(Pi(t)){for(we in r)r.hasOwnProperty(we)&&(o=r[we],o!==void 0&&Xm(e,t,we,o,r,void 0));return}}for(R in r)r.hasOwnProperty(R)&&(o=r[R],o!=null&&Qt(e,t,R,o,r,null))}function OS(e,t,r,o){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var f=null,p=null,S=null,R=null,q=null,ue=null,we=null;for(ge in r){var ke=r[ge];if(r.hasOwnProperty(ge)&&ke!=null)switch(ge){case"checked":break;case"value":break;case"defaultValue":q=ke;default:o.hasOwnProperty(ge)||Qt(e,t,ge,null,o,ke)}}for(var de in o){var ge=o[de];if(ke=r[de],o.hasOwnProperty(de)&&(ge!=null||ke!=null))switch(de){case"type":p=ge;break;case"name":f=ge;break;case"checked":ue=ge;break;case"defaultChecked":we=ge;break;case"value":S=ge;break;case"defaultValue":R=ge;break;case"children":case"dangerouslySetInnerHTML":if(ge!=null)throw Error(l(137,t));break;default:ge!==ke&&Qt(e,t,de,ge,o,ke)}}Lc(e,S,R,q,ue,we,p,f);return;case"select":ge=S=R=de=null;for(p in r)if(q=r[p],r.hasOwnProperty(p)&&q!=null)switch(p){case"value":break;case"multiple":ge=q;default:o.hasOwnProperty(p)||Qt(e,t,p,null,o,q)}for(f in o)if(p=o[f],q=r[f],o.hasOwnProperty(f)&&(p!=null||q!=null))switch(f){case"value":de=p;break;case"defaultValue":R=p;break;case"multiple":S=p;default:p!==q&&Qt(e,t,f,p,o,q)}t=R,r=S,o=ge,de!=null?xn(e,!!r,de,!1):!!o!=!!r&&(t!=null?xn(e,!!r,t,!0):xn(e,!!r,r?[]:"",!1));return;case"textarea":ge=de=null;for(R in r)if(f=r[R],r.hasOwnProperty(R)&&f!=null&&!o.hasOwnProperty(R))switch(R){case"value":break;case"children":break;default:Qt(e,t,R,null,o,f)}for(S in o)if(f=o[S],p=r[S],o.hasOwnProperty(S)&&(f!=null||p!=null))switch(S){case"value":de=f;break;case"defaultValue":ge=f;break;case"children":break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(l(91));break;default:f!==p&&Qt(e,t,S,f,o,p)}Ur(e,de,ge);return;case"option":for(var Ze in r)de=r[Ze],r.hasOwnProperty(Ze)&&de!=null&&!o.hasOwnProperty(Ze)&&(Ze==="selected"?e.selected=!1:Qt(e,t,Ze,null,o,de));for(q in o)de=o[q],ge=r[q],o.hasOwnProperty(q)&&de!==ge&&(de!=null||ge!=null)&&(q==="selected"?e.selected=de&&typeof de!="function"&&typeof de!="symbol":Qt(e,t,q,de,o,ge));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var it in r)de=r[it],r.hasOwnProperty(it)&&de!=null&&!o.hasOwnProperty(it)&&Qt(e,t,it,null,o,de);for(ue in o)if(de=o[ue],ge=r[ue],o.hasOwnProperty(ue)&&de!==ge&&(de!=null||ge!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":if(de!=null)throw Error(l(137,t));break;default:Qt(e,t,ue,de,o,ge)}return;default:if(Pi(t)){for(var Xt in r)de=r[Xt],r.hasOwnProperty(Xt)&&de!==void 0&&!o.hasOwnProperty(Xt)&&Xm(e,t,Xt,void 0,o,de);for(we in o)de=o[we],ge=r[we],!o.hasOwnProperty(we)||de===ge||de===void 0&&ge===void 0||Xm(e,t,we,de,o,ge);return}}for(var ae in r)de=r[ae],r.hasOwnProperty(ae)&&de!=null&&!o.hasOwnProperty(ae)&&Qt(e,t,ae,null,o,de);for(ke in o)de=o[ke],ge=r[ke],!o.hasOwnProperty(ke)||de===ge||de==null&&ge==null||Qt(e,t,ke,de,o,ge)}function Lv(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function HS(){if(typeof performance.getEntriesByType=="function"){for(var e=0,t=0,r=performance.getEntriesByType("resource"),o=0;o<r.length;o++){var f=r[o],p=f.transferSize,S=f.initiatorType,R=f.duration;if(p&&R&&Lv(S)){for(S=0,R=f.responseEnd,o+=1;o<r.length;o++){var q=r[o],ue=q.startTime;if(ue>R)break;var we=q.transferSize,ke=q.initiatorType;we&&Lv(ke)&&(q=q.responseEnd,S+=we*(q<R?1:(R-ue)/(q-ue)))}if(--o,t+=8*(p+S)/(f.duration/1e3),e++,10<e)break}}if(0<e)return t/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var Zm=null,Jm=null;function Fd(e){return e.nodeType===9?e:e.ownerDocument}function _v(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function Iv(e,t){if(e===0)switch(t){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&t==="foreignObject"?0:e}function eh(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.children=="bigint"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var th=null;function PS(){var e=window.event;return e&&e.type==="popstate"?e===th?!1:(th=e,!0):(th=null,!1)}var zv=typeof setTimeout=="function"?setTimeout:void 0,FS=typeof clearTimeout=="function"?clearTimeout:void 0,Ov=typeof Promise=="function"?Promise:void 0,$S=typeof queueMicrotask=="function"?queueMicrotask:typeof Ov<"u"?function(e){return Ov.resolve(null).then(e).catch(BS)}:zv;function BS(e){setTimeout(function(){throw e})}function Cl(e){return e==="head"}function Hv(e,t){var r=t,o=0;do{var f=r.nextSibling;if(e.removeChild(r),f&&f.nodeType===8)if(r=f.data,r==="/$"||r==="/&"){if(o===0){e.removeChild(f),pc(t);return}o--}else if(r==="$"||r==="$?"||r==="$~"||r==="$!"||r==="&")o++;else if(r==="html")Su(e.ownerDocument.documentElement);else if(r==="head"){r=e.ownerDocument.head,Su(r);for(var p=r.firstChild;p;){var S=p.nextSibling,R=p.nodeName;p[Nt]||R==="SCRIPT"||R==="STYLE"||R==="LINK"&&p.rel.toLowerCase()==="stylesheet"||r.removeChild(p),p=S}}else r==="body"&&Su(e.ownerDocument.body);r=f}while(r);pc(t)}function Pv(e,t){var r=e;e=0;do{var o=r.nextSibling;if(r.nodeType===1?t?(r._stashedDisplay=r.style.display,r.style.display="none"):(r.style.display=r._stashedDisplay||"",r.getAttribute("style")===""&&r.removeAttribute("style")):r.nodeType===3&&(t?(r._stashedText=r.nodeValue,r.nodeValue=""):r.nodeValue=r._stashedText||""),o&&o.nodeType===8)if(r=o.data,r==="/$"){if(e===0)break;e--}else r!=="$"&&r!=="$?"&&r!=="$~"&&r!=="$!"||e++;r=o}while(r)}function nh(e){var t=e.firstChild;for(t&&t.nodeType===10&&(t=t.nextSibling);t;){var r=t;switch(t=t.nextSibling,r.nodeName){case"HTML":case"HEAD":case"BODY":nh(r),sa(r);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(r.rel.toLowerCase()==="stylesheet")continue}e.removeChild(r)}}function US(e,t,r,o){for(;e.nodeType===1;){var f=r;if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!o&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(o){if(!e[Nt])switch(t){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(p=e.getAttribute("rel"),p==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(p!==f.rel||e.getAttribute("href")!==(f.href==null||f.href===""?null:f.href)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin)||e.getAttribute("title")!==(f.title==null?null:f.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(p=e.getAttribute("src"),(p!==(f.src==null?null:f.src)||e.getAttribute("type")!==(f.type==null?null:f.type)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin))&&p&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(t==="input"&&e.type==="hidden"){var p=f.name==null?null:""+f.name;if(f.type==="hidden"&&e.getAttribute("name")===p)return e}else return e;if(e=Ir(e.nextSibling),e===null)break}return null}function qS(e,t,r){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!r||(e=Ir(e.nextSibling),e===null))return null;return e}function Fv(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=Ir(e.nextSibling),e===null))return null;return e}function ah(e){return e.data==="$?"||e.data==="$~"}function rh(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function GS(e,t){var r=e.ownerDocument;if(e.data==="$~")e._reactRetry=t;else if(e.data!=="$?"||r.readyState!=="loading")t();else{var o=function(){t(),r.removeEventListener("DOMContentLoaded",o)};r.addEventListener("DOMContentLoaded",o),e._reactRetry=o}}function Ir(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?"||t==="$~"||t==="&"||t==="F!"||t==="F")break;if(t==="/$"||t==="/&")return null}}return e}var sh=null;function $v(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="/$"||r==="/&"){if(t===0)return Ir(e.nextSibling);t--}else r!=="$"&&r!=="$!"&&r!=="$?"&&r!=="$~"&&r!=="&"||t++}e=e.nextSibling}return null}function Bv(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"||r==="$~"||r==="&"){if(t===0)return e;t--}else r!=="/$"&&r!=="/&"||t++}e=e.previousSibling}return null}function Uv(e,t,r){switch(t=Fd(r),e){case"html":if(e=t.documentElement,!e)throw Error(l(452));return e;case"head":if(e=t.head,!e)throw Error(l(453));return e;case"body":if(e=t.body,!e)throw Error(l(454));return e;default:throw Error(l(451))}}function Su(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);sa(e)}var zr=new Map,qv=new Set;function $d(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Ti=re.d;re.d={f:VS,r:WS,D:YS,C:KS,L:QS,m:XS,X:JS,S:ZS,M:e0};function VS(){var e=Ti.f(),t=Dd();return e||t}function WS(e){var t=bn(e);t!==null&&t.tag===5&&t.type==="form"?lg(t):Ti.r(e)}var fc=typeof document>"u"?null:document;function Gv(e,t,r){var o=fc;if(o&&typeof t=="string"&&t){var f=Ua(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof r=="string"&&(f+='[crossorigin="'+r+'"]'),qv.has(f)||(qv.add(f),e={rel:e,crossOrigin:r,href:t},o.querySelector(f)===null&&(t=o.createElement("link"),pa(t,"link",e),kt(t),o.head.appendChild(t)))}}function YS(e){Ti.D(e),Gv("dns-prefetch",e,null)}function KS(e,t){Ti.C(e,t),Gv("preconnect",e,t)}function QS(e,t,r){Ti.L(e,t,r);var o=fc;if(o&&e&&t){var f='link[rel="preload"][as="'+Ua(t)+'"]';t==="image"&&r&&r.imageSrcSet?(f+='[imagesrcset="'+Ua(r.imageSrcSet)+'"]',typeof r.imageSizes=="string"&&(f+='[imagesizes="'+Ua(r.imageSizes)+'"]')):f+='[href="'+Ua(e)+'"]';var p=f;switch(t){case"style":p=mc(e);break;case"script":p=hc(e)}zr.has(p)||(e=b({rel:"preload",href:t==="image"&&r&&r.imageSrcSet?void 0:e,as:t},r),zr.set(p,e),o.querySelector(f)!==null||t==="style"&&o.querySelector(Cu(p))||t==="script"&&o.querySelector(ku(p))||(t=o.createElement("link"),pa(t,"link",e),kt(t),o.head.appendChild(t)))}}function XS(e,t){Ti.m(e,t);var r=fc;if(r&&e){var o=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+Ua(o)+'"][href="'+Ua(e)+'"]',p=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=hc(e)}if(!zr.has(p)&&(e=b({rel:"modulepreload",href:e},t),zr.set(p,e),r.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(r.querySelector(ku(p)))return}o=r.createElement("link"),pa(o,"link",e),kt(o),r.head.appendChild(o)}}}function ZS(e,t,r){Ti.S(e,t,r);var o=fc;if(o&&e){var f=Ve(o).hoistableStyles,p=mc(e);t=t||"default";var S=f.get(p);if(!S){var R={loading:0,preload:null};if(S=o.querySelector(Cu(p)))R.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":t},r),(r=zr.get(p))&&ih(e,r);var q=S=o.createElement("link");kt(q),pa(q,"link",e),q._p=new Promise(function(ue,we){q.onload=ue,q.onerror=we}),q.addEventListener("load",function(){R.loading|=1}),q.addEventListener("error",function(){R.loading|=2}),R.loading|=4,Bd(S,t,o)}S={type:"stylesheet",instance:S,count:1,state:R},f.set(p,S)}}}function JS(e,t){Ti.X(e,t);var r=fc;if(r&&e){var o=Ve(r).hoistableScripts,f=hc(e),p=o.get(f);p||(p=r.querySelector(ku(f)),p||(e=b({src:e,async:!0},t),(t=zr.get(f))&&lh(e,t),p=r.createElement("script"),kt(p),pa(p,"link",e),r.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function e0(e,t){Ti.M(e,t);var r=fc;if(r&&e){var o=Ve(r).hoistableScripts,f=hc(e),p=o.get(f);p||(p=r.querySelector(ku(f)),p||(e=b({src:e,async:!0,type:"module"},t),(t=zr.get(f))&&lh(e,t),p=r.createElement("script"),kt(p),pa(p,"link",e),r.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function Vv(e,t,r,o){var f=(f=J.current)?$d(f):null;if(!f)throw Error(l(446));switch(e){case"meta":case"title":return null;case"style":return typeof r.precedence=="string"&&typeof r.href=="string"?(t=mc(r.href),r=Ve(f).hoistableStyles,o=r.get(t),o||(o={type:"style",instance:null,count:0,state:null},r.set(t,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(r.rel==="stylesheet"&&typeof r.href=="string"&&typeof r.precedence=="string"){e=mc(r.href);var p=Ve(f).hoistableStyles,S=p.get(e);if(S||(f=f.ownerDocument||f,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(e,S),(p=f.querySelector(Cu(e)))&&!p._p&&(S.instance=p,S.state.loading=5),zr.has(e)||(r={rel:"preload",as:"style",href:r.href,crossOrigin:r.crossOrigin,integrity:r.integrity,media:r.media,hrefLang:r.hrefLang,referrerPolicy:r.referrerPolicy},zr.set(e,r),p||t0(f,e,r,S.state))),t&&o===null)throw Error(l(528,""));return S}if(t&&o!==null)throw Error(l(529,""));return null;case"script":return t=r.async,r=r.src,typeof r=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=hc(r),r=Ve(f).hoistableScripts,o=r.get(t),o||(o={type:"script",instance:null,count:0,state:null},r.set(t,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(l(444,e))}}function mc(e){return'href="'+Ua(e)+'"'}function Cu(e){return'link[rel="stylesheet"]['+e+"]"}function Wv(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function t0(e,t,r,o){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?o.loading=1:(t=e.createElement("link"),o.preload=t,t.addEventListener("load",function(){return o.loading|=1}),t.addEventListener("error",function(){return o.loading|=2}),pa(t,"link",r),kt(t),e.head.appendChild(t))}function hc(e){return'[src="'+Ua(e)+'"]'}function ku(e){return"script[async]"+e}function Yv(e,t,r){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+Ua(r.href)+'"]');if(o)return t.instance=o,kt(o),o;var f=b({},r,{"data-href":r.href,"data-precedence":r.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),kt(o),pa(o,"style",f),Bd(o,r.precedence,e),t.instance=o;case"stylesheet":f=mc(r.href);var p=e.querySelector(Cu(f));if(p)return t.state.loading|=4,t.instance=p,kt(p),p;o=Wv(r),(f=zr.get(f))&&ih(o,f),p=(e.ownerDocument||e).createElement("link"),kt(p);var S=p;return S._p=new Promise(function(R,q){S.onload=R,S.onerror=q}),pa(p,"link",o),t.state.loading|=4,Bd(p,r.precedence,e),t.instance=p;case"script":return p=hc(r.src),(f=e.querySelector(ku(p)))?(t.instance=f,kt(f),f):(o=r,(f=zr.get(p))&&(o=b({},r),lh(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),kt(f),pa(f,"link",o),e.head.appendChild(f),t.instance=f);case"void":return null;default:throw Error(l(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(o=t.instance,t.state.loading|=4,Bd(o,r.precedence,e));return t.instance}function Bd(e,t,r){for(var o=r.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=o.length?o[o.length-1]:null,p=f,S=0;S<o.length;S++){var R=o[S];if(R.dataset.precedence===t)p=R;else if(p!==f)break}p?p.parentNode.insertBefore(e,p.nextSibling):(t=r.nodeType===9?r.head:r,t.insertBefore(e,t.firstChild))}function ih(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function lh(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var Ud=null;function Kv(e,t,r){if(Ud===null){var o=new Map,f=Ud=new Map;f.set(r,o)}else f=Ud,o=f.get(r),o||(o=new Map,f.set(r,o));if(o.has(e))return o;for(o.set(e,null),r=r.getElementsByTagName(e),f=0;f<r.length;f++){var p=r[f];if(!(p[Nt]||p[se]||e==="link"&&p.getAttribute("rel")==="stylesheet")&&p.namespaceURI!=="http://www.w3.org/2000/svg"){var S=p.getAttribute(t)||"";S=e+S;var R=o.get(S);R?R.push(p):o.set(S,[p])}}return o}function Qv(e,t,r){e=e.ownerDocument||e,e.head.insertBefore(r,t==="title"?e.querySelector("head > title"):null)}function n0(e,t,r){if(r===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function Xv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function a0(e,t,r,o){if(r.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(r.state.loading&4)===0){if(r.instance===null){var f=mc(o.href),p=t.querySelector(Cu(f));if(p){t=p._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=qd.bind(e),t.then(e,e)),r.state.loading|=4,r.instance=p,kt(p);return}p=t.ownerDocument||t,o=Wv(o),(f=zr.get(f))&&ih(o,f),p=p.createElement("link"),kt(p);var S=p;S._p=new Promise(function(R,q){S.onload=R,S.onerror=q}),pa(p,"link",o),r.instance=p}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(r,t),(t=r.state.preload)&&(r.state.loading&3)===0&&(e.count++,r=qd.bind(e),t.addEventListener("load",r),t.addEventListener("error",r))}}var oh=0;function r0(e,t){return e.stylesheets&&e.count===0&&Vd(e,e.stylesheets),0<e.count||0<e.imgCount?function(r){var o=setTimeout(function(){if(e.stylesheets&&Vd(e,e.stylesheets),e.unsuspend){var p=e.unsuspend;e.unsuspend=null,p()}},6e4+t);0<e.imgBytes&&oh===0&&(oh=62500*HS());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Vd(e,e.stylesheets),e.unsuspend)){var p=e.unsuspend;e.unsuspend=null,p()}},(e.imgBytes>oh?50:800)+t);return e.unsuspend=r,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function qd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Gd=null;function Vd(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Gd=new Map,t.forEach(s0,e),Gd=null,qd.call(e))}function s0(e,t){if(!(t.state.loading&4)){var r=Gd.get(e);if(r)var o=r.get(null);else{r=new Map,Gd.set(e,r);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p<f.length;p++){var S=f[p];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(r.set(S.dataset.precedence,S),o=S)}o&&r.set(null,o)}f=t.instance,S=f.getAttribute("data-precedence"),p=r.get(S)||o,p===o&&r.set(null,f),r.set(S,f),this.count++,o=qd.bind(this),f.addEventListener("load",o),f.addEventListener("error",o),p?p.parentNode.insertBefore(f,p.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(f,e.firstChild)),t.state.loading|=4}}var ju={$$typeof:L,Provider:null,Consumer:null,_currentValue:V,_currentValue2:V,_threadCount:0};function i0(e,t,r,o,f,p,S,R,q){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=an(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=an(0),this.hiddenUpdates=an(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=p,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=q,this.incompleteTransitions=new Map}function Zv(e,t,r,o,f,p,S,R,q,ue,we,ke){return e=new i0(e,t,r,S,q,ue,we,ke,R),t=1,p===!0&&(t|=24),p=ca(3,null,null,t),e.current=p,p.stateNode=e,t=$o(),t.refCount++,e.pooledCache=t,t.refCount++,p.memoizedState={element:o,isDehydrated:r,cache:t},Zc(p),e}function Jv(e){return e?(e=Zn,e):Zn}function ey(e,t,r,o,f,p){f=Jv(f),o.context===null?o.context=f:o.pendingContext=f,o=Rs(t),o.payload={element:r},p=p===void 0?null:p,p!==null&&(o.callback=p),r=Rr(e,o,t),r!==null&&(ar(r,e,t),pi(r,e,t))}function ty(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var r=e.retryLane;e.retryLane=r!==0&&r<t?r:t}}function ch(e,t){ty(e,t),(e=e.alternate)&&ty(e,t)}function ny(e){if(e.tag===13||e.tag===31){var t=ps(e,67108864);t!==null&&ar(t,e,67108864),ch(e,67108864)}}function ay(e){if(e.tag===13||e.tag===31){var t=gr();t=dt(t);var r=ps(e,t);r!==null&&ar(r,e,t),ch(e,t)}}var Wd=!0;function l0(e,t,r,o){var f=z.T;z.T=null;var p=re.p;try{re.p=2,uh(e,t,r,o)}finally{re.p=p,z.T=f}}function o0(e,t,r,o){var f=z.T;z.T=null;var p=re.p;try{re.p=8,uh(e,t,r,o)}finally{re.p=p,z.T=f}}function uh(e,t,r,o){if(Wd){var f=dh(o);if(f===null)Qm(e,t,o,Yd,r),sy(e,o);else if(u0(f,e,t,r,o))o.stopPropagation();else if(sy(e,o),t&4&&-1<c0.indexOf(e)){for(;f!==null;){var p=bn(f);if(p!==null)switch(p.tag){case 3:if(p=p.stateNode,p.current.memoizedState.isDehydrated){var S=Fn(p.pendingLanes);if(S!==0){var R=p;for(R.pendingLanes|=2,R.entangledLanes|=2;S;){var q=1<<31-wt(S);R.entanglements[1]|=q,S&=~q}Ls(p),(Bt&6)===0&&(Rd=je()+500,bu(0))}}break;case 31:case 13:R=ps(p,2),R!==null&&ar(R,p,2),Dd(),ch(p,2)}if(p=dh(o),p===null&&Qm(e,t,o,Yd,r),p===f)break;f=p}f!==null&&o.stopPropagation()}else Qm(e,t,o,null,r)}}function dh(e){return e=Cr(e),fh(e)}var Yd=null;function fh(e){if(Yd=null,e=$n(e),e!==null){var t=u(e);if(t===null)e=null;else{var r=t.tag;if(r===13){if(e=m(t),e!==null)return e;e=null}else if(r===31){if(e=h(t),e!==null)return e;e=null}else if(r===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}}return Yd=e,null}function ry(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Fe()){case ut:return 2;case tt:return 8;case vt:case st:return 32;case xt:return 268435456;default:return 32}default:return 32}}var mh=!1,kl=null,jl=null,Ml=null,Mu=new Map,Au=new Map,Al=[],c0="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function sy(e,t){switch(e){case"focusin":case"focusout":kl=null;break;case"dragenter":case"dragleave":jl=null;break;case"mouseover":case"mouseout":Ml=null;break;case"pointerover":case"pointerout":Mu.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Au.delete(t.pointerId)}}function Nu(e,t,r,o,f,p){return e===null||e.nativeEvent!==p?(e={blockedOn:t,domEventName:r,eventSystemFlags:o,nativeEvent:p,targetContainers:[f]},t!==null&&(t=bn(t),t!==null&&ny(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,f!==null&&t.indexOf(f)===-1&&t.push(f),e)}function u0(e,t,r,o,f){switch(t){case"focusin":return kl=Nu(kl,e,t,r,o,f),!0;case"dragenter":return jl=Nu(jl,e,t,r,o,f),!0;case"mouseover":return Ml=Nu(Ml,e,t,r,o,f),!0;case"pointerover":var p=f.pointerId;return Mu.set(p,Nu(Mu.get(p)||null,e,t,r,o,f)),!0;case"gotpointercapture":return p=f.pointerId,Au.set(p,Nu(Au.get(p)||null,e,t,r,o,f)),!0}return!1}function iy(e){var t=$n(e.target);if(t!==null){var r=u(t);if(r!==null){if(t=r.tag,t===13){if(t=m(r),t!==null){e.blockedOn=t,Ii(e.priority,function(){ay(r)});return}}else if(t===31){if(t=h(r),t!==null){e.blockedOn=t,Ii(e.priority,function(){ay(r)});return}}else if(t===3&&r.stateNode.current.memoizedState.isDehydrated){e.blockedOn=r.tag===3?r.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Kd(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var r=dh(e.nativeEvent);if(r===null){r=e.nativeEvent;var o=new r.constructor(r.type,r);Vr=o,r.target.dispatchEvent(o),Vr=null}else return t=bn(r),t!==null&&ny(t),e.blockedOn=r,!1;t.shift()}return!0}function ly(e,t,r){Kd(e)&&r.delete(t)}function d0(){mh=!1,kl!==null&&Kd(kl)&&(kl=null),jl!==null&&Kd(jl)&&(jl=null),Ml!==null&&Kd(Ml)&&(Ml=null),Mu.forEach(ly),Au.forEach(ly)}function Qd(e,t){e.blockedOn===t&&(e.blockedOn=null,mh||(mh=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,d0)))}var Xd=null;function oy(e){Xd!==e&&(Xd=e,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){Xd===e&&(Xd=null);for(var t=0;t<e.length;t+=3){var r=e[t],o=e[t+1],f=e[t+2];if(typeof o!="function"){if(fh(o||r)===null)continue;break}var p=bn(r);p!==null&&(e.splice(t,3),t-=3,dm(p,{pending:!0,data:f,method:r.method,action:o},o,f))}}))}function pc(e){function t(q){return Qd(q,e)}kl!==null&&Qd(kl,e),jl!==null&&Qd(jl,e),Ml!==null&&Qd(Ml,e),Mu.forEach(t),Au.forEach(t);for(var r=0;r<Al.length;r++){var o=Al[r];o.blockedOn===e&&(o.blockedOn=null)}for(;0<Al.length&&(r=Al[0],r.blockedOn===null);)iy(r),r.blockedOn===null&&Al.shift();if(r=(e.ownerDocument||e).$$reactFormReplay,r!=null)for(o=0;o<r.length;o+=3){var f=r[o],p=r[o+1],S=f[Ee]||null;if(typeof p=="function")S||oy(r);else if(S){var R=null;if(p&&p.hasAttribute("formAction")){if(f=p,S=p[Ee]||null)R=S.formAction;else if(fh(f)!==null)continue}else R=S.action;typeof R=="function"?r[o+1]=R:(r.splice(o,3),o-=3),oy(r)}}}function cy(){function e(p){p.canIntercept&&p.info==="react-transition"&&p.intercept({handler:function(){return new Promise(function(S){return f=S})},focusReset:"manual",scroll:"manual"})}function t(){f!==null&&(f(),f=null),o||setTimeout(r,20)}function r(){if(!o&&!navigation.transition){var p=navigation.currentEntry;p&&p.url!=null&&navigation.navigate(p.url,{state:p.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var o=!1,f=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",t),navigation.addEventListener("navigateerror",t),setTimeout(r,100),function(){o=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",t),navigation.removeEventListener("navigateerror",t),f!==null&&(f(),f=null)}}}function hh(e){this._internalRoot=e}Zd.prototype.render=hh.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(l(409));var r=t.current,o=gr();ey(r,o,e,t,null,null)},Zd.prototype.unmount=hh.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;ey(e.current,2,null,e,null,null),Dd(),t[Ge]=null}};function Zd(e){this._internalRoot=e}Zd.prototype.unstable_scheduleHydration=function(e){if(e){var t=Ba();e={blockedOn:null,target:e,priority:t};for(var r=0;r<Al.length&&t!==0&&t<Al[r].priority;r++);Al.splice(r,0,e),r===0&&iy(e)}};var uy=a.version;if(uy!=="19.2.7")throw Error(l(527,uy,"19.2.7"));re.findDOMNode=function(e){var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(l(188)):(e=Object.keys(e).join(","),Error(l(268,e)));return e=y(t),e=e!==null?x(e):null,e=e===null?null:e.stateNode,e};var f0={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:z,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Jd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Jd.isDisabled&&Jd.supportsFiber)try{Pe=Jd.inject(f0),Re=Jd}catch{}}return Ru.createRoot=function(e,t){if(!c(e))throw Error(l(299));var r=!1,o="",f=vg,p=yg,S=bg;return t!=null&&(t.unstable_strictMode===!0&&(r=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onUncaughtError!==void 0&&(f=t.onUncaughtError),t.onCaughtError!==void 0&&(p=t.onCaughtError),t.onRecoverableError!==void 0&&(S=t.onRecoverableError)),t=Zv(e,1,!1,null,null,r,o,null,f,p,S,cy),e[Ge]=t.current,Km(e),new hh(t)},Ru.hydrateRoot=function(e,t,r){if(!c(e))throw Error(l(299));var o=!1,f="",p=vg,S=yg,R=bg,q=null;return r!=null&&(r.unstable_strictMode===!0&&(o=!0),r.identifierPrefix!==void 0&&(f=r.identifierPrefix),r.onUncaughtError!==void 0&&(p=r.onUncaughtError),r.onCaughtError!==void 0&&(S=r.onCaughtError),r.onRecoverableError!==void 0&&(R=r.onRecoverableError),r.formState!==void 0&&(q=r.formState)),t=Zv(e,1,!0,t,r??null,o,f,q,p,S,R,cy),t.context=Jv(null),r=t.current,o=gr(),o=dt(o),f=Rs(o),f.callback=null,Rr(r,f,o),r=o,t.current.lanes=r,Fr(t,r),Ls(t),e[Ge]=t.current,Km(e),new Zd(t)},Ru.version="19.2.7",Ru}var ky;function rC(){if(ky)return yh.exports;ky=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(a){console.error(a)}}return n(),yh.exports=aC(),yh.exports}var sC=rC();const iC="https://otbyfkjxrkngvjziawki.supabase.co",lC="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",oC={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},jy=typeof window<"u"&&!!window.liveDesk,bt=Z0(iC,lC,{auth:{autoRefreshToken:!0,persistSession:!jy,storage:jy?oC:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),cC=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),uC={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const n={browserLanguage:navigator.language||"",platform:navigator.platform||"",online:navigator.onLine,timezone:typeof Intl>"u"?"":Intl.DateTimeFormat().resolvedOptions().timeZone||"",viewport:typeof window>"u"?void 0:{width:window.innerWidth,height:window.innerHeight},screen:typeof window>"u"?void 0:{width:window.screen.width,height:window.screen.height}};return Object.fromEntries(Object.entries(n).filter(([a,s])=>cC.has(a)&&s!==void 0))}};function dC(n,a="Support request failed."){if(n&&typeof n=="object"&&"message"in n){const s=String(n.message||"").trim();if(s)return s.replace(/^.*Support request failed:\s*/i,"")}return n instanceof Error?n.message:a}function fC(n=uC){return n.collect()}async function mC(n,a="livedesk"){const{data:s,error:l}=await bt.from("app_admins").select("role").eq("user_id",n).limit(1);if(l)throw l;const c=s?.[0]?.role||"user";if(c!=="owner"){const{error:j}=await bt.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(j)throw j}const[u,m,h]=await Promise.all([bt.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),bt.from("product_admins").select("product_id, role").eq("user_id",n),bt.from("user_products").select("product_id").eq("user_id",n).eq("is_active",!0)]);if(u.error)throw u.error;if(m.error)throw m.error;if(h.error)throw h.error;const g=u.data||[],y=(m.data||[]).map(j=>String(j.product_id)),x=(h.data||[]).map(j=>String(j.product_id)),b=c==="owner",w=b?g.map(j=>j.id):[...new Set([...y,...x])];return{products:g,access:{userId:n,globalRole:c,accessibleProductIds:w,managedProductIds:b?g.map(j=>j.id):y,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||y.length>0}}}async function hC(n=""){const{data:a,error:s}=await bt.rpc("search_support_posts",{p_query:n.trim()||null,p_limit:250});if(s)throw s;return a||[]}async function pC(n){const{data:a,error:s}=await bt.from("support_attachments").select("*").eq("post_id",n).order("created_at");if(s)throw s;const l=a||[];return Promise.all(l.map(async c=>{const u=await bt.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:u.data?.signedUrl||void 0}}))}async function gC(){const{data:n,error:a}=await bt.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return n||[]}async function vC(n){const{error:a}=await bt.rpc("mark_support_notification_read",{p_notification_id:n});if(a)throw a}async function My(n){const{data:a,error:s}=await bt.from("support_comments").select("*").eq("post_id",n).order("created_at");if(s)throw s;return a||[]}async function yC(n){const{data:a,error:s}=await bt.from("support_votes").select("post_id").eq("user_id",n);if(s)throw s;return new Set((a||[]).map(l=>String(l.post_id)))}async function bC(n){const{data:a,error:s}=await bt.rpc("create_support_post",{p_product_id:n.productId,p_post_type:n.postType,p_title:n.title,p_body:n.body,p_visibility:n.visibility,p_app_version:n.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:n.includeEnvironment?fC():{}});if(s)throw s;const l=Array.isArray(a)?a[0]?.post_id:a?.post_id;if(!l)throw new Error("Support post was not created.");return String(l)}const xC=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function wC(n,a){if(!xC.has(a.type))throw new Error("This file type is not allowed.");if(a.size<=0||a.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const s=a.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",l=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,c=`${n}/${l}-${s}`,u=await bt.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(u.error)throw u.error;const{data:m,error:h}=await bt.rpc("add_support_attachment",{p_post_id:n,p_storage_path:c,p_file_name:s,p_mime_type:a.type,p_size_bytes:a.size});if(h)throw await bt.storage.from("support-attachments").remove([c]),h;const g=Array.isArray(m)?m[0]?.attachment_id:m?.attachment_id;if(!g)throw new Error("Attachment metadata was not created.");return String(g)}async function SC(n,a,s,l){const{error:c}=await bt.rpc("update_support_post",{p_post_id:n,p_title:a,p_body:s,p_visibility:l});if(c)throw c}async function CC(n,a){const{error:s}=await bt.rpc("add_support_comment",{p_post_id:n,p_body:a});if(s)throw s}async function kC(n){const{data:a,error:s}=await bt.rpc("toggle_support_vote",{p_post_id:n});if(s)throw s;const l=Array.isArray(a)?a[0]:a;return{voted:!!l?.voted,totalVotes:Number(l?.total_votes||0)}}async function jC(n,a){const{error:s}=await bt.rpc("change_support_post_status",{p_post_id:n,p_target_status:a});if(s)throw s}async function MC(n){const{error:a}=await bt.rpc("set_support_post_hidden",{p_post_id:n,p_hidden:!0});if(a)throw a}async function AC(n,a){const{error:s}=await bt.rpc("set_support_post_locked",{p_post_id:n,p_locked:a});if(s)throw s}async function NC(n,a){const{error:s}=await bt.rpc("set_support_post_pinned",{p_post_id:n,p_pinned:a});if(s)throw s}async function TC(n,a){const{error:s}=await bt.rpc("mark_support_duplicate",{p_post_id:n,p_duplicate_of_post_id:a});if(s)throw s}async function RC(n,a){const{error:s}=await bt.rpc("accept_support_answer",{p_post_id:n,p_comment_id:a});if(s)throw s}async function EC(n,a=!0){const{error:s}=await bt.rpc("hide_support_comment",{p_comment_id:n,p_hidden:a});if(s)throw s}const np=[{id:"question",label:"Questions",shortLabel:"Question"},{id:"issue",label:"Issues",shortLabel:"Issue"},{id:"feature",label:"Feature Requests",shortLabel:"Feature"},{id:"announcement",label:"Announcements",shortLabel:"Announcement"}],DC=[{id:"all",label:"All statuses"},{id:"needs-response",label:"Needs response"},{id:"open",label:"Open"},{id:"needs-info",label:"Needs more information"},{id:"in-progress",label:"In progress"},{id:"planned",label:"Planned"},{id:"released",label:"Released"},{id:"closed",label:"Closed"}],LC={question:["open","answered","resolved","closed"],issue:["open","needs-info","confirmed","in-progress","fixed","closed"],feature:["under-review","planned","in-progress","released","declined","closed"],announcement:["published","archived"]},_C={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function wh(){if(typeof window>"u")return _C;const n=new URLSearchParams(window.location.search),a=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],s=n.get("type")||a||"",l=s==="questions"||s==="question"?"question":s==="issues"||s==="issue"?"issue":s==="features"||s==="feature"?"feature":s==="announcements"||s==="announcement"?"announcement":"all",c=n.get("visibility"),u=n.get("sort");return{type:l,product:n.get("product")||"",status:n.get("status")||"all",visibility:c==="public"||c==="private"?c:"all",sort:u==="votes"||u==="newest"?u:"recent",query:n.get("q")||""}}function IC(n){return n==="all"?"":n==="question"?"questions":n==="issue"?"issues":n==="feature"?"features":"announcements"}function zC(n,a){const s={...n,...a},l=new URLSearchParams;s.product&&l.set("product",s.product),s.status!=="all"&&l.set("status",s.status),s.visibility!=="all"&&l.set("visibility",s.visibility),s.sort!=="recent"&&l.set("sort",s.sort),s.query&&l.set("q",s.query);const c=IC(s.type),u=l.toString();return`/support${c?`/${c}`:""}${u?`?${u}`:""}`}function ef(n){const a=new Date(n);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):n}function Sh(n){return n.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function Ay(n){return n==="question"?y0:n==="issue"?fx:n==="feature"?b0:x0}function Ny(n){return np.find(a=>a.id===n)?.shortLabel||n}function Ch(n,a){return n.find(s=>s.id===a)?.name||"Product"}function rr(n){const a=dC(n);return/relation .* does not exist|function .* does not exist|schema cache/i.test(a)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(a)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(a)?"You do not have access to this product.":a}function jx({session:n,currentProductKey:a="livedesk",appVersion:s="",onSignIn:l}){const[c,u]=d.useState(()=>wh()),[m,h]=d.useState(null),[g,y]=d.useState([]),[x,b]=d.useState([]),[w,j]=d.useState(""),[M,k]=d.useState([]),[N,A]=d.useState([]),[T,L]=d.useState([]),[O,I]=d.useState(()=>new Set),[B,_]=d.useState(!0),[G,te]=d.useState(""),[W,Y]=d.useState(""),[F,ve]=d.useState(!1),[fe,Q]=d.useState(!1),[z,re]=d.useState(""),[V,H]=d.useState(()=>wh().query),[le,oe]=d.useState(!1),[X,be]=d.useState(!1),[me,he]=d.useState(""),[J,Ce]=d.useState(""),[Te,He]=d.useState("free"),[ee,Ue]=d.useState(""),[ft,ne]=d.useState(""),[xe,Oe]=d.useState("admin"),[$e,ze]=d.useState(""),[Qe,qe]=d.useState(""),[We,lt]=d.useState(""),[U,ye]=d.useState(""),[je,Fe]=d.useState(""),[ut,tt]=d.useState([]),[vt,st]=d.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),xt=d.useCallback($=>{const Xe={...c,...$};u(Xe),typeof window<"u"&&window.history.pushState({},"",zC(c,$))},[c]);d.useEffect(()=>{const $=()=>u(wh());return window.addEventListener("popstate",$),()=>window.removeEventListener("popstate",$)},[]);const pe=d.useCallback(async()=>{const $=await hC(c.query);return b($),n?.user.id&&I(await yC(n.user.id)),$},[c.query,n?.user.id]),Le=d.useCallback(async()=>{if(!n?.user.id){h(null),y([]),b([]),j(""),L([]),_(!1);return}_(!0),Y("");try{const $=await mC(n.user.id,a);h($.access),y($.products),await pe(),L(await gC())}catch($){Y(rr($))}finally{_(!1)}},[a,pe,n?.user.id]);d.useEffect(()=>{Le()},[Le]);const Pe=d.useMemo(()=>m?m.canViewAllProducts?g:g.filter($=>m.accessibleProductIds.includes($.id)):[],[m,g]),Re=d.useMemo(()=>{const $=Pe.find(Xe=>Xe.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":$?$.product_key:Pe.some(Xe=>Xe.product_key===a)?a:Pe[0]?.product_key||""},[m?.canViewAllProducts,Pe,a,c.product]),ot=Re==="all"?"":Pe.find($=>$.product_key===Re)?.id||"",wt=d.useMemo(()=>{const $=new Map(g.map(dt=>[dt.id,dt.product_key]));return[...x.filter(dt=>c.type!=="all"&&dt.post_type!==c.type||Re!=="all"&&ot&&dt.product_id!==ot||c.status==="needs-response"&&!["open","needs-info"].includes(dt.status)||c.status!=="all"&&c.status!=="needs-response"&&dt.status!==c.status||c.visibility!=="all"&&dt.visibility!==c.visibility?!1:$.has(dt.product_id))].sort((dt,hn)=>c.sort==="votes"?hn.vote_count-dt.vote_count||hn.updated_at.localeCompare(dt.updated_at):c.sort==="newest"?hn.created_at.localeCompare(dt.created_at):Number(hn.is_pinned)-Number(dt.is_pinned)||hn.updated_at.localeCompare(dt.updated_at))},[x,g,c.sort,c.status,c.type,c.visibility,ot,Re]),De=wt.find($=>$.id===w)||wt[0]||null,Hn=!!(De&&m&&(m.canViewAllProducts||m.managedProductIds.includes(De.product_id))),_t=!!(De&&n?.user.id===De.author_id)||Hn;d.useEffect(()=>{if(!De){j(""),k([]),Q(!1);return}De.id!==w&&j(De.id)},[De,w]),d.useEffect(()=>{let $=!0;return w?(My(w).then(Xe=>{$&&k(Xe)}).catch(Xe=>{$&&Y(rr(Xe))}),pC(w).then(Xe=>{$&&A(Xe)}).catch(Xe=>{$&&Y(rr(Xe))}),()=>{$=!1}):(k([]),A([]),()=>{$=!1})},[w]),d.useEffect(()=>{!vt.productId&&Pe[0]&&st($=>({...$,productId:ot||Pe[0].id}))},[Pe,vt.productId,ot]),d.useEffect(()=>{H(c.query)},[c.query]),d.useEffect(()=>{!J&&Pe[0]&&Ce(Pe[0].id),!ft&&Pe[0]&&ne(Pe[0].id)},[Pe,J,ft]);const Ot=$=>{De&&b(Xe=>Xe.map(dt=>dt.id===De.id?{...dt,...$}:dt))},$t=async $=>{if($.preventDefault(),!(!n||!vt.productId)){te("create"),Y("");try{const Xe=await bC({productId:vt.productId,postType:vt.postType,title:vt.title,body:vt.body,visibility:vt.postType==="announcement"?"public":vt.visibility,appVersion:s,includeEnvironment:vt.postType==="issue"&&vt.includeEnvironment});for(const hn of ut)await wC(Xe,hn);const dt=await pe();ve(!1),tt([]),st(hn=>({...hn,title:"",body:"",files:[]})),j(Xe),dt.some(hn=>hn.id===Xe)||await Le()}catch(Xe){Y(rr(Xe))}finally{te("")}}},Pn=async $=>{if($.preventDefault(),!!De){te("edit"),Y("");try{await SC(De.id,De.title,De.body,De.visibility),Q(!1),await pe()}catch(Xe){Y(rr(Xe))}finally{te("")}}},Fn=async $=>{if($.preventDefault(),!(!De||!z.trim())){te("comment"),Y("");try{await CC(De.id,z),re(""),k(await My(De.id)),await pe()}catch(Xe){Y(rr(Xe))}finally{te("")}}},_e=async()=>{if(!(!De||De.post_type!=="feature")){te("vote"),Y("");try{const $=await kC(De.id);I(Xe=>{const dt=new Set(Xe);return $.voted?dt.add(De.id):dt.delete(De.id),dt}),Ot({vote_count:$.totalVotes})}catch($){Y(rr($))}finally{te("")}}},nn=async $=>{if(De){te("status"),Y("");try{await jC(De.id,$),Ot({status:$}),await pe()}catch(Xe){Y(rr(Xe))}finally{te("")}}},cn=async()=>{if(!(!De||!window.confirm("Hide this Support post from the board?"))){te("hide"),Y("");try{await MC(De.id),j(""),await pe()}catch($){Y(rr($))}finally{te("")}}},Da=async()=>{if(De){te("lock"),Y("");try{await AC(De.id,!De.is_locked),Ot({is_locked:!De.is_locked}),await pe()}catch($){Y(rr($))}finally{te("")}}},an=async()=>{if(De){te("pin"),Y("");try{await NC(De.id,!De.is_pinned),Ot({is_pinned:!De.is_pinned}),await pe()}catch($){Y(rr($))}finally{te("")}}},Fr=async $=>{if(De){te(`accept-${$}`),Y("");try{await RC(De.id,$),Ot({accepted_comment_id:$,status:De.post_type==="question"?"answered":De.status}),await pe()}catch(Xe){Y(rr(Xe))}finally{te("")}}},Kn=async()=>{if(!(!De||!U||U===De.id)){te("duplicate"),Y("");try{await TC(De.id,U),j(""),ye(""),await pe()}catch($){Y(rr($))}finally{te("")}}},$r=async $=>{if(!$.read_at)try{await vC($.id),L(Xe=>Xe.map(dt=>dt.id===$.id?{...dt,read_at:new Date().toISOString()}:dt))}catch(Xe){Y(rr(Xe))}$.post_id&&j($.post_id),oe(!1)};return n?B&&!m?i.jsxs("section",{className:"support-page support-loading",children:[i.jsx(Ac,{className:"support-spin",size:23})," Loading Support Board..."]}):i.jsxs("section",{className:"support-page",children:[i.jsx("header",{className:"support-page-header support-page-actions-only",children:i.jsxs("div",{className:"support-header-actions",children:[i.jsxs("div",{className:"support-notification-wrap",children:[i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>oe($=>!$),title:"Notifications",children:[i.jsx(p0,{size:16})," ",T.filter($=>!$.read_at).length>0&&i.jsx("b",{children:T.filter($=>!$.read_at).length})]}),le&&i.jsxs("div",{className:"support-notification-popover",children:[i.jsx("strong",{children:"Notifications"}),T.length===0?i.jsx("span",{className:"support-muted",children:"No notifications yet."}):T.map($=>i.jsxs("button",{type:"button",className:$.read_at?"":"unread",onClick:()=>{$r($)},children:[i.jsx("b",{children:$.title}),i.jsx("span",{children:$.body}),i.jsx("small",{children:ef($.created_at)})]},$.id))]})]}),m?.canViewAllProducts&&i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>be($=>!$),children:[i.jsx(Yn,{size:16})," Admin"]}),i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Le()},disabled:B,children:[i.jsx(Ac,{size:16,className:B?"support-spin":""})," Refresh"]}),i.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>ve(!0),disabled:Pe.length===0,children:[i.jsx(ph,{size:17})," New request"]})]})}),W&&i.jsxs("div",{className:"support-error",role:"alert",children:[i.jsx(Ra,{size:17})," ",i.jsx("span",{children:W}),i.jsx("button",{type:"button",onClick:()=>Y(""),"aria-label":"Dismiss error",children:i.jsx(Ra,{size:15})})]}),F&&i.jsxs("form",{className:"support-composer",onSubmit:$=>{$t($)},children:[i.jsxs("div",{className:"support-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"New Support request"}),i.jsx("strong",{children:"Describe one actionable problem or idea."})]}),i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ve(!1),"aria-label":"Close composer",children:i.jsx(Ra,{size:18})})]}),i.jsxs("div",{className:"support-form-grid",children:[i.jsxs("label",{children:[i.jsx("span",{children:"Product"}),i.jsx("select",{value:vt.productId,onChange:$=>st(Xe=>({...Xe,productId:$.target.value})),children:Pe.map($=>i.jsx("option",{value:$.id,children:$.name},$.id))})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Type"}),i.jsx("select",{value:vt.postType,onChange:$=>st(Xe=>({...Xe,postType:$.target.value})),children:np.filter($=>$.id!=="announcement"||m?.canCreateAnnouncements).map($=>i.jsx("option",{value:$.id,children:$.label},$.id))})]}),i.jsxs("label",{className:"support-form-wide",children:[i.jsx("span",{children:"Title"}),i.jsx("input",{required:!0,minLength:3,maxLength:180,value:vt.title,onChange:$=>st(Xe=>({...Xe,title:$.target.value})),placeholder:"A short, searchable summary"})]}),i.jsxs("label",{className:"support-form-wide",children:[i.jsx("span",{children:vt.postType==="issue"?"What happened?":vt.postType==="feature"?"Describe the desired behavior":vt.postType==="announcement"?"Announcement":"Question"}),i.jsx("textarea",{required:!0,value:vt.body,onChange:$=>st(Xe=>({...Xe,body:$.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Visibility"}),i.jsxs("select",{value:vt.visibility,disabled:vt.postType==="announcement",onChange:$=>st(Xe=>({...Xe,visibility:$.target.value})),children:[i.jsx("option",{value:"public",children:"Public"}),i.jsx("option",{value:"private",children:"Private"})]})]}),vt.postType==="issue"&&i.jsxs("label",{className:"support-checkbox",children:[i.jsx("input",{type:"checkbox",checked:vt.includeEnvironment,onChange:$=>st(Xe=>({...Xe,includeEnvironment:$.target.checked}))}),i.jsx("span",{children:"Attach safe browser/runtime details"})]}),i.jsxs("label",{className:"support-form-wide",children:[i.jsx("span",{children:"Attachments"}),i.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:$=>tt(Array.from($.target.files||[]).slice(0,5))}),i.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),i.jsxs("div",{className:"support-composer-footer",children:[i.jsx("span",{children:ut.length>0?`${ut.length} attachment${ut.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),i.jsxs("button",{className:"support-primary-button",type:"submit",disabled:G==="create",children:[i.jsx(Vu,{size:16})," ",G==="create"?"Submitting...":"Submit request"]})]})]}),i.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[i.jsx("button",{className:c.type==="all"?"active":"",type:"button",onClick:()=>xt({type:"all"}),children:"All"}),np.map($=>{const Xe=Ay($.id);return i.jsxs("button",{className:c.type===$.id?"active":"",type:"button",onClick:()=>xt({type:$.id}),children:[i.jsx(Xe,{size:15})," ",$.label]},$.id)})]}),X&&m?.canViewAllProducts&&i.jsxs("section",{className:"support-admin-panel",children:[i.jsxs("div",{className:"support-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Owner controls"}),i.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),i.jsx(Yn,{size:19})]}),i.jsxs("div",{className:"support-admin-grid",children:[i.jsxs("form",{onSubmit:$=>{},children:[i.jsx("strong",{children:"Grant product access"}),i.jsx("input",{type:"email",required:!0,placeholder:"User email",value:me,onChange:$=>he($.target.value)}),i.jsx("select",{value:J,onChange:$=>Ce($.target.value),children:Pe.map($=>i.jsx("option",{value:$.id,children:$.name},$.id))}),i.jsxs("select",{value:Te,onChange:$=>He($.target.value),children:[i.jsx("option",{value:"free",children:"Free"}),i.jsx("option",{value:"user",children:"User"}),i.jsx("option",{value:"paid",children:"Paid"}),i.jsx("option",{value:"beta",children:"Beta"}),i.jsx("option",{value:"staff",children:"Staff"})]}),i.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="access",children:[i.jsx(Os,{size:15})," Grant access"]})]}),i.jsxs("form",{onSubmit:$=>{},children:[i.jsx("strong",{children:"Assign product admin"}),i.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:ee,onChange:$=>Ue($.target.value)}),i.jsx("select",{value:ft,onChange:$=>ne($.target.value),children:Pe.map($=>i.jsx("option",{value:$.id,children:$.name},$.id))}),i.jsxs("select",{value:xe,onChange:$=>Oe($.target.value),children:[i.jsx("option",{value:"admin",children:"Admin"}),i.jsx("option",{value:"support",children:"Support"}),i.jsx("option",{value:"moderator",children:"Moderator"})]}),i.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="product-admin",children:[i.jsx(Yn,{size:15})," Assign admin"]})]}),i.jsxs("form",{onSubmit:$=>{},children:[i.jsx("strong",{children:"Add a product"}),i.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:$e,onChange:$=>ze($.target.value)}),i.jsx("input",{required:!0,placeholder:"Product name",value:Qe,onChange:$=>qe($.target.value)}),i.jsx("input",{placeholder:"Description",value:We,onChange:$=>lt($.target.value)}),i.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="product",children:[i.jsx(ph,{size:15})," Add product"]})]})]})]}),i.jsxs("form",{className:"support-search-bar",onSubmit:$=>{$.preventDefault(),xt({query:V.trim()})},children:[i.jsxs("label",{children:[i.jsx("span",{children:"Search Support"}),i.jsx("input",{value:V,onChange:$=>H($.target.value),placeholder:"Search titles and request details"})]}),i.jsxs("button",{className:"support-secondary-button",type:"submit",children:[i.jsx(dy,{size:15})," Search"]}),c.query&&i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{H(""),xt({query:""})},"aria-label":"Clear search",children:i.jsx(Ra,{size:16})})]}),i.jsxs("div",{className:"support-filter-bar",children:[i.jsxs("div",{className:"support-filter-title",children:[i.jsx(dy,{size:16}),i.jsx("span",{children:"Filter"})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Product"}),i.jsxs("select",{value:Re,onChange:$=>xt({product:$.target.value}),disabled:!m?.canViewAllProducts&&Pe.length<=1,children:[i.jsx("option",{value:"all",children:"All products"}),Pe.map($=>i.jsx("option",{value:$.product_key,children:$.name},$.id))]})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Status"}),i.jsx("select",{value:c.status,onChange:$=>xt({status:$.target.value}),children:DC.map($=>i.jsx("option",{value:$.id,children:$.label},$.id))})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Visibility"}),i.jsxs("select",{value:c.visibility,onChange:$=>xt({visibility:$.target.value}),children:[i.jsx("option",{value:"all",children:"All visibility"}),i.jsx("option",{value:"public",children:"Public"}),i.jsx("option",{value:"private",children:"Private"})]})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Sort"}),i.jsxs("select",{value:c.sort,onChange:$=>xt({sort:$.target.value}),children:[i.jsx("option",{value:"recent",children:"Recently updated"}),i.jsx("option",{value:"newest",children:"Newest"}),i.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),m?.canViewAllProducts&&i.jsxs("div",{className:"support-admin-shortcuts",children:[i.jsxs("span",{children:[i.jsx(Yn,{size:15})," Owner view"]}),i.jsx("button",{type:"button",onClick:()=>xt({status:"needs-response"}),children:"Needs response"}),i.jsx("button",{type:"button",onClick:()=>xt({visibility:"private"}),children:"Private requests"}),i.jsx("button",{type:"button",onClick:()=>xt({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),i.jsxs("div",{className:"support-board-layout",children:[i.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[i.jsxs("div",{className:"support-list-heading",children:[i.jsxs("span",{children:[wt.length," request",wt.length===1?"":"s"]}),i.jsx("small",{children:Re==="all"?"All products":Ch(Pe,ot)})]}),wt.length===0?i.jsxs("div",{className:"support-list-empty",children:[i.jsx(Fu,{size:25}),i.jsx("strong",{children:"No posts match these filters."}),i.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),Pe.length>0&&i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ve(!0),children:[i.jsx(ph,{size:16})," Create the first request"]})]}):wt.map($=>{const Xe=Ay($.post_type);return i.jsxs("button",{type:"button",className:`support-post-row ${$.id===De?.id?"active":""}`,onClick:()=>{j($.id),Q(!1)},children:[i.jsx("span",{className:"support-post-row-icon",children:i.jsx(Xe,{size:17})}),i.jsxs("span",{className:"support-post-row-copy",children:[i.jsxs("span",{className:"support-post-row-meta",children:[i.jsx("b",{children:Ch(g,$.product_id)}),i.jsx("em",{children:Ny($.post_type)}),$.visibility==="private"&&i.jsx(Di,{size:13})]}),i.jsx("strong",{children:$.title}),i.jsxs("small",{children:[Sh($.status)," · ",ef($.updated_at)," · ",$.comment_count," comments"]})]}),$.post_type==="feature"&&i.jsxs("span",{className:"support-vote-count",children:[i.jsx(dx,{size:14})," ",$.vote_count]})]},$.id)})]}),i.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:De?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"support-detail-head",children:[i.jsxs("div",{className:"support-detail-badges",children:[i.jsx("span",{className:"support-product-badge",children:Ch(g,De.product_id)}),i.jsx("span",{className:"support-type-badge",children:Ny(De.post_type)}),i.jsx("span",{className:`support-status-badge status-${De.status}`,children:Sh(De.status)}),De.visibility==="private"&&i.jsxs("span",{className:"support-private-badge",children:[i.jsx(Di,{size:13})," Private"]})]}),i.jsxs("div",{className:"support-detail-actions",children:[_t&&i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>Q($=>!$),title:"Edit post",children:i.jsx(g0,{size:16})}),Hn&&i.jsxs(i.Fragment,{children:[i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{an()},disabled:G==="pin",title:De.is_pinned?"Unpin post":"Pin post",children:i.jsx(fy,{size:16})}),i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Da()},disabled:G==="lock",title:De.is_locked?"Unlock post":"Lock post",children:i.jsx(Di,{size:16})}),i.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{cn()},disabled:G==="hide",title:"Hide post",children:i.jsx(my,{size:16})})]})]})]}),fe?i.jsxs("form",{className:"support-edit-form",onSubmit:$=>{Pn($)},children:[i.jsx("input",{value:De.title,onChange:$=>Ot({title:$.target.value}),minLength:3,maxLength:180,required:!0}),i.jsx("textarea",{value:De.body,onChange:$=>Ot({body:$.target.value}),rows:9,required:!0}),i.jsxs("div",{className:"support-edit-actions",children:[i.jsxs("select",{value:De.visibility,onChange:$=>Ot({visibility:$.target.value}),children:[i.jsx("option",{value:"public",children:"Public"}),i.jsx("option",{value:"private",children:"Private"})]}),i.jsxs("button",{className:"support-primary-button",type:"submit",disabled:G==="edit",children:[i.jsx(Os,{size:16})," Save changes"]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("h3",{children:De.title}),i.jsx("div",{className:"support-detail-body",children:De.body.split(`
|
|
10
10
|
`).map(($,Xe)=>i.jsx("p",{children:$||" "},`${De.id}-body-${Xe}`))})]}),i.jsxs("div",{className:"support-detail-meta",children:[i.jsxs("span",{children:["Opened ",ef(De.created_at)]}),De.app_version&&i.jsxs("span",{children:["Version ",De.app_version]}),De.platform&&i.jsx("span",{children:De.platform}),De.is_locked&&i.jsxs("span",{children:[i.jsx(Di,{size:13})," Locked"]}),De.is_pinned&&i.jsxs("span",{children:[i.jsx(fy,{size:13})," Pinned"]})]}),i.jsxs("div",{className:"support-detail-controls",children:[De.post_type==="feature"&&i.jsxs("button",{className:`support-vote-button ${O.has(De.id)?"voted":""}`,type:"button",onClick:()=>{_e()},disabled:G==="vote",children:[i.jsx(v0,{size:16})," ",O.has(De.id)?"Voted":"Vote"," ",i.jsx("b",{children:De.vote_count})]}),Hn&&i.jsxs("label",{className:"support-status-control",children:[i.jsx("span",{children:"Change status"}),i.jsx("select",{value:De.status,onChange:$=>{nn($.target.value)},disabled:G==="status",children:(LC[De.post_type]||[]).map($=>i.jsx("option",{value:$,children:Sh($)},$))})]}),Hn&&i.jsxs(i.Fragment,{children:[i.jsxs("select",{className:"support-status-control",value:U,onChange:$=>ye($.target.value),children:[i.jsx("option",{value:"",children:"Duplicate of..."}),wt.filter($=>$.id!==De.id&&$.product_id===De.product_id).map($=>i.jsx("option",{value:$.id,children:$.title.slice(0,55)},$.id))]}),i.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Kn()},disabled:!U||G==="duplicate",children:"Merge duplicate"})]})]}),N.length>0&&i.jsxs("div",{className:"support-attachments",children:[i.jsx("div",{className:"support-section-heading",children:i.jsxs("div",{children:[i.jsx("span",{children:"Attachments"}),i.jsxs("strong",{children:[N.length," file",N.length===1?"":"s"]})]})}),N.map($=>i.jsxs("a",{href:$.signed_url,target:"_blank",rel:"noreferrer",children:[i.jsx(kp,{size:14})," ",$.file_name,i.jsxs("small",{children:[Math.ceil($.size_bytes/1024)," KB"]})]},$.id))]}),i.jsxs("div",{className:"support-comments",children:[i.jsxs("div",{className:"support-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Discussion"}),i.jsxs("strong",{children:[M.length," comment",M.length===1?"":"s"]})]}),De.is_locked&&i.jsxs("span",{className:"support-locked-label",children:[i.jsx(Di,{size:14})," Locked"]})]}),M.length===0?i.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):i.jsx("div",{className:"support-comment-list",children:M.map($=>i.jsxs("article",{className:`support-comment ${$.is_staff_answer?"staff":""} ${De.accepted_comment_id===$.id?"accepted":""}`,children:[i.jsxs("div",{className:"support-comment-head",children:[i.jsx("strong",{children:$.is_staff_answer?"LiveDesk Support":$.author_id===n.user.id?"You":"Support user"}),$.is_staff_answer&&i.jsxs("span",{children:[i.jsx(Yn,{size:13})," Staff answer"]}),De.accepted_comment_id===$.id&&i.jsxs("span",{children:[i.jsx(ea,{size:13})," Accepted"]}),i.jsx("time",{children:ef($.created_at)})]}),i.jsx("p",{children:$.body}),i.jsxs("div",{className:"support-comment-actions",children:[(n.user.id===De.author_id||Hn)&&De.post_type==="question"&&De.accepted_comment_id!==$.id&&i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Fr($.id)},disabled:G===`accept-${$.id}`,children:[i.jsx(Os,{size:14})," Accept answer"]}),Hn&&i.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{EC($.id)},title:"Hide comment",children:i.jsx(my,{size:14})})]})]},$.id))}),!De.is_locked&&i.jsxs("form",{className:"support-comment-form",onSubmit:$=>{Fn($)},children:[i.jsx("textarea",{value:z,onChange:$=>re($.target.value),placeholder:"Add a focused reply...",rows:3}),i.jsxs("button",{className:"support-primary-button",type:"submit",disabled:G==="comment"||!z.trim(),children:[i.jsx(Vu,{size:15})," Reply"]})]})]})]}):i.jsxs("div",{className:"support-detail-empty",children:[i.jsx(Fu,{size:28}),i.jsx("strong",{children:"Select a Support request"}),i.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):i.jsx("section",{className:"support-page support-auth-page",children:i.jsxs("div",{className:"support-empty-hero",children:[i.jsx("span",{className:"support-hero-icon",children:i.jsx(Fu,{size:28})}),i.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),i.jsx("h2",{children:"Get help, report issues, and shape the product."}),i.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),i.jsxs("button",{className:"support-primary-button",type:"button",onClick:l,children:[i.jsx(Yn,{size:17})," Sign in with Google"]})]})})}function tf(n){return!!n&&typeof n=="object"}function Mx(n){let a=n;return tf(a)&&"data"in a&&(a=a.data),tf(a)&&"session"in a&&(a=a.session),!tf(a)||typeof a.access_token!="string"||!a.access_token||!tf(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function Ty(n){return n?.access_token?n.refresh_token?"":"refresh-token-required":"access-token-required"}const Bu=5179,Rn=Hl(`http://127.0.0.1:${Bu}`);function OC(n){const a=n.split(".").map(s=>Number(s));return a.length===4&&a.every(s=>Number.isInteger(s)&&s>=0&&s<=255)?a:[]}function HC(n){const a=n.trim().toLowerCase();return a==="localhost"||a==="127.0.0.1"||a==="::1"||a==="[::1]"}function PC(n){const a=n.trim().toLowerCase();return!a||a==="0.0.0.0"||a==="::"||a==="[::]"}function FC(n){const a=OC(n);return a.length===0?!1:a[0]===10||a[0]===172&&a[1]>=16&&a[1]<=31||a[0]===192&&a[1]===168}function $C(n){return n.includes(":")&&!n.startsWith("[")?`[${n}]`:n}function BC(n){const a=String(n||"").trim();if(!a)return null;const s=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`tcp://${a}`;try{const l=new URL(s),c=l.hostname.replace(/^\[|\]$/g,""),u=Number(l.port);return!c||!Number.isInteger(u)||u<1||u>65535||PC(c)?null:{host:c,port:u}}catch{return null}}function Hl(n){const a=String(n||"").trim()||`http://127.0.0.1:${Bu}`,s=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`http://${a}`;try{const l=new URL(s);return l.port||(l.port=String(Bu)),l.hash="",l.search="",l.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${Bu}`}}function UC(n){const a=BC(n);return a?Hl(`http://${$C(a.host)}:${Bu}`):""}function Ry(n){const s=[n?.endpoint,...Array.isArray(n?.endpoint_candidates)?n.endpoint_candidates:[]].map(l=>UC(String(l||""))).filter(Boolean);return[...new Set(s)]}function Uu(n=Rn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(n);if(a.protocol!=="http:")return;if(HC(a.hostname))return"loopback";if(FC(a.hostname))return"local"}catch{return}}function Vf(n,a=Rn){const s=new URL(n,Hl(a));return s.protocol=s.protocol==="https:"?"wss:":"ws:",s.toString()}async function Ye(n,a,s=Rn){const l=Hl(s),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},u=Uu(l);u&&(c.targetAddressSpace=u);let m;try{m=await fetch(`${l}${n}`,c)}catch(g){throw u?new Error("LiveDesk Hub is not reachable at this local network address. If Chrome shows a local network prompt, allow it; otherwise restart the Hub so port 5179 is open on the network."):g}let h=null;try{h=await m.json()}catch{h=null}if(!m.ok){const g=h&&typeof h=="object"&&"error"in h?String(h.error||""):"";throw new Error(`${m.status} ${g||m.statusText}`)}return h}async function Ax({baseUrl:n=Rn,targetRole:a,previousRuntimePid:s=0,allowedStates:l=["running","waiting-auth"],timeoutMs:c=3e4}){const u=Date.now()+c;let m=null;for(;Date.now()<u;){try{const g=await Ye("/api/runtime/status",void 0,n),y=String(g.role||"").toLowerCase(),x=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),w=s>1?b>1&&b!==s:b>1;if(y===a&&l.map(j=>j.toLowerCase()).includes(x)&&w)return g}catch(g){m=g}await new Promise(g=>setTimeout(g,300))}const h=m instanceof Error?` ${m.message}`:"";throw new Error(`LiveDesk runtime did not become ${a} with a new process.${h}`)}function qC(n,a=120){if(typeof window>"u")return;const s=new URL(window.location.href);s.port=String(n),s.pathname="/",s.search="",s.hash="";const l=s.toString();let c=0;const u=()=>{fetch(l,{cache:"no-store",mode:"no-cors"}).then(()=>window.location.replace(l)).catch(()=>{if(c+=1,c>=a){window.location.replace(l);return}window.setTimeout(u,250)})};u()}function Nx(n){if(!n)return"-";const a=Date.now()-Date.parse(n);return Number.isFinite(a)?a<1e3?"now":a<6e4?`${Math.round(a/1e3)}s`:a<36e5?`${Math.round(a/6e4)}m`:`${Math.round(a/36e5)}h`:"-"}async function jf(n){await navigator.clipboard.writeText(n)}function Tx({size:n=22}){return i.jsxs("svg",{width:n,height:n,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[i.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),i.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),i.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),i.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),i.jsx("rect",{x:"6.5",y:"8.5",width:"15",height:"10",rx:"1.7",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"1.9"}),i.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const Rx={hub:"Use this computer as Hub. Hub connects to and manages Client computers.","switch-to-hub":"Switch this computer from Client to Hub. It will manage Client computers instead of sharing its own screen.",client:"Keep this computer in Client mode so its screens, files, audio, and remote controls remain available to the active Hub.",wall:"Show live thumbnails from every connected Client. Choose a display, change tile size, or move into Control without opening another connection.",control:"Open the selected Client at full resolution and send mouse and keyboard input through the existing Hub session.","share-files":"Browse files on the Hub, send files to selected Clients, and manage shared folders and transfer progress.",agents:"Run Hub-hosted Codex tasks on connected Clients within the selected permissions, timeouts, and audit controls."},ap={en:Rx,ko:{hub:"이 컴퓨터를 Hub로 사용합니다. Hub는 Client 컴퓨터를 연결하고 관리합니다.","switch-to-hub":"이 컴퓨터를 Client에서 Hub로 바꿉니다. 자신의 화면 공유를 멈추고 Client 컴퓨터를 관리합니다.",client:"이 컴퓨터를 Client 모드로 유지합니다. 화면, 파일, 오디오와 원격 제어 기능이 활성 Hub에서 계속 사용 가능하도록 연결합니다.",wall:"연결된 모든 Client의 실시간 화면을 한곳에 표시합니다. 모니터와 타일 크기를 선택하고 새 연결 없이 Control로 이동할 수 있습니다.",control:"선택한 Client 화면을 전체 해상도로 열고 기존 Hub 세션을 통해 마우스와 키보드 입력을 전송합니다.","share-files":"Hub의 파일을 탐색하고 선택한 Client로 전송하며 공유 폴더와 전송 진행 상태를 관리합니다.",agents:"Hub에서 실행되는 Codex 작업을 연결된 Client에 전달합니다. 선택한 권한, 제한 시간과 감사 기록 범위 안에서만 실행됩니다."},ja:{hub:"このコンピューターを LiveDesk Hub として運用します。Hub は Client 接続、Wall、Control、ファイル共有、Agents を一か所で管理する統合コントロールセンターで、ネットワーク変更後に押すと安全な接続情報も更新します。","switch-to-hub":"このコンピューターを Client から Hub に切り替えます。新しい役割を保存して同じデスクトップランタイムを再起動し、Wall を開きます。Client としての共有は停止します。",client:"このコンピューターを Client モードで維持し、画面、ファイル、音声、リモート操作をアクティブ Hub から利用できるようにします。",wall:"接続中のすべての Client のライブ画面を一覧表示します。ディスプレイやタイルサイズを選び、新しい接続なしで Control に移動できます。",control:"選択した Client をフル解像度で開き、既存の Hub セッションからマウスとキーボード入力を送信します。","share-files":"Hub のファイルを参照し、選択した Client への送信、共有フォルダー、転送状況を管理します。",agents:"Hub 上の Codex タスクを接続中の Client で実行します。選択した権限、タイムアウト、監査設定が適用されます。"},zh:{hub:"将此电脑作为 LiveDesk Hub 运行。Hub 是统一控制中心,可集中管理 Client 连接、Wall、Control、文件共享和 Agents;网络变化后按下此按钮还会刷新安全连接信息。","switch-to-hub":"将此电脑从 Client 切换为 Hub。LiveDesk 保存新角色、重启同一桌面运行时并打开 Wall;此电脑将停止作为 Client 共享。",client:"让此电脑保持 Client 模式,使活动 Hub 可以继续使用它的屏幕、文件、音频和远程控制。",wall:"集中显示所有已连接 Client 的实时缩略图。可以选择显示器、调整磁贴大小,并在不新建连接的情况下进入 Control。",control:"以完整分辨率打开所选 Client,并通过现有 Hub 会话发送鼠标和键盘输入。","share-files":"浏览 Hub 文件、向所选 Client 发送文件,并管理共享文件夹和传输进度。",agents:"在已连接 Client 上运行由 Hub 托管的 Codex 任务,并遵守所选权限、超时和审计控制。"},"zh-TW":{hub:"將此電腦作為 LiveDesk Hub 運作。Hub 是統一控制中心,可集中管理 Client 連線、Wall、Control、檔案分享與 Agents;網路變更後按下此按鈕也會更新安全連線資訊。","switch-to-hub":"將此電腦從 Client 切換為 Hub。LiveDesk 會儲存新角色、重新啟動同一桌面執行階段並開啟 Wall;此電腦將停止以 Client 身分共享。",client:"讓此電腦維持 Client 模式,使作用中 Hub 可繼續使用它的畫面、檔案、音訊與遠端控制。",wall:"集中顯示所有已連線 Client 的即時縮圖。可選擇顯示器、調整圖塊大小,並在不建立新連線的情況下進入 Control。",control:"以完整解析度開啟所選 Client,並透過現有 Hub 工作階段傳送滑鼠與鍵盤輸入。","share-files":"瀏覽 Hub 檔案、傳送檔案到所選 Client,並管理共享資料夾與傳輸進度。",agents:"在已連線 Client 上執行由 Hub 託管的 Codex 工作,並遵守所選權限、逾時與稽核控制。"},es:{hub:"Usa este equipo como LiveDesk Hub. Hub es el centro de control unificado para conexiones Client, Wall, Control, archivos y Agents; púlsalo tras cambios de red para actualizar el acceso seguro.","switch-to-hub":"Cambia este equipo de Client a Hub. LiveDesk guarda el nuevo rol, reinicia el mismo entorno de escritorio y abre Wall; el equipo deja de compartirse como Client.",client:"Mantiene este equipo en modo Client para que sus pantallas, archivos, audio y control remoto sigan disponibles desde el Hub activo.",wall:"Muestra miniaturas en vivo de todos los Clients conectados. Elige pantalla y tamaño, o entra en Control sin abrir otra conexión.",control:"Abre el Client seleccionado a resolución completa y envía ratón y teclado por la sesión Hub existente.","share-files":"Explora archivos del Hub, envíalos a los Clients seleccionados y administra carpetas compartidas y transferencias.",agents:"Ejecuta tareas Codex alojadas en el Hub sobre Clients conectados, respetando permisos, límites de tiempo y auditoría."},fr:{hub:"Utilise cet ordinateur comme LiveDesk Hub. Hub est le centre de contrôle unifié des connexions Client, de Wall, Control, des fichiers et des Agents ; appuyez après un changement réseau pour actualiser l’accès sécurisé.","switch-to-hub":"Bascule cet ordinateur de Client vers Hub. LiveDesk enregistre le nouveau rôle, redémarre le même environnement de bureau et ouvre Wall ; le partage Client s’arrête.",client:"Maintient cet ordinateur en mode Client afin que ses écrans, fichiers, sons et commandes à distance restent disponibles depuis le Hub actif.",wall:"Affiche les miniatures en direct de tous les Clients connectés. Choisissez l’écran et la taille, ou passez à Control sans nouvelle connexion.",control:"Ouvre le Client sélectionné en pleine résolution et transmet souris et clavier via la session Hub existante.","share-files":"Parcourez les fichiers du Hub, envoyez-les aux Clients sélectionnés et gérez dossiers partagés et transferts.",agents:"Exécute des tâches Codex hébergées par le Hub sur les Clients connectés, selon les permissions, délais et règles d’audit."},de:{hub:"Verwendet diesen Computer als LiveDesk Hub. Hub ist die gemeinsame Steuerzentrale für Client-Verbindungen, Wall, Control, Dateien und Agents; nach Netzwerkänderungen aktualisiert ein Klick den sicheren Zugriff.","switch-to-hub":"Wechselt diesen Computer von Client zu Hub. LiveDesk speichert die neue Rolle, startet dieselbe Desktop-Laufzeit neu und öffnet Wall; die Client-Freigabe endet.",client:"Hält diesen Computer im Client-Modus, damit Bildschirme, Dateien, Audio und Fernsteuerung am aktiven Hub verfügbar bleiben.",wall:"Zeigt Live-Vorschaubilder aller verbundenen Clients. Display und Kachelgröße wählen oder ohne neue Verbindung zu Control wechseln.",control:"Öffnet den gewählten Client in voller Auflösung und sendet Maus- und Tastatureingaben über die bestehende Hub-Sitzung.","share-files":"Dateien auf dem Hub durchsuchen, an gewählte Clients senden sowie Freigaben und Übertragungen verwalten.",agents:"Führt Hub-gehostete Codex-Aufgaben auf verbundenen Clients innerhalb der gewählten Berechtigungen, Zeitlimits und Auditregeln aus."},"pt-BR":{hub:"Usa este computador como LiveDesk Hub. Hub é o centro de controle unificado para conexões Client, Wall, Control, arquivos e Agents; após mudanças de rede, pressione para atualizar o acesso seguro.","switch-to-hub":"Muda este computador de Client para Hub. O LiveDesk salva a nova função, reinicia o mesmo runtime de desktop e abre o Wall; o compartilhamento como Client é encerrado.",client:"Mantém este computador no modo Client para que telas, arquivos, áudio e controle remoto continuem disponíveis no Hub ativo.",wall:"Mostra miniaturas ao vivo de todos os Clients conectados. Escolha a tela e o tamanho ou entre em Control sem criar outra conexão.",control:"Abre o Client selecionado em resolução total e envia mouse e teclado pela sessão Hub existente.","share-files":"Navegue pelos arquivos do Hub, envie para Clients selecionados e gerencie pastas compartilhadas e transferências.",agents:"Executa tarefas Codex hospedadas no Hub em Clients conectados, respeitando permissões, limites de tempo e auditoria."},it:{hub:"Usa questo computer come LiveDesk Hub. Hub è il centro di controllo unificato per connessioni Client, Wall, Control, file e Agents; dopo modifiche di rete, premilo per aggiornare l’accesso sicuro.","switch-to-hub":"Passa questo computer da Client a Hub. LiveDesk salva il nuovo ruolo, riavvia lo stesso runtime desktop e apre Wall; la condivisione come Client termina.",client:"Mantiene questo computer in modalità Client, rendendo schermi, file, audio e controllo remoto disponibili all’Hub attivo.",wall:"Mostra le anteprime live di tutti i Client connessi. Scegli display e dimensione oppure passa a Control senza una nuova connessione.",control:"Apre il Client selezionato a piena risoluzione e invia mouse e tastiera tramite la sessione Hub esistente.","share-files":"Esplora i file dell’Hub, inviali ai Client selezionati e gestisci cartelle condivise e trasferimenti.",agents:"Esegue attività Codex ospitate dall’Hub sui Client connessi rispettando permessi, timeout e controlli di audit."},id:{hub:"Gunakan komputer ini sebagai LiveDesk Hub. Hub adalah pusat kendali terpadu untuk koneksi Client, Wall, Control, file, dan Agents; tekan setelah perubahan jaringan untuk memperbarui akses aman.","switch-to-hub":"Alihkan komputer ini dari Client menjadi Hub. LiveDesk menyimpan peran baru, memulai ulang runtime desktop yang sama, lalu membuka Wall; berbagi sebagai Client berhenti.",client:"Pertahankan komputer ini dalam mode Client agar layar, file, audio, dan kendali jarak jauh tetap tersedia bagi Hub aktif.",wall:"Tampilkan thumbnail live semua Client yang terhubung. Pilih layar dan ukuran tile atau masuk ke Control tanpa koneksi baru.",control:"Buka Client terpilih pada resolusi penuh dan kirim input mouse serta keyboard melalui sesi Hub yang ada.","share-files":"Jelajahi file Hub, kirim ke Client terpilih, serta kelola folder bersama dan progres transfer.",agents:"Jalankan tugas Codex yang di-host Hub pada Client terhubung sesuai izin, batas waktu, dan kontrol audit."},vi:{hub:"Dùng máy tính này làm LiveDesk Hub. Hub là trung tâm điều khiển hợp nhất cho kết nối Client, Wall, Control, tệp và Agents; nhấn sau khi đổi mạng để làm mới quyền truy cập an toàn.","switch-to-hub":"Chuyển máy tính này từ Client sang Hub. LiveDesk lưu vai trò mới, khởi động lại cùng môi trường desktop và mở Wall; việc chia sẻ dưới dạng Client sẽ dừng.",client:"Giữ máy tính này ở chế độ Client để màn hình, tệp, âm thanh và điều khiển từ xa luôn sẵn sàng cho Hub đang hoạt động.",wall:"Hiển thị ảnh thu nhỏ trực tiếp của mọi Client đã kết nối. Chọn màn hình, cỡ ô hoặc vào Control mà không tạo kết nối mới.",control:"Mở Client đã chọn ở độ phân giải đầy đủ và gửi chuột, bàn phím qua phiên Hub hiện có.","share-files":"Duyệt tệp trên Hub, gửi tới Client đã chọn và quản lý thư mục chia sẻ cùng tiến trình truyền.",agents:"Chạy tác vụ Codex do Hub lưu trữ trên các Client đã kết nối trong phạm vi quyền, thời gian chờ và kiểm toán đã chọn."},th:{hub:"ใช้คอมพิวเตอร์เครื่องนี้เป็น LiveDesk Hub โดย Hub คือศูนย์ควบคุมรวมสำหรับการเชื่อมต่อ Client, Wall, Control, ไฟล์ และ Agents และกดหลังเปลี่ยนเครือข่ายเพื่อรีเฟรชการเข้าถึงที่ปลอดภัย","switch-to-hub":"เปลี่ยนคอมพิวเตอร์นี้จาก Client เป็น Hub โดย LiveDesk จะบันทึกบทบาทใหม่ รีสตาร์ต desktop runtime เดิม และเปิด Wall พร้อมหยุดแชร์ในฐานะ Client",client:"ให้คอมพิวเตอร์นี้อยู่ในโหมด Client เพื่อให้ Hub ที่ใช้งานเข้าถึงหน้าจอ ไฟล์ เสียง และการควบคุมระยะไกลได้ต่อเนื่อง",wall:"แสดงภาพสดแบบย่อของ Client ที่เชื่อมต่อทั้งหมด เลือกจอและขนาด tile หรือเข้า Control ได้โดยไม่เปิดการเชื่อมต่อใหม่",control:"เปิด Client ที่เลือกแบบความละเอียดเต็ม และส่งเมาส์กับคีย์บอร์ดผ่าน session ของ Hub ที่มีอยู่","share-files":"เรียกดูไฟล์บน Hub ส่งไปยัง Client ที่เลือก และจัดการโฟลเดอร์แชร์กับความคืบหน้าการโอน",agents:"เรียกใช้งาน Codex ที่โฮสต์บน Hub กับ Client ที่เชื่อมต่อ ภายใต้สิทธิ์ timeout และการตรวจสอบที่เลือก"},hi:{hub:"इस कंप्यूटर को LiveDesk Hub के रूप में उपयोग करें। Hub, Client कनेक्शन, Wall, Control, फ़ाइल और Agents का एकीकृत नियंत्रण केंद्र है; नेटवर्क बदलने के बाद सुरक्षित पहुँच ताज़ा करने के लिए इसे दबाएँ।","switch-to-hub":"इस कंप्यूटर को Client से Hub में बदलता है। LiveDesk नई भूमिका सहेजता है, उसी desktop runtime को restart करके Wall खोलता है और Client sharing रोक देता है।",client:"इस कंप्यूटर को Client मोड में रखता है ताकि इसकी स्क्रीन, फ़ाइलें, ऑडियो और remote control सक्रिय Hub पर उपलब्ध रहें।",wall:"सभी जुड़े Clients के live thumbnail दिखाता है। स्क्रीन और tile आकार चुनें या नया connection खोले बिना Control में जाएँ।",control:"चुने हुए Client को पूर्ण resolution में खोलता है और मौजूदा Hub session से mouse तथा keyboard input भेजता है।","share-files":"Hub की फ़ाइलें देखें, चुने हुए Clients को भेजें और shared folders तथा transfer progress प्रबंधित करें।",agents:"चुनी हुई permissions, timeout और audit controls के भीतर जुड़े Clients पर Hub-hosted Codex tasks चलाता है।"},ar:{hub:"استخدم هذا الكمبيوتر بوصفه LiveDesk Hub. يمثّل Hub مركز التحكم الموحّد لاتصالات Client وWall وControl والملفات وAgents؛ اضغط عليه بعد تغييرات الشبكة لتحديث الوصول الآمن.","switch-to-hub":"يحوّل هذا الكمبيوتر من Client إلى Hub. يحفظ LiveDesk الدور الجديد ويعيد تشغيل بيئة سطح المكتب نفسها ويفتح Wall، ويتوقف الجهاز عن المشاركة كـ Client.",client:"يبقي هذا الكمبيوتر في وضع Client لتظل شاشاته وملفاته وصوته والتحكم عن بعد متاحة من Hub النشط.",wall:"يعرض صورا حية مصغرة لكل Clients المتصلين. اختر الشاشة وحجم البلاطات أو انتقل إلى Control من دون اتصال جديد.",control:"يفتح Client المحدد بالدقة الكاملة ويرسل إدخال الماوس ولوحة المفاتيح عبر جلسة Hub الحالية.","share-files":"استعرض ملفات Hub وأرسلها إلى Clients المحددين وأدر المجلدات المشتركة وتقدم النقل.",agents:"يشغّل مهام Codex المستضافة على Hub في Clients المتصلين ضمن الصلاحيات والمهل وضوابط التدقيق المحددة."},tr:{hub:"Bu bilgisayarı LiveDesk Hub olarak kullanır. Hub; Client bağlantıları, Wall, Control, dosyalar ve Agents için birleşik kontrol merkezidir; ağ değişikliklerinden sonra güvenli erişimi yenilemek için basın.","switch-to-hub":"Bu bilgisayarı Client rolünden Hub rolüne geçirir. LiveDesk yeni rolü kaydeder, aynı masaüstü runtime’ını yeniden başlatıp Wall’u açar; Client paylaşımı durur.",client:"Bu bilgisayarı Client modunda tutar; ekran, dosya, ses ve uzaktan kontrol özellikleri etkin Hub tarafından kullanılabilir kalır.",wall:"Bağlı tüm Client ekranlarının canlı küçük görüntülerini gösterir. Ekran ve kutu boyutunu seçin veya yeni bağlantı açmadan Control’e geçin.",control:"Seçili Client’ı tam çözünürlükte açar ve mevcut Hub oturumu üzerinden fare ile klavye girdisi gönderir.","share-files":"Hub dosyalarını gezin, seçili Client’lara gönderin ve paylaşılan klasörlerle aktarım ilerlemesini yönetin.",agents:"Hub üzerinde barındırılan Codex görevlerini seçili izinler, zaman aşımları ve denetim kontrolleri içinde bağlı Client’larda çalıştırır."}};function Wf(n){const a=n?[n]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const s of a){const l=String(s||"").trim(),c=l.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const u=c.split("-")[0];if(ap[l])return l;if(ap[u])return u}return"en"}function _f(n,a){const s=Wf(a);return ap[s]?.[n]||Rx[n]}function rp(n,a,s){return`${n}
|
|
11
11
|
${_f(a,s)}`}const Ex={eyebrow:"Change computer role",title:"Switch this computer to Hub?",description:"LiveDesk will stop sharing this computer as a Client, save the Hub role, restart the local runtime, and open Wall in this same window.",restartNotice:"Remote streams from this computer will end while LiveDesk restarts.",cancel:"Cancel",confirm:"Switch to Hub",closeLabel:"Close Hub switch confirmation"},GC={en:Ex,ko:{eyebrow:"컴퓨터 역할 변경",title:"이 컴퓨터를 Hub로 전환하시겠습니까?",description:"이 컴퓨터의 Client 공유를 중지하고 Hub 역할을 저장한 뒤 로컬 런타임을 재시작하여 같은 창에서 Wall을 엽니다.",restartNotice:"LiveDesk가 재시작되는 동안 이 컴퓨터의 원격 스트림이 종료됩니다.",cancel:"취소",confirm:"Hub로 전환",closeLabel:"Hub 전환 확인 닫기"},ja:{eyebrow:"コンピューターの役割を変更",title:"このコンピューターを Hub に切り替えますか?",description:"このコンピューターの Client 共有を停止し、Hub の役割を保存してローカルランタイムを再起動し、同じウィンドウで Wall を開きます。",restartNotice:"LiveDesk の再起動中、このコンピューターのリモートストリームは終了します。",cancel:"キャンセル",confirm:"Hub に切り替える",closeLabel:"Hub 切り替え確認を閉じる"},zh:{eyebrow:"更改电脑角色",title:"将此电脑切换为 Hub?",description:"LiveDesk 将停止此电脑的 Client 共享,保存 Hub 角色,重启本地运行时,并在同一窗口中打开 Wall。",restartNotice:"LiveDesk 重启期间,此电脑的远程流将会结束。",cancel:"取消",confirm:"切换为 Hub",closeLabel:"关闭 Hub 切换确认"},"zh-TW":{eyebrow:"變更電腦角色",title:"要將此電腦切換為 Hub 嗎?",description:"LiveDesk 將停止此電腦的 Client 分享、儲存 Hub 角色、重新啟動本機執行階段,並在同一視窗中開啟 Wall。",restartNotice:"LiveDesk 重新啟動期間,此電腦的遠端串流將會結束。",cancel:"取消",confirm:"切換為 Hub",closeLabel:"關閉 Hub 切換確認"},es:{eyebrow:"Cambiar función del equipo",title:"¿Cambiar este equipo a Hub?",description:"LiveDesk dejará de compartir este equipo como Client, guardará la función Hub, reiniciará el entorno local y abrirá Wall en esta misma ventana.",restartNotice:"Los streams remotos de este equipo terminarán mientras LiveDesk se reinicia.",cancel:"Cancelar",confirm:"Cambiar a Hub",closeLabel:"Cerrar confirmación de cambio a Hub"},fr:{eyebrow:"Changer le rôle de l’ordinateur",title:"Basculer cet ordinateur vers Hub ?",description:"LiveDesk arrêtera le partage Client de cet ordinateur, enregistrera le rôle Hub, redémarrera le runtime local et ouvrira Wall dans cette même fenêtre.",restartNotice:"Les flux distants de cet ordinateur prendront fin pendant le redémarrage de LiveDesk.",cancel:"Annuler",confirm:"Basculer vers Hub",closeLabel:"Fermer la confirmation de bascule vers Hub"},de:{eyebrow:"Computerrolle ändern",title:"Diesen Computer auf Hub umstellen?",description:"LiveDesk beendet die Client-Freigabe dieses Computers, speichert die Hub-Rolle, startet die lokale Laufzeit neu und öffnet Wall im selben Fenster.",restartNotice:"Die Remote-Streams dieses Computers enden während des LiveDesk-Neustarts.",cancel:"Abbrechen",confirm:"Auf Hub umstellen",closeLabel:"Bestätigung für Hub-Wechsel schließen"},"pt-BR":{eyebrow:"Alterar função do computador",title:"Mudar este computador para Hub?",description:"O LiveDesk interromperá o compartilhamento deste computador como Client, salvará a função Hub, reiniciará o runtime local e abrirá o Wall nesta mesma janela.",restartNotice:"Os streams remotos deste computador serão encerrados enquanto o LiveDesk reinicia.",cancel:"Cancelar",confirm:"Mudar para Hub",closeLabel:"Fechar confirmação de mudança para Hub"},it:{eyebrow:"Cambia ruolo del computer",title:"Passare questo computer a Hub?",description:"LiveDesk interromperà la condivisione Client di questo computer, salverà il ruolo Hub, riavvierà il runtime locale e aprirà Wall nella stessa finestra.",restartNotice:"Gli stream remoti di questo computer termineranno durante il riavvio di LiveDesk.",cancel:"Annulla",confirm:"Passa a Hub",closeLabel:"Chiudi la conferma del passaggio a Hub"},id:{eyebrow:"Ubah peran komputer",title:"Alihkan komputer ini menjadi Hub?",description:"LiveDesk akan menghentikan berbagi komputer ini sebagai Client, menyimpan peran Hub, memulai ulang runtime lokal, lalu membuka Wall di jendela yang sama.",restartNotice:"Stream jarak jauh dari komputer ini akan berakhir saat LiveDesk dimulai ulang.",cancel:"Batal",confirm:"Alihkan ke Hub",closeLabel:"Tutup konfirmasi peralihan Hub"},vi:{eyebrow:"Đổi vai trò máy tính",title:"Chuyển máy tính này thành Hub?",description:"LiveDesk sẽ dừng chia sẻ máy tính này dưới dạng Client, lưu vai trò Hub, khởi động lại runtime cục bộ và mở Wall trong cùng cửa sổ.",restartNotice:"Các luồng từ xa của máy tính này sẽ kết thúc trong khi LiveDesk khởi động lại.",cancel:"Hủy",confirm:"Chuyển sang Hub",closeLabel:"Đóng xác nhận chuyển sang Hub"},th:{eyebrow:"เปลี่ยนบทบาทคอมพิวเตอร์",title:"เปลี่ยนคอมพิวเตอร์เครื่องนี้เป็น Hub หรือไม่",description:"LiveDesk จะหยุดแชร์คอมพิวเตอร์เครื่องนี้ในฐานะ Client บันทึกบทบาท Hub รีสตาร์ทรันไทม์ภายในเครื่อง และเปิด Wall ในหน้าต่างเดิม",restartNotice:"สตรีมระยะไกลจากคอมพิวเตอร์เครื่องนี้จะสิ้นสุดลงระหว่างที่ LiveDesk รีสตาร์ท",cancel:"ยกเลิก",confirm:"เปลี่ยนเป็น Hub",closeLabel:"ปิดการยืนยันการเปลี่ยนเป็น Hub"},hi:{eyebrow:"कंप्यूटर की भूमिका बदलें",title:"इस कंप्यूटर को Hub में बदलें?",description:"LiveDesk इस कंप्यूटर की Client साझेदारी बंद करेगा, Hub भूमिका सहेजेगा, स्थानीय रनटाइम पुनः आरंभ करेगा और इसी विंडो में Wall खोलेगा।",restartNotice:"LiveDesk के पुनः आरंभ होने के दौरान इस कंप्यूटर की रिमोट स्ट्रीम समाप्त हो जाएँगी।",cancel:"रद्द करें",confirm:"Hub में बदलें",closeLabel:"Hub परिवर्तन की पुष्टि बंद करें"},ar:{eyebrow:"تغيير دور الكمبيوتر",title:"هل تريد تحويل هذا الكمبيوتر إلى Hub؟",description:"سيوقف LiveDesk مشاركة هذا الكمبيوتر كـ Client، ويحفظ دور Hub، ويعيد تشغيل وقت التشغيل المحلي، ثم يفتح Wall في النافذة نفسها.",restartNotice:"ستنتهي التدفقات البعيدة من هذا الكمبيوتر أثناء إعادة تشغيل LiveDesk.",cancel:"إلغاء",confirm:"التحويل إلى Hub",closeLabel:"إغلاق تأكيد التحويل إلى Hub"},tr:{eyebrow:"Bilgisayar rolünü değiştir",title:"Bu bilgisayar Hub rolüne geçirilsin mi?",description:"LiveDesk bu bilgisayarın Client paylaşımını durdurur, Hub rolünü kaydeder, yerel çalışma zamanını yeniden başlatır ve Wall’u aynı pencerede açar.",restartNotice:"LiveDesk yeniden başlatılırken bu bilgisayarın uzak akışları sona erer.",cancel:"İptal",confirm:"Hub’a geçir",closeLabel:"Hub geçişi onayını kapat"}},Dx={eyebrow:"Computer role",title:"Use this computer as Hub?",description:"Hub connects to and manages Client computers.",restartNotice:"If another computer is Hub, this computer will become the new Hub.",cancel:"Cancel",confirm:"Use as Hub",closeLabel:"Close Hub confirmation"},VC={en:Dx,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function WC(n){const a=Wf(n);return GC[a]||Ex}function YC(n){const a=Wf(n);return VC[a]||Dx}const KC=[{id:"docs",label:"Doc",icon:Lf},{id:"support",label:"Support",icon:Fu},{id:"pricing",label:"Pricing",icon:$u},{id:"settings",label:"Settings",icon:jp}],Ey=[0,1e3,2e3,5e3,1e4,2e4,3e4];function QC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function ho(n,a=!1){const s=a?"":sessionStorage.getItem("livedesk.client.csrf");if(s)return s;const l=await fetch(`${n}/api/runtime/status`,{cache:"no-store"}),c=await l.json().catch(()=>({}));if(!l.ok)throw new Error(c.error||`Client runtime returned HTTP ${l.status}.`);const u=String(c.csrfToken||"");return u&&sessionStorage.setItem("livedesk.client.csrf",u),u}function sp(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function kh(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function Lx(n){return Number.isFinite(n)?sp(Number(n)):"0%"}function So(n){const a=Number(n);return!Number.isFinite(a)||a<0?"—":a>=1024**4?`${(a/1024**4).toFixed(a>=10*1024**4?0:1)} TB`:a>=1024**3?`${(a/1024**3).toFixed(a>=10*1024**3?0:1)} GB`:`${(a/1024**2).toFixed(0)} MB`}function Dy(n){const a=Math.max(0,Number(n||0));return a>=1024**3?`${(a/1024**3).toFixed(1)} GB/s`:a>=1024**2?`${(a/1024**2).toFixed(1)} MB/s`:a>=1024?`${(a/1024).toFixed(1)} KB/s`:`${a.toFixed(0)} B/s`}function XC(n,a){const s=Number(n||0)/1073741824,l=Number(a||0)/1024**3;return l>0?`${s.toFixed(1)} / ${l.toFixed(1)} GB`:"Checking..."}function ZC(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${So(n)} / ${So(a)}`:`${So(a)} available`}function JC(n){const a=Math.max(0,Math.floor(Number(n||0)/60)),s=Math.floor(a/1440),l=Math.floor(a%1440/60),c=a%60;return s>0?`${s}d ${l}h`:l>0?`${l}h ${c}m`:`${c}m`}function nf({icon:n,label:a,value:s,detail:l,percent:c}){return i.jsxs("article",{className:"client-resource-metric",children:[i.jsxs("div",{className:"client-resource-metric-head",children:[i.jsx(n,{size:17}),i.jsx("span",{children:a}),i.jsx("strong",{children:s})]}),i.jsx("small",{title:l,children:l}),i.jsx("i",{"aria-hidden":"true",children:i.jsx("b",{style:{width:Lx(c)}})})]})}function e1(n,a){const s=n?.user.user_metadata||{},l=s.full_name||s.name||s.preferred_username||n?.user.email||n?.user.id||a?.userName||a?.auth?.name||a?.userEmail||a?.userId||"Account";return String(l).trim()||"Account"}function t1(n,a){const s=n?.user.user_metadata||{},l=s.avatar_url||s.picture||a?.userAvatarUrl||a?.auth?.avatarUrl;return typeof l=="string"?l.trim():""}function n1({page:n,status:a}){const l={docs:{label:"DOC",title:"Using this computer",body:"This computer connects to its assigned Hub automatically. Keep LiveDesk running and manage screens, files, and remote control from the Hub."},pricing:{label:"PRICING",title:"LiveDesk plans",body:"Plans are based on how many computers the Hub manages. This Client computer does not need a separate subscription or setup."},settings:{label:"SETTINGS",title:"Computer preferences",body:"LiveDesk keeps the verified sign-in on this computer and reconnects to the assigned Hub automatically."}}[n];return i.jsxs("section",{className:"client-service-page",children:[i.jsx("span",{className:"client-unified-section-label",children:l.label}),i.jsx("h2",{children:l.title}),i.jsx("p",{children:l.body}),i.jsxs("div",{className:"client-service-page-card",children:[n==="docs"&&i.jsxs(i.Fragment,{children:[i.jsx("strong",{children:"Automatic connection"}),i.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),n==="pricing"&&i.jsxs(i.Fragment,{children:[i.jsx("strong",{children:"One plan, managed at the Hub"}),i.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),n==="settings"&&i.jsxs(i.Fragment,{children:[i.jsx("strong",{children:"Saved sign-in"}),i.jsx("span",{children:a?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function a1({session:n,status:a,pin:s,error:l,roleChangeMessage:c,videoAccelerationBusy:u,slotInput:m,slotBusy:h,onSignIn:g,onPinChange:y,onSubmitPin:x,onSlotInputChange:b,onSaveSlot:w,onEnableVideoAcceleration:j}){const M=a?.connectionState==="connected",k=a?.videoAcceleration,N=u||k?.busy||k?.state==="installing",A=k?.ready?`${k.encoder||"H.264"} · ${k.driver||"VAAPI"}`:N?"Setting up…":k?.message||"Setup available",T=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,L=a?.system?.gpus||[],O=L.find(F=>Number.isFinite(F.usagePercent)||Number.isFinite(F.memoryTotalBytes))||L[0],I=Number.isFinite(O?.usagePercent)?Number(O?.usagePercent):null,B=Number.isFinite(O?.memoryTotalBytes)&&Number(O?.memoryTotalBytes)>0&&Number.isFinite(O?.memoryUsedBytes)?Number(O?.memoryUsedBytes)/Number(O?.memoryTotalBytes)*100:null,_=a?.system?.disks||[],G=a?.system?.network,te=G?.interfaces||[],W=[...new Set(te.map(F=>F.name).filter(Boolean))],Y=te.map(F=>F.address).filter(Boolean);return i.jsxs("section",{className:"client-home-page",children:[i.jsxs("header",{className:"client-home-heading",children:[i.jsxs("div",{children:[i.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),i.jsx("h2",{children:a?.deviceName||"This Computer"})]}),i.jsxs("span",{className:`client-unified-role-chip ${M?"connected":""}`,children:[i.jsx(Ea,{size:15})," ",M?"Online":"Connecting"]})]}),i.jsxs("div",{className:"client-home-layout",children:[i.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[i.jsxs("div",{className:"client-main-surface-head",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),i.jsx("strong",{children:"Hardware at a glance"})]}),i.jsxs("small",{children:[i.jsx(px,{size:14})," Uptime ",JC(a?.system?.uptimeSeconds)]})]}),i.jsxs("div",{className:"client-system-dashboard",children:[i.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[i.jsxs("div",{className:"client-system-subhead",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),i.jsx("strong",{children:"Live resources"})]}),i.jsx("small",{children:"Live updates"})]}),i.jsxs("div",{className:"client-live-metrics",children:[i.jsx(nf,{icon:hy,label:"CPU",value:sp(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),i.jsx(nf,{icon:w0,label:"Memory",value:sp(T),detail:XC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:T}),i.jsx(nf,{icon:S0,label:"GPU",value:kh(I),detail:O?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:I}),i.jsx(nf,{icon:Hs,label:"VRAM",value:kh(B),detail:ZC(O?.memoryUsedBytes,O?.memoryTotalBytes),percent:B})]})]}),i.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[i.jsxs("div",{className:"client-system-subhead",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),i.jsx("strong",{children:"Local drives"})]}),i.jsx("small",{children:_.length>0?`${_.length} ${_.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),i.jsxs("div",{className:"client-disk-list",children:[_.map(F=>i.jsxs("article",{className:"client-disk-row",children:[i.jsxs("div",{className:"client-disk-row-head",children:[i.jsxs("span",{children:[i.jsx(wo,{size:16}),i.jsx("strong",{children:F.mount||"Disk"}),i.jsx("small",{children:F.name||"Local disk"})]}),i.jsx("strong",{children:kh(F.usedPercent)})]}),i.jsxs("small",{children:[So(F.freeBytes)," free · ",So(F.totalBytes)," total"]}),i.jsx("i",{"aria-hidden":"true",children:i.jsx("b",{style:{width:Lx(F.usedPercent)}})})]},`${F.mount}-${F.name||""}`)),_.length===0&&i.jsxs("div",{className:"client-disk-empty",children:[i.jsx(wo,{size:18}),i.jsx("span",{children:a?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),i.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[i.jsxs("div",{className:"client-system-subhead",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),i.jsx("strong",{children:"Live traffic"})]}),i.jsx("small",{children:W.length>0?W.join(", "):"Detecting adapter"})]}),i.jsxs("div",{className:"client-network-live",children:[i.jsxs("div",{className:"client-network-adapter",children:[i.jsx(qf,{size:18}),i.jsxs("span",{children:[i.jsx("strong",{children:W.join(", ")||"Network"}),i.jsx("small",{children:Y.join(" / ")||"Checking active connection"})]})]}),i.jsxs("div",{className:"client-network-rate download",children:[i.jsx(C0,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Receive"}),i.jsx("strong",{children:Dy(G?.receiveBytesPerSecond)})]})]}),i.jsxs("div",{className:"client-network-rate upload",children:[i.jsx(k0,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Send"}),i.jsx("strong",{children:Dy(G?.sendBytesPerSecond)})]})]}),i.jsxs("small",{className:"client-network-total",children:["Total ",So(G?.receivedBytes)," received / ",So(G?.sentBytes)," sent"]})]})]})]})]}),i.jsxs("aside",{className:"client-connection-panel",children:[i.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),i.jsx("h3",{children:M?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),M?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),i.jsxs("div",{className:"client-service-status-list",children:[i.jsxs("div",{children:[i.jsx(Ea,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Screen sharing"}),i.jsx("small",{children:a?.permissions?.screenCapture?"Active":"Waiting"})]})]}),i.jsxs("div",{children:[i.jsx(Yn,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Remote control"}),i.jsx("small",{children:a?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),i.jsxs("div",{children:[i.jsx(Sc,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"File delivery"}),i.jsx("small",{children:a?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),i.jsxs("div",{children:[i.jsx(jo,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Computer audio"}),i.jsx("small",{children:a?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"client-unified-copy",children:a?.authenticated?"LiveDesk is checking the registered Hub endpoints. A temporary Hub PIN can be used as a fallback.":"Sign in once on this computer. LiveDesk saves the verified session, finds the Hub, and starts screen sharing automatically."}),!n&&!a?.authenticated?i.jsxs("button",{className:"client-unified-primary",type:"button",onClick:g,children:[i.jsx(ko,{size:16})," Sign in with Google"]}):i.jsxs("p",{className:"client-unified-success",children:[i.jsx(ea,{size:16})," Signed in as ",n?.user.email||n?.user.id||a?.userEmail||a?.userId||"saved account"]}),i.jsxs("div",{className:"client-unified-pin-row",children:[i.jsx(j0,{size:16}),i.jsx("input",{value:s,onChange:F=>y(F.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),i.jsx("button",{className:"client-unified-secondary",type:"button",onClick:x,disabled:s.length!==6,children:"Connect"})]})]}),k?.supported&&i.jsxs("div",{className:`client-video-acceleration state-${k.ready?"ready":k.state||"setup-required"}`,children:[i.jsx(hy,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Hardware video"}),i.jsx("small",{children:A})]}),!k.ready&&k.canInstall&&i.jsx("button",{type:"button",onClick:j,disabled:N,title:"Install and verify Linux FFmpeg hardware video support",children:N?"Setting up":"Enable"})]}),(l||a?.lastError)&&i.jsxs("p",{className:"client-unified-error",role:"alert",children:[i.jsx(hx,{size:15})," ",l||a?.lastError]}),c&&i.jsx("p",{className:"client-unified-success",children:c}),i.jsxs("div",{className:"client-slot-setting",children:[i.jsxs("label",{htmlFor:"client-slot-number",children:[i.jsx("span",{children:"Slot"}),i.jsx("input",{id:"client-slot-number",value:m,onChange:F=>b(F.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!M||h})]}),i.jsxs("button",{type:"button",onClick:w,disabled:!M||h||!m,"aria-label":"Save slot number",title:"Save slot number",children:[i.jsx(jp,{size:17}),i.jsx("span",{children:h?"Saving":"Set"})]})]})]})]})]})}function r1(){const[n,a]=d.useState(null),[s,l]=d.useState(null),[c,u]=d.useState(!1),[m,h]=d.useState(""),[g,y]=d.useState(""),[x,b]=d.useState(""),[w,j]=d.useState(!1),[M,k]=d.useState(!1),[N,A]=d.useState(""),[T,L]=d.useState(!1),[O,I]=d.useState(null),[B,_]=d.useState(!1),[G,te]=d.useState("computer"),[W,Y]=d.useState(!1),F=d.useRef(null),ve=d.useRef(null),fe=d.useRef(!1),Q=d.useRef(!1),z=d.useRef(!1),re=d.useRef(0),V=d.useRef(!1),H=d.useMemo(QC,[]),le=d.useMemo(()=>e1(s,n),[s,n]),oe=d.useMemo(()=>t1(s,n),[s,n]),[X,be]=d.useState(!1),me=le.slice(0,1).toUpperCase()||"L";d.useEffect(()=>{be(!1)},[oe]);const he=d.useCallback(async()=>{if(y(""),window.liveDesk?.auth?.signInWithGoogle){const U=await window.liveDesk.auth.signInWithGoogle();return U?.ok===!1?(y(U.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${H}/auth/google`),!0},[H]),J=d.useCallback(async()=>{z.current||(z.current=!0,y("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await bt.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await he()||(z.current=!1))},[he]),Ce=d.useCallback(async U=>{const ye=Ty(U);if(ye)throw new Error(ye);if(fe.current)return!1;fe.current=!0;try{const je=await window.liveDesk?.auth?.persistSession?.(U);if(je?.ok===!1)throw new Error(je.error||"LiveDesk could not validate the desktop session.");for(let Fe=0;Fe<2;Fe+=1){const ut=await ho(H,Fe>0),tt=await fetch(`${H}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":ut},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:U.access_token,refreshToken:U.refresh_token,expiresAt:U.expires_at,user:{id:U.user.id,email:U.user.email}})}),vt=await tt.json().catch(()=>({}));if(tt.status===403&&Fe===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!tt.ok)throw new Error(vt.error||`Client runtime returned HTTP ${tt.status}.`);return y(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{fe.current=!1}},[H]),Te=d.useCallback(async()=>{try{const U=await fetch(`${H}/api/client/status`,{cache:"no-store"}),ye=await U.json().catch(()=>({}));if(!U.ok)throw new Error(ye.error||`Client runtime returned HTTP ${U.status}.`);if(ye.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",ye.csrfToken),String(ye.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(ye)}catch(U){y(U instanceof Error?U.message:String(U))}},[H]);d.useEffect(()=>{Te();const U=window.setInterval(()=>{Te()},2e3);return()=>window.clearInterval(U)},[Te]),d.useEffect(()=>{if(V.current)return;const U=Number(n?.slotNumber||0);A(U>0?String(U):"")},[n?.slotNumber]),d.useEffect(()=>{if(!O)return;const U=window.setTimeout(()=>I(null),5e3);return()=>window.clearTimeout(U)},[O]);const He=d.useCallback(async()=>{const U=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||U-re.current<4e3)){re.current=U;try{const ye=await fetch(`${H}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(H)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!ye.ok)throw new Error(`Client reconnect returned HTTP ${ye.status}.`);await Te()}catch(ye){y(ye instanceof Error?ye.message:String(ye))}}},[H,Te,n]);d.useEffect(()=>{const U=()=>{He()},ye=()=>{He()},je=()=>{document.visibilityState==="visible"&&He()};return window.addEventListener("online",U),window.addEventListener("focus",ye),document.addEventListener("visibilitychange",je),()=>{window.removeEventListener("online",U),window.removeEventListener("focus",ye),document.removeEventListener("visibilitychange",je)}},[He]),d.useEffect(()=>{if(!c||!n||!s?.access_token||n.authenticated)return;if(Ty(s)==="refresh-token-required"){J().catch(ut=>{z.current=!1,y(ut instanceof Error?ut.message:String(ut))});return}let U=!1,ye,je=0;const Fe=async()=>{if(U)return;try{const tt=await Ce(s);if(await Te(),tt)return}catch(tt){y(tt instanceof Error?tt.message:String(tt))}if(U)return;const ut=Ey[Math.min(je,Ey.length-1)];je+=1,ye=window.setTimeout(()=>{Fe()},ut)};return Fe(),()=>{U=!0,ye!==void 0&&window.clearTimeout(ye)}},[c,Te,J,s,n,Ce]),d.useEffect(()=>{const U=new URLSearchParams(window.location.search),ye=U.get("auth_error");if(!ye)return;y(ye),U.delete("auth_error");const je=U.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${je?`?${je}`:""}${window.location.hash}`)},[]),d.useEffect(()=>{let U=!0;if(!window.liveDesk?.auth)return l(null),u(!0),Te(),()=>{U=!1};const ye=window.liveDesk?.auth?.onComplete?.(Fe=>{Fe.ok&&Fe.session?bt.auth.setSession(Fe.session).catch(ut=>y(ut instanceof Error?ut.message:String(ut))):Fe.error&&y(Fe.error)});(async()=>{try{const Fe=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await bt.auth.getSession();if(!U)return;const ut=Mx(Fe);l(ut),Te()}catch(Fe){U&&y(Fe instanceof Error?Fe.message:String(Fe))}finally{U&&u(!0)}})();const{data:je}=bt.auth.onAuthStateChange((Fe,ut)=>{U&&(l(ut),u(!0),Te())});return()=>{U=!1,ye?.(),je.subscription.unsubscribe()}},[Te]),d.useEffect(()=>{if(!c||!n||Q.current||z.current||s||n.authenticated)return;const U=new URLSearchParams(window.location.search);if(!U.has("livedesk_launch"))return;Q.current=!0,U.delete("livedesk_launch");const ye=U.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ye?`?${ye}`:""}${window.location.hash}`),he().catch(je=>y(je instanceof Error?je.message:String(je)))},[c,s,he,n]);const ee=async()=>{Y(!1),window.liveDesk?.auth?.persistSession?(await bt.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&y("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${H}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await ho(H)}}).catch(()=>{}),l(null),await Te()};d.useEffect(()=>{if(!W)return;const U=je=>{je.target instanceof Element&&je.target.closest(".account-popover, .rail-account")||Y(!1)},ye=je=>{je.key==="Escape"&&Y(!1)};return window.addEventListener("pointerdown",U),window.addEventListener("keydown",ye),()=>{window.removeEventListener("pointerdown",U),window.removeEventListener("keydown",ye)}},[W]);const Ue=d.useCallback((U=!0)=>{w||(_(!1),U&&window.requestAnimationFrame(()=>ve.current?.focus()))},[w]),ft=d.useCallback(()=>{w||!n?.authenticated||(ve.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b(""),_(!0))},[w,n?.authenticated]);d.useEffect(()=>{if(!B)return;const U=window.requestAnimationFrame(()=>F.current?.focus()),ye=Fe=>{Fe.target instanceof Element&&Fe.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||Ue(!1)},je=Fe=>{Fe.key==="Escape"&&Ue()};return window.addEventListener("pointerdown",ye),window.addEventListener("keydown",je),()=>{window.cancelAnimationFrame(U),window.removeEventListener("pointerdown",ye),window.removeEventListener("keydown",je)}},[Ue,B]);const ne=async()=>{y("");try{const U=await fetch(`${H}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(H)},body:JSON.stringify({pin:m})}),ye=await U.json().catch(()=>({}));if(!U.ok||ye?.ok===!1)throw new Error(ye?.error||"PIN could not be accepted.");h(""),await Te()}catch(U){y(U instanceof Error?U.message:String(U))}},xe=async()=>{_(!1),j(!0),b(""),y("");try{const U=await fetch(`${H}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(H)},body:JSON.stringify({role:"hub"})}),ye=await U.json().catch(()=>({}));if(!U.ok||ye?.ok===!1)throw new Error(ye?.error||`Role change failed with HTTP ${U.status}.`);b("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const je=Number(n?.runtimePid||0);await Ax({baseUrl:H,targetRole:"hub",previousRuntimePid:je,allowedStates:["running"]}),window.location.reload()}catch(U){y(U instanceof Error?U.message:String(U)),j(!1)}},Oe=async()=>{if(T)return;const U=Number(N);if(!Number.isInteger(U)||U<1||U>999){I({kind:"error",message:"Enter a slot number from 1 to 999."});return}L(!0),I(null);try{const ye=await fetch(`${H}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(H)},body:JSON.stringify({slotNumber:U})}),je=await ye.json().catch(()=>({}));if(!ye.ok||je.ok===!1){if(je.error==="slot-taken"){const Fe=je.conflict?.deviceName||je.conflict?.hostname||je.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(U).padStart(3,"0")} is already used by ${Fe}.`)}throw new Error(je.error||`Slot update failed with HTTP ${ye.status}.`)}V.current=!1,A(String(U)),a(je),I({kind:"success",message:`Slot ${String(U).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(ye){I({kind:"error",message:ye instanceof Error?ye.message:String(ye)})}finally{L(!1),await Te()}},$e=async()=>{if(!M){k(!0),y("");try{const U=await fetch(`${H}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(H)},body:JSON.stringify({confirm:!0})}),ye=await U.json().catch(()=>({}));if(a(ye),!U.ok||ye.videoAcceleration?.ready!==!0)throw new Error(ye.videoAcceleration?.error||ye.error||"Linux hardware video setup did not complete.")}catch(U){y(U instanceof Error?U.message:String(U))}finally{k(!1),await Te()}}},ze=!!(n?.authenticated||s),Qe=d.useMemo(()=>Wf(),[]),qe=_f("switch-to-hub",Qe),We=_f("client",Qe),lt=WC(Qe);return i.jsxs("main",{className:"app-shell client-unified-shell",children:[i.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[i.jsx("div",{className:"rail-brand",title:"LiveDesk",children:i.jsx(Tx,{size:25})}),i.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:i.jsxs("div",{className:"client-main-tool-slot",children:[i.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:ft,disabled:w||!n?.authenticated,"aria-busy":w,"aria-expanded":B,"aria-haspopup":"dialog","aria-controls":B?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${qe}`,"data-tooltip":B?void 0:rp("Hub","switch-to-hub",Qe),children:[i.jsx(Hs,{size:19}),i.jsx("span",{children:w?"Switching…":"Hub"})]}),i.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${G==="computer"?"active":""}`,type:"button",onClick:()=>te("computer"),"aria-current":G==="computer"?"page":void 0,"aria-label":`Client. ${We}`,"data-tooltip":rp("Client","client",Qe),children:[i.jsx(Ea,{size:19}),i.jsx("span",{children:"Client"})]})]})}),i.jsxs("div",{className:"rail-footer",children:[KC.map(U=>{const ye=U.icon;return i.jsxs("button",{className:`rail-tool compact ${G===U.id?"active":""}`,type:"button",onClick:()=>te(U.id),title:U.label,children:[i.jsx(ye,{size:18}),i.jsx("span",{children:U.label})]},U.id)}),i.jsxs("button",{className:`rail-account ${ze?"signed-in":""}`,type:"button",onClick:()=>Y(U=>!U),"aria-expanded":W,"aria-haspopup":"dialog",title:ze?"Account":"Sign in",children:[ze&&oe&&!X?i.jsx("img",{src:oe,alt:le,referrerPolicy:"no-referrer",onError:()=>be(!0)},oe):ze?i.jsx("span",{className:"avatar-fallback",children:me}):i.jsx(ko,{size:18}),i.jsx("span",{children:ze?"Account":"Sign in"})]})]})]}),B&&i.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[i.jsxs("header",{className:"client-hub-switch-head",children:[i.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:i.jsx(Hs,{size:19})}),i.jsx("span",{className:"client-hub-switch-eyebrow",children:lt.eyebrow}),i.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Ue(),"aria-label":lt.closeLabel,children:i.jsx(Ra,{size:17})})]}),i.jsx("h2",{id:"client-hub-switch-title",children:lt.title}),i.jsx("p",{id:"client-hub-switch-description",children:lt.description}),i.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[i.jsx(Yn,{size:16,"aria-hidden":"true"}),i.jsx("span",{children:lt.restartNotice})]}),i.jsxs("div",{className:"client-hub-switch-actions",children:[i.jsx("button",{type:"button",onClick:()=>Ue(),children:lt.cancel}),i.jsxs("button",{ref:F,className:"primary",type:"button",onClick:()=>{xe()},disabled:w||!n?.authenticated,children:[i.jsx(Hs,{size:16}),lt.confirm]})]})]}),W&&i.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[i.jsxs("div",{className:"account-popover-head",children:[i.jsx("div",{className:"account-popover-avatar",children:ze&&oe&&!X?i.jsx("img",{src:oe,alt:le,referrerPolicy:"no-referrer",onError:()=>be(!0)},oe):ze?i.jsx("span",{children:me}):i.jsx(ko,{size:18})}),i.jsxs("div",{children:[i.jsx("strong",{children:ze?le:"Account"}),i.jsx("p",{children:s?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),i.jsxs("dl",{className:"account-popover-facts",children:[i.jsx("dt",{children:"User"}),i.jsx("dd",{children:s?.user.email||n?.userEmail||n?.userId||"Not signed in"}),i.jsx("dt",{children:"Runtime"}),i.jsx("dd",{children:n?"Local app ready":"Checking local app"}),i.jsx("dt",{children:"Session"}),i.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":ze?"Active for this run":"Not saved"}),i.jsx("dt",{children:"Role"}),i.jsx("dd",{children:"Client"})]}),ze?i.jsxs("button",{className:"account-popover-action",onClick:()=>{ee()},type:"button",children:[i.jsx(mx,{size:16}),"Logout"]}):i.jsxs("button",{className:"account-popover-action primary",onClick:()=>{Y(!1),he()},type:"button",children:[i.jsx(ko,{size:16}),"Sign in with Google"]})]}),i.jsxs("section",{className:"desk-stage client-unified-stage",children:[i.jsx("header",{className:"topbar",children:i.jsxs("div",{className:"brand",children:[i.jsx("span",{className:"brand-mark",children:i.jsx(jo,{size:18})}),i.jsxs("div",{children:[i.jsx("h1",{children:"LiveDesk"}),i.jsx("p",{children:"Client workspace"})]})]})}),G==="support"?i.jsx("section",{className:"client-unified-page",children:i.jsx(jx,{session:s,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{he()}})}):G!=="computer"?i.jsx("section",{className:"client-unified-page",children:i.jsx(n1,{page:G,status:n})}):i.jsx(a1,{session:s,status:n,pin:m,error:g,roleChangeMessage:x,videoAccelerationBusy:M,slotInput:N,slotBusy:T,onSignIn:()=>{he()},onPinChange:U=>h(U.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{ne()},onSlotInputChange:U=>{V.current=!0,A(U.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{Oe()},onEnableVideoAcceleration:()=>{$e()}})]}),O&&i.jsxs("div",{className:`client-side-toast ${O.kind}`,role:O.kind==="error"?"alert":"status",children:[O.kind==="error"?i.jsx(hx,{size:18}):i.jsx(ea,{size:18}),i.jsx("span",{children:O.message}),i.jsx("button",{type:"button",onClick:()=>I(null),"aria-label":"Dismiss notification",children:i.jsx(Ra,{size:16})})]})]})}function Rl(n,a,s){if(s<0||a<0||a+s>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function jh(n,a,s){let l=0;for(;Rl(n,a.inputIndex,1),n[a.inputIndex]===0;)l+=1,a.inputIndex+=1;const c=l*255+s+n[a.inputIndex];return a.inputIndex+=1,c}function af(n,a,s,l){if(Rl(n,a.inputIndex,l),a.outputIndex+l>s.length)throw new Error("Invalid LZO1X block: output overrun.");s.set(n.subarray(a.inputIndex,a.inputIndex+l),a.outputIndex),a.inputIndex+=l,a.outputIndex+=l}function s1(n,a,s,l){const c=a-s;if(c<=0||l<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let u=Math.min(c,l);for(n.set(n.subarray(s,s+u),a);u<l;){const m=Math.min(u,l-u);n.copyWithin(a+u,a,a+m),u+=m}return a+l}function _x(n,a){if(!(n instanceof Uint8Array)||n.length<3||a<0)throw new Error("Invalid LZO1X block.");const s=new Uint8Array(a),l={inputIndex:0,outputIndex:0};let c=0,u=0;if(n[l.inputIndex]>=22){const m=n[l.inputIndex]-17;l.inputIndex+=1,af(n,l,s,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,af(n,l,s,c));for(;;){Rl(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let h,g;if((m&192)!==0)Rl(n,l.inputIndex,1),g=l.outputIndex-((n[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,u=(m>>5)+1,h=m&3;else if((m&32)!==0){u=(m&31)+2,u===2&&(u+=jh(n,l,31)),Rl(n,l.inputIndex,2);const y=n[l.inputIndex]|n[l.inputIndex+1]<<8;l.inputIndex+=2,g=l.outputIndex-((y>>2)+1),h=y&3}else if((m&16)!==0){u=(m&7)+2,u===2&&(u+=jh(n,l,7)),Rl(n,l.inputIndex,2);const y=n[l.inputIndex]|n[l.inputIndex+1]<<8;if(l.inputIndex+=2,g=l.outputIndex-(((m&8)<<11)+(y>>2)),h=y&3,g===l.outputIndex)break;g-=16384}else if(c===0){let y=m+3;y===3&&(y+=jh(n,l,15)),af(n,l,s,y),c=4;continue}else c!==4?(Rl(n,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,u=2):(Rl(n,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+2049),l.inputIndex+=1,u=3);if(g<0||l.outputIndex+u+h>s.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=s1(s,l.outputIndex,g,u),c=h,af(n,l,s,h)}if(u!==3||l.inputIndex!==n.length||l.outputIndex!==s.length)throw new Error("Invalid LZO1X block: incomplete output.");return s}const Ly=16,_y=8,i1=24*1024*1024,Ix=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,ip=new Uint32Array(65536);for(let n=0;n<ip.length;n+=1){const a=Math.round((n>>11&31)*255/31),s=Math.round((n>>5&63)*255/63),l=Math.round((n&31)*255/31);ip[n]=Ix?(a|s<<8|l<<16|4278190080)>>>0:(a<<24|s<<16|l<<8|255)>>>0}function Tl(n,a){return n[a]|n[a+1]<<8}function l1(n,a){const s=Number(a);if(!Number.isSafeInteger(s)||s<Ly||s>i1)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=_x(l,s);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const u=(c[5]&1)!==0,m=Tl(c,6),h=Tl(c,8),g=Tl(c,10),y=Tl(c,12);if(m<=0||h<=0||m>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${h}.`);if(g<=0||g>256||y>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${y}.`);const x=[];let b=Ly;for(let w=0;w<y;w+=1){if(b+_y>c.length)throw new Error("Mode 5 tile header is truncated.");const j=Tl(c,b),M=Tl(c,b+2),k=Tl(c,b+4),N=Tl(c,b+6);b+=_y;const A=k*N*2;if(k<=0||N<=0||k>g||N>g||j+k>m||M+N>h||b+A>c.length)throw new Error(`Invalid Mode 5 tile ${w}.`);x.push({x:j,y:M,width:k,height:N,pixels:c.subarray(b,b+A)}),b+=A}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:u,width:m,height:h,tileSize:g,tiles:x}}function o1(n,a,s,l){if(!(n instanceof Uint8ClampedArray)||n.length!==a*s*4||l.width!==a||l.height!==s)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=a,u=s,m=0,h=0;const g=new Uint32Array(n.buffer,n.byteOffset,n.byteLength>>>2);for(const y of l.tiles){const x=Ix&&(y.pixels.byteOffset&1)===0?new Uint16Array(y.pixels.buffer,y.pixels.byteOffset,y.pixels.byteLength>>>1):null;let b=0;for(let w=0;w<y.height;w+=1){let j=(y.y+w)*a+y.x;for(let M=0;M<y.width;M+=1){const k=b<<1,N=x?x[b]:y.pixels[k]|y.pixels[k+1]<<8;g[j]=ip[N],b+=1,j+=1}}c=Math.min(c,y.x),u=Math.min(u,y.y),m=Math.max(m,y.x+y.width),h=Math.max(h,y.y+y.height)}return l.tiles.length>0?{x:c,y:u,width:m-c,height:h-u}:null}const $a=new WeakMap,Yu=new WeakMap,lp=new WeakMap,Ku=new Set,Co=new Set,Nc=new WeakMap,Cc=new Set,Qu=new WeakMap,op=new WeakMap,cp=new WeakMap,If=new WeakMap,zx=4,c1=2,u1=2,d1=2,f1=18,m1=40,h1=0,p1=250,Ox=80,Iy=5,g1=150,v1=1200,y1=18,b1=.65,x1=2e3,w1=500,Tp=250,S1=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Hx=1,Px=0,Fx=0,$x=0,Bx,Ux,_i={h264DecodeAcceleration:"prefer-hardware"};function C1(n){n.h264DecodeAcceleration&&(_i={..._i,h264DecodeAcceleration:n.h264DecodeAcceleration})}function up(n,a=_i.h264DecodeAcceleration){const s=Nc.get(n);return s?.requested===a?(s.actual!=="prefer-hardware"&&(Co.delete(n),Cc.add(n)),s.actual):(s&&(Nc.delete(n),Cc.delete(n)),a!=="prefer-hardware"?(Co.delete(n),Cc.delete(n),a):(Co.has(n)||Co.add(n),"prefer-hardware"))}function Rp(n,a,s){if(a!=="prefer-hardware")return!1;const l=Nc.get(n),c=$a.get(n),u=Date.now();return Qu.has(n)||Qu.set(n,Hx++),Nc.set(n,{requested:a,actual:"prefer-software",reason:s,failedAt:u,failureCount:(l?.requested===a?l.failureCount:0)+1,codec:c?.codec||l?.codec||"",latencyMode:c?.latencyMode||l?.latencyMode||"smooth",inputCount:c?.inputSerial??l?.inputCount??0,outputCount:c?.outputSerial??l?.outputCount??0,lastInputAt:c?.lastInputAt??l?.lastInputAt??0,lastOutputAt:c?.lastOutputAt??l?.lastOutputAt??0,lastPaintAt:c?.lastPaintAt??l?.lastPaintAt??0}),Co.delete(n),Cc.add(n),$x+=1,Bx=s,Ux=u,!0}function k1(n,a,s,l=64){try{let c=op.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},op.set(n,c));const u=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(u*Math.max(1,s)/Math.max(1,a)));(c.canvas.width!==u||c.canvas.height!==m)&&(c.canvas.width=u,c.canvas.height=m);const h=c.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(n,0,0,Math.max(1,a),Math.max(1,s),0,0,u,m);const g=h.getImageData(0,0,u,m).data;let y=2166136261;for(let w=0;w<g.length;w+=4)y^=g[w],y=Math.imul(y,16777619),y^=g[w+1],y=Math.imul(y,16777619),y^=g[w+2],y=Math.imul(y,16777619);const x=(y>>>0).toString(16).padStart(8,"0"),b=!c.initialized||x!==c.lastHash;return c.initialized=!0,c.lastHash=x,{visualHash:x,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function dp(n,a,s,l=Tp,c=64,u){if(!S1&&u)return qx(n,u);let m=cp.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},cp.set(n,m));const h=performance.now();if(m.initialized&&l>0&&h-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const g=k1(n,a,s,c);return m.initialized=!0,m.lastHash=g.visualHash,m.lastCanvasSampleAt=h,g}function qx(n,a){let s=If.get(n);s||(s={lastHash:"",initialized:!1},If.set(n,s));const l=String(a.contentHash||""),c=!s.initialized||!l||l!==s.lastHash;return s.initialized=!0,s.lastHash=l,{visualHash:l,visualChanged:c}}function Gx(n,a){const s=lp.get(n);if(s)return s;const l=n.getContext("2d",{alpha:!1,desynchronized:a==="interactive"});if(l){const c=l.getContextAttributes?.(),u={context:l,presentation:c?.desynchronized?"desync":"sync"};return lp.set(n,u),u}return null}function j1(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),s=String(n.compression||"").toLowerCase(),l=String(n.mimeType||"").toLowerCase();return a==="mode2-lzo"||s==="lzo1x"||l==="application/vnd.livedesk.lzo-rgb565"||a==="mode2-lz4"||String(n.compression||"").toLowerCase()==="lz4"||l==="application/vnd.livedesk.lz4-raw"}function M1(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function A1(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),s=String(n.mimeType||"").toLowerCase();return a==="mode5-lzo-delta"||s==="application/vnd.livedesk.lzo-rgb565-delta"}function zy(n,a,s){let l=s,c=a;if(l===15){let u=255;for(;u===255;){if(c>=n.length)throw new Error("Invalid LZ4 block: length overrun.");u=n[c],c+=1,l+=u}}return{length:l,cursor:c}}function N1(n,a){const s=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const u=n[l];l+=1;const m=zy(n,l,u>>4);l=m.cursor;const h=m.length;if(l+h>n.length||c+h>s.length)throw new Error("Invalid LZ4 block: literal overrun.");if(s.set(n.subarray(l,l+h),c),l+=h,c+=h,l>=n.length)break;if(l+2>n.length)throw new Error("Invalid LZ4 block: missing offset.");const g=n[l]|n[l+1]<<8;if(l+=2,g<=0||g>c)throw new Error("Invalid LZ4 block: bad match offset.");const y=zy(n,l,u&15);l=y.cursor;const x=y.length+4;if(c+x>s.length)throw new Error("Invalid LZ4 block: match overrun.");let b=c-g;for(let w=0;w<x;w+=1)s[c]=s[b],c+=1,b+=1}if(c!==s.length)throw new Error("Invalid LZ4 block: incomplete output.");return s}function T1(n){const a=Math.max(1,Math.floor(n.width||0)),s=Math.max(1,Math.floor(n.height||0)),l=String(n.compression||"").toLowerCase(),c=String(n.pixelFormat||n.codec||"").toLowerCase();if(l==="lzo1x"||String(n.frameMode||n.mode||"").toLowerCase()==="mode2-lzo"||String(n.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const x=Math.max(1,Math.floor(n.bytesPerPixel||2)),b=a*s*2,w=Math.floor(n.uncompressedByteLength||b);if(x!==2||w!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${w} for ${a}x${s}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const j=_x(n.payload,b),M=new Uint8ClampedArray(a*s*4);for(let k=0,N=0;k<j.length;k+=2,N+=4){const A=j[k]|j[k+1]<<8,T=A>>11&31,L=A>>5&63,O=A&31;M[N]=T<<3|T>>2,M[N+1]=L<<2|L>>4,M[N+2]=O<<3|O>>2,M[N+3]=255}return new ImageData(M,a,s)}const m=Math.max(1,Math.floor(n.bytesPerPixel||4)),h=Math.max(a*s*m,Math.floor(n.uncompressedByteLength||0)),g=N1(n.payload,h);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const y=new Uint8ClampedArray(a*s*4);if(c==="rgba32"||c==="rgba")y.set(g.subarray(0,y.length));else for(let x=0,b=0;b<y.length;x+=4,b+=4)y[b]=g[x+2],y[b+1]=g[x+1],y[b+2]=g[x],y[b+3]=g[x+3];return new ImageData(y,a,s)}function Oy(n,a="smooth",s=_i.h264DecodeAcceleration){const l=window.VideoDecoder;if(!l||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const c=$a.get(n);if(c&&c.decoder.state!=="closed"&&c.latencyMode===a)return c;c&&Hr(n);let u;const m=new l({output:h=>{if($a.get(n)!==u){h.close();return}const g=Number(h.timestamp||0);u.outputSerial+=1;let y=u.pendingFrames.get(g);if(y)u.pendingFrames.delete(g);else if(u.pendingFrames.size>0){const k=u.pendingFrames.entries().next().value;k&&(u.pendingFrames.delete(k[0]),y=k[1],u.timestampFallbacks+=1)}const x=h.displayWidth||h.codedWidth||n.width||960,b=h.displayHeight||h.codedHeight||n.height||540,w=Number(y?.frame.durationUs||0),j=Number(h.duration||0),M=Math.max(16,Math.min(250,(w>0?w:j||83333)/1e3));for(u.targetPaintIntervalMs=M,u.decodedFrames.push({videoFrame:h,pending:y,decodedAt:performance.now(),width:x,height:b,durationMs:M}),u.lastOutputAt=performance.now();u.decodedFrames.length>Ep(u);)zf(u,u.decodedFrames.shift());Wx(u),u.renderTimer!==null&&u.renderScheduledAt>0&&performance.now()-u.renderScheduledAt>w1&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),u.renderTimer!==null&&u.decodedFrames.length>=zx&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),Of(n,u)},error:()=>{$a.get(n)===u&&(Rp(n,u.requestedAcceleration,"decoder-error"),Hr(n))}});return Px+=1,Qu.has(n)||Qu.set(n,Hx++),u={decoder:m,configured:!1,configKey:"",codec:"",requestedAcceleration:s,hardwareAcceleration:up(n,s),latencyMode:a,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,decodedFrames:[],renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0},$a.set(n,u),Ku.add(n),u}function Vx(n){n.renderTimer!==null&&(window.cancelAnimationFrame(n.renderTimer),n.renderTimer=null),n.renderScheduledAt=0,n.flushTimer!==null&&(window.clearTimeout(n.flushTimer),n.flushTimer=null),n.flushInFlight=!1;for(const a of n.decodedFrames)a.videoFrame.close();n.decodedFrames=[],n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0}function zf(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function Ep(n){return n.latencyMode==="interactive"?u1:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?c1:zx}function Wx(n,a=performance.now()){const s=Ep(n);for(;n.decodedFrames.length>s;)zf(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?Ox:p1;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)zf(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function Yx(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.latencyMode==="interactive"||a.flushTimer!==null||a.flushInFlight)return;const s=g1;a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const l=performance.now();for(const[u,m]of a.pendingFrames.entries())l-m.queuedAt>x1&&a.pendingFrames.delete(u);if($a.get(n)!==a||a.decoder.state!=="configured"||a.pendingFrames.size===0||a.inputSerial<=a.lastFlushInputSerial||a.lastOutputAt>0&&l-a.lastOutputAt<s)return;const c=a.inputSerial;a.flushInFlight=!0,a.flushCount+=1,a.keyFrameSeen=!1;try{await a.decoder.flush(),a.lastFlushInputSerial=Math.max(a.lastFlushInputSerial,c)}catch{$a.get(n)===a&&Mf(a)}finally{a.flushInFlight=!1,$a.get(n)===a&&a.inputSerial>c&&a.pendingFrames.size>0&&performance.now()-a.lastOutputAt>=s&&Yx(n,a)}},s)}function Hy(n,a,s){const l=performance.now();try{(n.width!==s.width||n.height!==s.height)&&(n.width=s.width,n.height=s.height);const c=Gx(n,a.latencyMode);if(c?.context.drawImage(s.videoFrame,0,0,s.width,s.height),s.pending){const u=performance.now(),h=a.latencyMode==="interactive"?qx(n,s.pending.frame):dp(n,s.width,s.height,Tp,64,s.pending.frame);try{a.onPaint?.(s.pending.frame,{deviceId:s.pending.frame.deviceId,frameSeq:s.pending.frame.frameSeq,mode:s.pending.frame.frameMode||s.pending.frame.mode||s.pending.frame.codec||s.pending.frame.mimeType,width:s.width,height:s.height,byteLength:s.pending.frame.byteLength,queuedForMs:Math.max(0,l-s.pending.queuedAt),decodedForMs:Math.max(0,s.decodedAt-s.pending.queuedAt),scheduledForMs:Math.max(0,l-s.decodedAt),drawMs:Math.max(0,u-l),queueSize:s.pending.queueSize,renderQueueSize:a.decodedFrames.length,droppedForLatency:a.droppedForLatency,h264DecodeAcceleration:a.hardwareAcceleration,decoderLabel:a.hardwareAcceleration,decoderFlushCount:a.flushCount,decoderTimestampFallbacks:a.timestampFallbacks,decoderInputCount:a.inputSerial,decoderOutputCount:a.outputSerial,targetPaintIntervalMs:a.targetPaintIntervalMs,canvasPresentation:c?.presentation||"sync",interactiveBufferWaitCount:a.interactiveBufferWaitCount,interactiveBufferWaitMs:a.interactiveBufferWaitMs,interactiveQueueDrainCount:a.interactiveQueueDrainCount,visualHash:h.visualHash,visualChanged:h.visualChanged,paintedAt:u})}catch{}}a.lastPaintAt=performance.now()}finally{s.videoFrame.close()}}function Of(n,a){if(a.renderTimer!==null||a.decodedFrames.length===0)return;const s=Math.max(16,Math.min(250,a.targetPaintIntervalMs||1e3/12)),l=()=>{if(a.renderTimer=null,a.renderScheduledAt=0,a.decodedFrames.length===0)return;const c=performance.now();if(Wx(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const g=a.targetPaintIntervalMs<=m1,y=a.targetPaintIntervalMs<=20;if(y&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const k=a.decodedFrames.length>=d1,N=c-a.interactiveBufferStartedAt>=f1;if(!k&&!N){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else y||(a.interactiveBufferPrimed=!0);const x=a.decodedFrames[0],b=x?.pending?Math.max(0,c-x.pending.queuedAt):0,w=a.lastPaintAt>0?a.lastPaintAt+s:c;if(!(!g||c+Iy>=w||b>=Ox)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const M=a.decodedFrames.shift();if(M)try{Hy(n,a,M)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),Of(n,a);return}const u=a.lastPaintAt>0?a.lastPaintAt+s:c+h1;if(!(c+Iy>=u||a.decodedFrames.length>=Math.max(1,Ep(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const h=a.decodedFrames.shift();if(h)try{Hy(n,a,h)}catch{}Of(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function Kx(n,a){if($a.get(n)!==a||a.decoder.state==="closed")return!1;for(a.renderTimer!==null&&(window.cancelAnimationFrame(a.renderTimer),a.renderTimer=null),a.renderScheduledAt=0;a.decodedFrames.length>1;)zf(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,Of(n,a),!0}function Mh(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of Ku){const a=$a.get(n);if(!a||a.decoder.state==="closed"){Ku.delete(n);continue}Kx(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Mh),window.addEventListener("focus",Mh),window.addEventListener("pageshow",Mh));function Hr(n){Co.delete(n),Ku.delete(n),If.delete(n);const a=$a.get(n);if(a){$a.delete(n),Fx+=1;try{Vx(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function gc(n){n&&(Nc.delete(n),Cc.delete(n),lp.delete(n),cp.delete(n),op.delete(n),If.delete(n),Yu.delete(n),Hr(n))}function R1(n,a){const s=$a.get(n),l=Nc.get(n);if(!s&&!l)return null;const c=u=>u>0?Math.max(0,a-u):void 0;return{canvasId:Qu.get(n)||0,canvasWidth:Math.max(0,Number(n.width||0)),canvasHeight:Math.max(0,Number(n.height||0)),decoderState:s?.decoder.state||"fallback-pending",configured:s?.configured||!1,codec:s?.codec||l?.codec||"",requestedAcceleration:s?.requestedAcceleration||l?.requested||_i.h264DecodeAcceleration,configuredAcceleration:s?.hardwareAcceleration||l?.actual||_i.h264DecodeAcceleration,latencyMode:s?.latencyMode||l?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(s?.decoder.decodeQueueSize||0)),pendingFrameCount:s?.pendingFrames.size||0,renderQueueSize:s?.decodedFrames.length||0,inputCount:s?.inputSerial??l?.inputCount??0,outputCount:s?.outputSerial??l?.outputCount??0,lastInputAgeMs:c(s?.lastInputAt??l?.lastInputAt??0),lastOutputAgeMs:c(s?.lastOutputAt??l?.lastOutputAt??0),lastPaintAgeMs:c(s?.lastPaintAt??l?.lastPaintAt??0),softwareFallbackReason:l?.reason,softwareFallbackAt:l?.failedAt,softwareFallbackCount:l?.failureCount||0}}function Py(n){const a=performance.now(),l=(n?[n]:[...new Set([...Ku,...Cc])]).map(c=>R1(c,a)).filter(c=>c!==null);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:l.filter(c=>c.decoderState!=="fallback-pending").length,hardwareLeaseCount:Co.size,activeSoftwareFallbackCount:l.filter(c=>c.configuredAcceleration==="prefer-software"&&c.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:Px,decoderCloseCount:Fx,softwareFallbackEventCount:$x,lastSoftwareFallbackReason:Bx,lastSoftwareFallbackAt:Ux,canvases:l}}function Mf(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),Vx(n),n.lastPaintAt=0,n.lastOutputAt=0,n.lastInputAt=0,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,n.lastInputFrameSeq=void 0,n.nextChunkTimestampUs=0,n.healthSampleStartedAt=performance.now(),n.healthInputSerial=n.inputSerial,n.healthOutputSerial=n.outputSerial,n.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a)))}function E1(n,a,s,l,c){n.decoder.configure(a),n.configured=!0,n.configKey=s,n.codec=a.codec,n.requestedAcceleration=c,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0}function D1(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const s=performance.now();if(s-a.healthSampleStartedAt<v1)return!1;const l=a.inputSerial-a.healthInputSerial,c=a.outputSerial-a.healthOutputSerial;return a.healthSampleStartedAt=s,a.healthInputSerial=a.inputSerial,a.healthOutputSerial=a.outputSerial,l<y1||c/Math.max(1,l)>=b1?!1:(Rp(n,a.requestedAcceleration,"interactive-health"),Hr(n),!0)}function Eu(n,a=1){if(!n)return!1;const s=$a.get(n);return s?(s.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),Hr(n),!0):!1}function L1(n){if(!n)return!1;const a=$a.get(n);return a?Kx(n,a):!1}function _1(n,a,s,l="interactive"){Hr(n);const c=performance.now(),u=l1(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let h=Yu.get(n);if(!h||h.streamId!==m||h.width!==u.width||h.height!==u.height){const k=new Uint8ClampedArray(u.width*u.height*4);for(let N=3;N<k.length;N+=4)k[N]=255;h={streamId:m,width:u.width,height:u.height,rgba:k,imageData:new ImageData(k,u.width,u.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Yu.set(n,h)}if(!h)throw new Error("Mode 5 canvas state could not be initialized.");h.inputSerial+=1;const y=Number(a.streamFrameSeq||0);if(y>0&&(h.lastStreamFrameSeq=y),!u.keyFrame&&!h.keyFrameSeen)return;u.keyFrame&&(h.keyFrameSeen=!0);const x=o1(h.rgba,h.width,h.height,u),b=performance.now();(n.width!==h.width||n.height!==h.height)&&(n.width=h.width,n.height=h.height);const w=Gx(n,l),j=performance.now();x&&w?.context.putImageData(h.imageData,0,0,x.x,x.y,x.width,x.height);const M=performance.now();h.outputSerial+=1,s?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:h.width,height:h.height,byteLength:a.byteLength,queuedForMs:Math.max(0,M-c),decodedForMs:Math.max(0,b-c),scheduledForMs:0,drawMs:Math.max(0,M-j),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:h.inputSerial,decoderOutputCount:h.outputSerial,targetPaintIntervalMs:Math.max(1,Number(a.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:M})}const Ah=[{code:30,maxFrameSize:1620,maxMacroblocksPerSecond:40500},{code:31,maxFrameSize:3600,maxMacroblocksPerSecond:108e3},{code:32,maxFrameSize:5120,maxMacroblocksPerSecond:216e3},{code:40,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:41,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:42,maxFrameSize:8704,maxMacroblocksPerSecond:522240},{code:50,maxFrameSize:22080,maxMacroblocksPerSecond:589824},{code:51,maxFrameSize:36864,maxMacroblocksPerSecond:983040},{code:52,maxFrameSize:36864,maxMacroblocksPerSecond:2073600}];function Fy(n,a){for(let s=Math.max(0,a);s+3<n.length;s+=1)if(!(n[s]!==0||n[s+1]!==0)){if(n[s+2]===1)return{index:s,length:3};if(n[s+2]===0&&n[s+3]===1)return{index:s,length:4}}return null}function I1(n){let a=0;for(;a<n.length;){const s=Fy(n,a);if(!s)break;const l=s.index+s.length,c=Fy(n,l),u=c?.index??n.length;if(l<u&&(n[l]&31)===7){const m=[];let h=0;for(let g=l+1;g<u;g+=1){const y=n[g];if(h>=2&&y===3){h=0;continue}m.push(y),h=y===0?h+1:0}if(m.length>=3)return`avc1.${m.slice(0,3).map(g=>g.toString(16).toUpperCase().padStart(2,"0")).join("")}`}a=c?c.index:n.length}return""}function z1(n,a,s,l,c=""){const u=Math.ceil(n/16)*Math.ceil(a/16),m=s>0?1e6/s:30,h=u*m,g=Ah.find(y=>u<=y.maxFrameSize&&h<=y.maxMacroblocksPerSecond)||Ah[Ah.length-1];return I1(l)||c||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function Qx(n,a,s,l,c="smooth",u=!0){Yu.delete(n);const m=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",h=Math.max(1,Math.floor(a.width||960)),g=Math.max(1,Math.floor(a.height||540)),y=Math.max(1,Math.floor(a.durationUs||1e6/12)),x=l||_i.h264DecodeAcceleration;let b=Oy(n,c,x);const w=z1(h,g,y,a.payload,b.codec),j=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";let M=up(n,x),k="";const N=()=>{k=[a.streamId||"",a.commandId||"",h,g,w,m,x,M,c].join("|")};N(),b.onPaint=s,b.configured&&b.decoder.state!=="configured"&&(b.configured=!1,b.configKey=""),b.configured&&b.configKey!==k&&(Hr(n),b=Oy(n,c,x),b.onPaint=s,M=up(n,x),N());const A=()=>({codec:w,codedWidth:h,codedHeight:g,hardwareAcceleration:M,optimizeForLatency:!0,avc:{format:m}}),T=G=>b.hardwareAcceleration!=="prefer-hardware"||!Rp(n,b.requestedAcceleration,G)?!1:(Hr(n),u&&j&&Qx(n,a,s,x,c,!1),!0),L=()=>{try{return E1(b,A(),k,M,x),!0}catch(G){if(T("configure-error"))return!1;throw Hr(n),G}};if(!b.configured&&!L())return;const O=Number(a.streamFrameSeq||0);if(O>0&&b.lastInputFrameSeq!==void 0&&(O<=b.lastInputFrameSeq&&(!j||O===b.lastInputFrameSeq||(Mf(b,b.lastInputFrameSeq-O+1),!L()))||O>b.lastInputFrameSeq+1&&(Mf(b,O-b.lastInputFrameSeq-1),!j||!L()))||(O>0&&(b.lastInputFrameSeq=O),!j&&!b.keyFrameSeen))return;j&&(b.keyFrameSeen=!0);const I=Number(b.decoder.decodeQueueSize||0);if(I>8){if(b.latencyMode==="interactive"&&b.hardwareAcceleration==="prefer-hardware"){T("decode-queue-overflow");return}if(Mf(b),!j||!L())return;b.keyFrameSeen=!0}const B=b.nextChunkTimestampUs;b.nextChunkTimestampUs+=y,b.pendingFrames.set(B,{frame:a,queuedAt:performance.now(),queueSize:I}),b.inputSerial+=1,b.lastInputAt=performance.now();const _=new EncodedVideoChunk({type:j?"key":"delta",timestamp:B,duration:y,data:a.payload});try{b.decoder.decode(_)}catch(G){if(T("decode-error"))return;throw Hr(n),G}Yx(n,b),D1(n,b)}async function Nh(n,a,s,l,c,u="smooth"){if(A1(a)){s()||_1(n,a,l,u);return}if(M1(a)){s()||Qx(n,a,l,c,u);return}if(Yu.delete(n),j1(a)){Hr(n);const b=T1(a);if(s())return;(n.width!==b.width||n.height!==b.height)&&(n.width=b.width,n.height=b.height);const w=n.getContext("2d"),j=performance.now();w?.putImageData(b,0,0);const M=performance.now(),k=dp(n,b.width,b.height,Tp,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:b.width,height:b.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,M-j),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:_i.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:k.visualHash,visualChanged:k.visualChanged,paintedAt:M});return}Hr(n);const m=new Blob([a.payload],{type:a.mimeType}),h=await createImageBitmap(m);if(s()){h.close();return}const g=a.width||h.width||960,y=a.height||h.height||540;(n.width!==g||n.height!==y)&&(n.width=g,n.height=y);const x=n.getContext("2d");if(x){const b=performance.now();x.clearRect(0,0,g,y),x.drawImage(h,0,0,g,y);const w=performance.now(),j=dp(n,g,y);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:g,height:y,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,w-b),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:_i.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:j.visualHash,visualChanged:j.visualChanged,paintedAt:w})}h.close()}const $y="livedesk_remote_host_targets",O1="livedesk_entitlements",Dp=new TextDecoder;function H1(n){const s=(Array.isArray(n)?n:[n||Rn]).map(l=>Hl(l||Rn));return[...new Set(s.filter(Boolean))]}function P1(){const[n,a]=d.useState(null),[s,l]=d.useState(!0);return d.useEffect(()=>{let c=!0;const u=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&bt.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||bt.auth.getSession()).then(h=>{c&&(a(Mx(h)),l(!1))});const{data:{subscription:m}}=bt.auth.onAuthStateChange((h,g)=>{a(g),l(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{c=!1,u?.(),m.unsubscribe()}},[]),{session:n,loading:s}}function F1(n,a=!0){const[s,l]=d.useState(null),[c,u]=d.useState([]),[m,h]=d.useState(""),[g,y]=d.useState(""),[x,b]=d.useState(0),w=d.useRef(new Map),j=Array.isArray(n)?n.join(`
|
|
12
|
-
`):String(n||""),M=d.useMemo(()=>H1(n),[j]),k=d.useMemo(()=>M.find(T=>Uu(T)==="loopback")||M[0]||Rn,[M]),N=d.useCallback(async()=>{if(!a){l(null),u([]),y(""),h("");return}let T=null;const L=Date.now(),O=M.filter(I=>(w.current.get(I)||0)<=L);if(O.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const I of O)try{const[B,_]=await Promise.all([Ye("/api/remote/status",void 0,I),Ye("/api/remote/devices",void 0,I)]);if(!Array.isArray(_.devices))throw new Error("Invalid Hub devices response.");w.current.delete(I),l(B),u(_.devices),y(I),h("");return}catch(B){T=B,w.current.set(I,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,M]),A=d.useCallback(()=>{w.current.clear(),N().catch(T=>{h(T instanceof Error?T.message:String(T))}),b(T=>T+1)},[N]);return d.useEffect(()=>{if(!a){l(null),u([]),y(""),h("");return}let T=!0;const L=async()=>{try{await N()}catch(I){T&&h(I instanceof Error?I.message:String(I))}};L();const O=window.setInterval(L,2500);return()=>{T=!1,window.clearInterval(O)}},[a,N,x]),{status:s,devices:c,error:m,refresh:A,hubBaseUrl:g||k,hubCandidates:M}}function $1(n){const[a,s]=d.useState(null),[l,c]=d.useState(""),u=n?.user?.id||"",m=d.useCallback(async()=>{if(!u){s(null);return}const{data:h,error:g}=await bt.from($y).select("*").eq("user_id",u).maybeSingle();if(g){c(g.message);return}s(h),c("")},[u]);return d.useEffect(()=>{m()},[m]),d.useEffect(()=>{if(!u)return;const h=bt.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:$y,filter:`user_id=eq.${u}`},g=>s(g.new)).subscribe();return()=>{bt.removeChannel(h)}},[u]),{target:a,error:l,refresh:m}}function B1(n){const[a,s]=d.useState(null),[l,c]=d.useState(!1),[u,m]=d.useState(""),h=n?.user?.id||"",g=d.useCallback(async()=>{if(!h){s(null),m(""),c(!1);return}c(!0);const{data:x,error:b}=await bt.from(O1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){m(b.message),c(!1);return}s(x),m(""),c(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:y,loading:l,error:u,refresh:g}}const qu={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},U1=2500,q1=3e4,G1=64*1024,V1=6,W1=V1,Xx=new Map;function Y1(n){return Xx.get(n)}const By={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function K1(n,a,s){const l=Number(a);if(!Number.isFinite(l)||l<=0)return 0;const c=s-l,u=n.minimumHubClockOffsetMs;if(!Number.isFinite(u)||c<Number(u))return n.minimumHubClockOffsetMs=c,0;const m=Math.max(0,c-Number(u));return m>q1?(n.minimumHubClockOffsetMs=c,0):m}function Du(n){if(n==null||n==="")return;const a=Number(n);return Number.isFinite(a)?a:void 0}function Uy(n,a,s=Rn,l={}){const[c,u]=d.useState(new Map),[m,h]=d.useState("idle"),[g,y]=d.useState(""),[x,b]=d.useState(qu),w=d.useRef(new Map),j=d.useRef(new Map),M=d.useRef(0),k=d.useRef(new Map),N=d.useRef({enabled:!1,token:"",reason:""}),A=d.useRef(new Set),[T,L]=d.useState(0),O=d.useRef(l.onFrame),I=d.useRef(l.onStreamReady),B=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),_=d.useMemo(()=>[...n].sort().join(","),[n]),G=Number.isFinite(l.fps)?Number(l.fps):2,te=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,W=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,Y=Number.isFinite(l.quality)?Number(l.quality):45,F=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ve=l.streamPurpose==="control"?"control":"wall",fe=l.forceRestart===!0,Q=String(l.forceRestartToken||"").trim(),z=String(l.restartReason||"").trim();N.current={enabled:fe,token:Q,reason:z};const re=d.useMemo(()=>{const me=Object.entries(l.monitorSelections||{}).filter(([he])=>!!he).sort(([he],[J])=>he.localeCompare(J));return JSON.stringify(Object.fromEntries(me))},[l.monitorSelections]);d.useEffect(()=>{O.current=l.onFrame},[l.onFrame]),d.useEffect(()=>{I.current=l.onStreamReady},[l.onStreamReady]);const V=d.useCallback((me,he="livedesk-frame-socket-release")=>{me.disposed=!0;try{me.socket.readyState===WebSocket.CONNECTING||me.socket.readyState===WebSocket.OPEN?me.socket.close(1e3,he):me.socket.close()}catch{}},[]),H=d.useCallback(()=>{const me=[...j.current.values()].map(he=>he.socket);if(me.length===0){h("idle");return}if(me.some(he=>he.readyState===WebSocket.OPEN)){h("open");return}if(me.some(he=>he.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),le=d.useCallback((me,he,J,Ce)=>{if(he.disposed||he.socket.readyState!==WebSocket.OPEN)return!1;try{return he.socket.send(JSON.stringify({...he.payload,type:"restart-live",deviceIds:[me],forceRestart:!0,restartReason:J,restartToken:Ce})),!0}catch{return!1}},[]),oe=d.useCallback((me,he)=>{if(!me||me.byteLength<5)return;const J=Date.now(),Te=new DataView(me).getUint32(0,!1);if(Te<=0||Te+4>me.byteLength)return;const He=new Uint8Array(me,4,Te),ee=JSON.parse(Dp.decode(He)),Ue=Du(ee.hubPacketEpochMs),ft=Ue!==void 0&&Ue>0?Ue:void 0,ne=K1(he,ft,J);if(ne>U1)return;const xe=new Uint8Array(me,4+Te),Oe={deviceId:String(ee.deviceId||""),kind:ee.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(ee.frameSeq||0),streamFrameSeq:Number(ee.streamFrameSeq||0)||void 0,streamId:String(ee.streamId||""),commandId:ee.commandId?String(ee.commandId):void 0,sessionId:ee.sessionId?String(ee.sessionId):void 0,captureGeneration:Number(ee.captureGeneration||0)||void 0,streamPurpose:ee.streamPurpose?String(ee.streamPurpose):void 0,width:Number(ee.width||0),height:Number(ee.height||0),sourceWidth:Number(ee.sourceWidth||0)||void 0,sourceHeight:Number(ee.sourceHeight||0)||void 0,mimeType:String(ee.mimeType||"image/jpeg"),mode:ee.mode?String(ee.mode):void 0,frameMode:ee.frameMode?String(ee.frameMode):void 0,frameProfile:ee.frameProfile?String(ee.frameProfile):void 0,encoding:ee.encoding?String(ee.encoding):void 0,codec:ee.codec?String(ee.codec):void 0,compression:ee.compression?String(ee.compression):void 0,pixelFormat:ee.pixelFormat?String(ee.pixelFormat):void 0,bytesPerPixel:Number(ee.bytesPerPixel||0)||0,uncompressedByteLength:Number(ee.uncompressedByteLength||0)||0,h264Format:ee.h264Format?String(ee.h264Format):void 0,isKeyFrame:ee.isKeyFrame===!0,chunkType:ee.chunkType?String(ee.chunkType):void 0,timestampUs:Number(ee.timestampUs||0)||0,durationUs:Number(ee.durationUs||0)||0,sourceGapMs:Number(ee.sourceGapMs||0)||0,agentSendGapMs:Number(ee.agentSendGapMs||0)||0,agentSendDurationMs:Number(ee.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(ee.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(ee.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(ee.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(ee.agentFrameAgeMs||0)||0,nativeCaptureTelemetryAvailable:ee.nativeCaptureTelemetryAvailable===!0,nativeEncoderHardwareAccelerationKnown:ee.nativeEncoderHardwareAccelerationKnown===!0,nativeEncoderHardwareAccelerated:typeof ee.nativeEncoderHardwareAccelerated=="boolean"?ee.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:ee.nativeEncoderHardwareQueryStatus?String(ee.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureFps:Number(ee.nativeCaptureFps||0)||0,nativeEncodedFps:Number(ee.nativeEncodedFps||0)||0,nativeCaptureSampleCount:Number(ee.nativeCaptureSampleCount||0)||0,nativeEncodableFrameCount:Number(ee.nativeEncodableFrameCount||0)||0,nativeSkippedFrameCount:Number(ee.nativeSkippedFrameCount||0)||0,nativeEncodedFrameCount:Number(ee.nativeEncodedFrameCount||0)||0,nativeEncodeFramesInFlight:Number(ee.nativeEncodeFramesInFlight||0)||0,nativeBackpressureSkippedFrameCount:Number(ee.nativeBackpressureSkippedFrameCount||0)||0,nativeIdleSkippedFrameCount:Number(ee.nativeIdleSkippedFrameCount||0)||0,nativeCaptureTelemetryAt:ee.nativeCaptureTelemetryAt?String(ee.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(ee.droppedByAgent||0)||0,hubIngressDropped:Number(ee.hubIngressDropped||0)||0,hubClientDropped:Number(ee.hubClientDropped||0)||0,transport:ee.transport?String(ee.transport):void 0,videoTransport:ee.videoTransport?String(ee.videoTransport):void 0,frameTransportActive:ee.frameTransportActive?String(ee.frameTransportActive):void 0,frameTransportProtocol:ee.frameTransportProtocol?String(ee.frameTransportProtocol):void 0,frameTransportState:ee.frameTransportState?String(ee.frameTransportState):void 0,frameTransportReason:ee.frameTransportReason?String(ee.frameTransportReason):void 0,frameTransportChangedAt:ee.frameTransportChangedAt?String(ee.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(ee.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(ee.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:ee.frameTransportP2pReady===!0,hubClientQueueDepth:Number(ee.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(ee.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(ee.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(ee.udpIncompleteFrames||0)||0,hardwareEncoder:ee.hardwareEncoder?String(ee.hardwareEncoder):void 0,platformProfile:ee.platformProfile?String(ee.platformProfile):void 0,monitorIndex:Number.isFinite(Number(ee.monitorIndex))?Number(ee.monitorIndex):void 0,monitorCount:Number.isFinite(Number(ee.monitorCount))?Number(ee.monitorCount):void 0,requestedFps:Number(ee.requestedFps||0)||0,effectiveFps:Number(ee.effectiveFps||0)||0,captureTimingAvailable:ee.captureTimingAvailable===!0,captureAverageMs:Du(ee.captureAverageMs),captureP95Ms:Du(ee.captureP95Ms),slowFrameCount:Number(ee.slowFrameCount||0)||0,captureHelperRestarts:Number(ee.captureHelperRestarts||0)||0,capturedAt:String(ee.capturedAt||""),receivedAt:String(ee.receivedAt||""),hubPacketAt:ee.hubPacketAt?String(ee.hubPacketAt):void 0,hubPacketEpochMs:ft,browserReceivedEpochMs:J,hubPacketTransitAgeMs:ft!==void 0?ne:void 0,byteLength:Number(ee.byteLength||xe.byteLength),contentHash:ee.contentHash?String(ee.contentHash):void 0,captureMs:Du(ee.captureMs),captureStageMs:Du(ee.captureStageMs),convertMs:Number(ee.convertMs||0)||0,compressMs:Number(ee.compressMs||0)||0,captureSourceSerial:Number(ee.captureSourceSerial||0)||0,captureSourceSkipped:Number(ee.captureSourceSkipped||0)||0,deltaTileSize:Number(ee.deltaTileSize||0)||0,deltaTileCount:Number(ee.deltaTileCount||0)||0,deltaVisualTileCount:Number(ee.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(ee.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(ee.deltaTotalTiles||0)||0,payload:xe};if(!Oe.deviceId)return;const $e=Number(he.payload.monitorSelections?.[Oe.deviceId]);if(Number.isFinite($e)&&Number.isFinite(Number(Oe.monitorIndex))&&Number(Oe.monitorIndex)!==$e)return;const ze={streamId:he.lastFrameStreamId,commandId:he.lastFrameCommandId,order:he.lastFrameOrder},Qe=Number(Oe.streamFrameSeq||Oe.frameSeq||0),qe=!!ze.commandId&&!!Oe.commandId,We=ze.streamId===Oe.streamId&&(!qe||ze.commandId===Oe.commandId),lt=ze.order;if(We&<>=Qe&&(lt===Qe||qe))return;he.lastFrameStreamId=Oe.streamId,he.lastFrameCommandId=Oe.commandId||"",he.lastFrameOrder=Qe;const U=B.current;U.totalFrames+=1,U.totalBytes+=xe.byteLength,U.sampleFrames+=1,U.sampleBytes+=xe.byteLength;const ye=!w.current.has(Oe.deviceId);w.current.set(Oe.deviceId,Oe),ye&&u(new Map(w.current)),O.current?.(Oe)},[]);d.useEffect(()=>{const me=window.setInterval(()=>{const he=performance.now(),J=B.current,Ce=Math.max(1,he-J.sampleStartedAt);b({totalFrames:J.totalFrames,totalBytes:J.totalBytes,framesPerSecond:J.sampleFrames*1e3/Ce,bytesPerSecond:J.sampleBytes*1e3/Ce,sampleMs:Ce,lastUpdatedAt:Date.now()}),u(new Map(w.current)),J.sampleFrames=0,J.sampleBytes=0,J.sampleStartedAt=he},2e3);return()=>{window.clearInterval(me)}},[]),d.useEffect(()=>{const me=_?_.split(",").filter(Boolean):[],he=new Set(me),J=performance.now();for(const[Ce,Te]of j.current.entries())he.has(Ce)||(V(Te,"livedesk-device-unsubscribed"),j.current.delete(Ce),k.current.delete(Ce),w.current.delete(Ce));if(me.length===0){for(const Ce of j.current.values())V(Ce,"livedesk-no-devices");j.current.clear(),k.current.clear(),w.current=new Map,u(new Map),y(""),B.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},b(qu),H();return}B.current.sampleStartedAt<=0&&(B.current.sampleStartedAt=J,b({...qu,lastUpdatedAt:Date.now()}));for(const Ce of me){const Te=Number(l.monitorSelections?.[Ce]),He=Number.isInteger(Te)&&Te>=0?Te:0,ee={[Ce]:He},Ue={type:"subscribe",deviceIds:[Ce],autoStartLive:a,fps:G,maxWidth:te,maxHeight:W,quality:Y,mode:F,frameMode:F,streamPurpose:ve,monitorSelections:ee},ft=JSON.stringify(Ue),ne=j.current.get(Ce),xe=Number(ne?.payload.monitorSelections?.[Ce]),Oe=Number(ee[Ce]),$e=!!ne&&Number.isFinite(xe)&&Number.isFinite(Oe)&&xe!==Oe;if(ne){const We=ne.socket.readyState===WebSocket.CONNECTING||ne.socket.readyState===WebSocket.OPEN;if(ne.payloadKey===ft&&We&&!ne.disposed)continue}const ze=ne&&(ne.socket.readyState===WebSocket.CONNECTING||ne.socket.readyState===WebSocket.OPEN)&&!ne.disposed?ne.handoffFrom&&!ne.handoffCompleted?ne.handoffFrom:ne:void 0;ne&&ne!==ze&&V(ne,"livedesk-subscription-superseded");const Qe=new WebSocket(Vf(`/api/remote/frames/ws?devices=${encodeURIComponent(Ce)}`,s));Qe.binaryType="arraybuffer";const qe={socket:Qe,payload:Ue,payloadKey:ft,generation:M.current+1,monitorRestartToken:$e?`monitor-${Ce}-${Oe}-${M.current+1}`:"",disposed:!1,handoffFrom:ze,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};M.current=qe.generation,$e&&(w.current.delete(Ce),u(new Map(w.current))),j.current.set(Ce,qe),Qe.addEventListener("open",()=>{if(qe.disposed||j.current.get(Ce)!==qe){V(qe,"livedesk-stale-frame-socket");return}y("");const We=N.current,lt=We.enabled&&(!We.token||k.current.get(Ce)!==We.token),U=lt||qe.monitorRestartToken!=="",ye=lt?We.token:qe.monitorRestartToken,je=lt?We.reason:qe.monitorRestartToken?"monitor-selection-change":"";Qe.send(JSON.stringify({...qe.payload,forceRestart:U,restartReason:U?je:"",restartToken:U?ye:""})),lt&&We.token&&k.current.set(Ce,We.token);const Fe=qe.handoffFrom;qe.handoffFrom=void 0,qe.handoffCompleted=!0,Fe&&!Fe.disposed&&V(Fe,"livedesk-subscription-replaced"),H()}),Qe.addEventListener("message",We=>{if(qe.disposed||j.current.get(Ce)!==qe)return;if(typeof We.data=="string"){try{const U=JSON.parse(We.data);if(U?.type==="RemoteFrameSubscriptionError")y(String(U.error||"control-stream-start-failed"));else if(U?.type==="RemoteFrameLiveAutoStart"){const je=(Array.isArray(U.skipped)?U.skipped:[]).find(Fe=>Fe?.deviceId===Ce);if(je)y(String(je.reason||"control-stream-start-failed"));else if(Array.isArray(U.started)){const Fe=U.started.find(ut=>ut?.deviceId===Ce);Fe&&(y(""),Fe.ready===!0&&Fe.streamPurpose==="control"&&Fe.sessionId&&Fe.commandId&&Number(Fe.captureGeneration||0)>0&&I.current?.({deviceId:Ce,sessionId:String(Fe.sessionId),streamId:String(Fe.streamId||""),streamPurpose:"control",commandId:String(Fe.commandId),captureGeneration:Number(Fe.captureGeneration),monitorIndex:Number(Fe.monitorIndex||0)}))}}else U?.type==="RemoteFrameStreamReady"&&U.deviceId===Ce&&U.streamPurpose==="control"&&U.sessionId&&U.commandId&&Number(U.captureGeneration||0)>0&&(y(""),I.current?.({deviceId:Ce,sessionId:String(U.sessionId),streamId:String(U.streamId||""),streamPurpose:"control",commandId:String(U.commandId),captureGeneration:Number(U.captureGeneration),monitorIndex:Number(U.monitorIndex||0)}))}catch{}return}const lt=We.data instanceof ArrayBuffer?We.data:null;lt&&(y(""),oe(lt,qe))}),Qe.addEventListener("error",()=>{qe.disposed||j.current.get(Ce)!==qe||h("connecting")}),Qe.addEventListener("close",()=>{const We=!qe.disposed;qe.disposed=!0;const lt=j.current.get(Ce);let U=!1;if(lt===qe){const ye=qe.handoffFrom;qe.handoffFrom=void 0,ye&&!ye.disposed&&(ye.socket.readyState===WebSocket.CONNECTING||ye.socket.readyState===WebSocket.OPEN)?(j.current.set(Ce,ye),U=!0):j.current.delete(Ce)}if(H(),We&<===qe&&!U){const ye=window.setTimeout(()=>{A.current.delete(ye),L(je=>je+1)},750);A.current.add(ye)}})}H()},[a,V,_,G,F,oe,s,W,te,re,l.monitorSelections,Y,T,ve,H]),d.useEffect(()=>{if(!fe||!Q)return;const me=_?_.split(",").filter(Boolean):[];for(const he of me){if(k.current.get(he)===Q)continue;const J=j.current.get(he);!J||!le(he,J,z,Q)||k.current.set(he,Q)}},[_,fe,Q,z,le]),d.useEffect(()=>()=>{for(const me of j.current.values())V(me,"livedesk-hook-unmount");j.current.clear();for(const me of A.current)window.clearTimeout(me);A.current.clear()},[V]);const X=d.useCallback((me,he="browser-stale")=>{const J=Array.isArray(me)&&me.length>0?me:_.split(",").filter(Boolean);if(J.length===0)return!1;let Ce=!1;for(const Te of J){const He=j.current.get(Te);!He||He.socket.readyState!==WebSocket.OPEN||(Ce=le(Te,He,he,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Ce)}return Ce},[_,le]),be=d.useCallback((me,he="browser-reconnect")=>{const J=Array.isArray(me)&&me.length>0?me:_.split(",").filter(Boolean);if(J.length===0)return!1;let Ce=!1;for(const Te of J){const He=j.current.get(Te);He&&(V(He,`livedesk-${he}`),j.current.delete(Te),k.current.delete(Te),w.current.delete(Te),Ce=!0)}return Ce&&u(new Map(w.current)),L(Te=>Te+1),H(),!0},[V,_,H]);return{frames:c,state:m,error:g,stats:x,restartLive:X,reconnectLive:be}}function Q1(n,a,s=Rn,l={}){const[c,u]=d.useState(null),[m,h]=d.useState(null),[g,y]=d.useState("idle"),[x,b]=d.useState(qu),w=d.useRef(null),j=d.useRef(l.onFrame),M=d.useRef(null),k=d.useRef(0),N=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),A=d.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=d.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),L=d.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),O=d.useMemo(()=>({deviceIds:A.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(l.fps||20),inputFps:Number(l.inputFps||8),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[T,A,L,l.fps,l.height,l.inputFps,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),I=d.useMemo(()=>JSON.stringify(O),[O]),B=d.useRef(O);B.current=O;const _=a&&O.deviceIds.length>0,G=d.useCallback(W=>W.readyState!==WebSocket.OPEN?!1:(W.send(JSON.stringify({type:"configure",...B.current})),!0),[]);d.useEffect(()=>{j.current=l.onFrame},[l.onFrame]),d.useEffect(()=>{const W=window.setInterval(()=>{const Y=N.current,F=performance.now(),ve=Math.max(1,F-Y.sampleStartedAt);b({totalFrames:Y.totalFrames,totalBytes:Y.totalBytes,framesPerSecond:Y.sampleFrames*1e3/ve,bytesPerSecond:Y.sampleBytes*1e3/ve,sampleMs:ve,lastUpdatedAt:Date.now()});const fe=M.current;fe&&fe.frameSeq!==k.current&&(k.current=fe.frameSeq,u(fe)),Y.sampleFrames=0,Y.sampleBytes=0,Y.sampleStartedAt=F},1e3);return()=>window.clearInterval(W)},[]),d.useEffect(()=>{if(!_){w.current?.close(),w.current=null,u(null),M.current=null,k.current=0,h(null),y("idle"),b(qu);return}let W=!1,Y=0;const F=()=>{if(W)return;const ve=new WebSocket(Vf("/api/remote/atlas/ws",s));ve.binaryType="arraybuffer",w.current=ve,y("connecting"),ve.addEventListener("open",()=>{N.current.sampleStartedAt=performance.now(),y("open"),G(ve)}),ve.addEventListener("message",fe=>{if(typeof fe.data=="string"){try{const z=JSON.parse(fe.data);z?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(z.layoutVersion||0),width:Number(z.width||1920),height:Number(z.height||1080),columns:Number(z.columns||1),rows:Number(z.rows||1),tiles:Array.isArray(z.tiles)?z.tiles:[]})}catch{}return}const Q=fe.data instanceof ArrayBuffer?fe.data:null;if(!(!Q||Q.byteLength<5))try{const z=Date.now(),V=new DataView(Q).getUint32(0,!1);if(V<=0||V+4>Q.byteLength)return;const H=JSON.parse(Dp.decode(new Uint8Array(Q,4,V))),le=new Uint8Array(Q,4+V),oe={deviceId:String(H.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(H.frameSeq||0),streamFrameSeq:Number(H.streamFrameSeq||0)||void 0,streamId:String(H.streamId||"mode4-atlas"),commandId:H.commandId?String(H.commandId):void 0,width:Number(H.width||1920),height:Number(H.height||1080),sourceWidth:Number(H.sourceWidth||H.width||1920),sourceHeight:Number(H.sourceHeight||H.height||1080),mimeType:String(H.mimeType||"video/h264"),mode:String(H.mode||"mode4-h264-atlas"),frameMode:String(H.frameMode||"mode4-h264-atlas"),frameProfile:String(H.frameProfile||"mode4-h264-atlas-v1"),encoding:String(H.encoding||"video-atlas"),codec:String(H.codec||"h264"),compression:String(H.compression||"video/h264"),h264Format:String(H.h264Format||"annexb"),isKeyFrame:H.isKeyFrame===!0,chunkType:String(H.chunkType||""),timestampUs:Number(H.timestampUs||0),durationUs:Number(H.durationUs||0),transport:H.transport?String(H.transport):void 0,videoTransport:H.videoTransport?String(H.videoTransport):void 0,frameTransportActive:H.frameTransportActive?String(H.frameTransportActive):void 0,frameTransportProtocol:H.frameTransportProtocol?String(H.frameTransportProtocol):void 0,frameTransportState:H.frameTransportState?String(H.frameTransportState):void 0,frameTransportReason:H.frameTransportReason?String(H.frameTransportReason):void 0,frameTransportChangedAt:H.frameTransportChangedAt?String(H.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(H.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(H.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:H.frameTransportP2pReady===!0,hubClientQueueDepth:Number(H.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(H.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(H.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(H.udpIncompleteFrames||0)||0,hardwareEncoder:H.hardwareEncoder?String(H.hardwareEncoder):void 0,platformProfile:H.platformProfile?String(H.platformProfile):void 0,capturedAt:String(H.capturedAt||""),receivedAt:String(H.receivedAt||""),hubPacketAt:H.hubPacketAt?String(H.hubPacketAt):void 0,hubPacketEpochMs:Number(H.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:z,byteLength:le.byteLength,layoutVersion:Number(H.layoutVersion||0),atlasComposeMs:Number(H.atlasComposeMs||0),atlasPoolStarved:Number(H.atlasPoolStarved||0),atlasReadyTiles:Number(H.atlasReadyTiles||0),atlasTileCount:Number(H.atlasTileCount||0),atlasInputRevision:Number(H.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(H.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(H.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(H.atlasSourceMaxAgeMs||0),payload:le},X=N.current;X.totalFrames+=1,X.totalBytes+=le.byteLength,X.sampleFrames+=1,X.sampleBytes+=le.byteLength,M.current=oe,k.current===0&&(k.current=oe.frameSeq,u(oe)),j.current?.(oe)}catch{}}),ve.addEventListener("error",()=>y("error")),ve.addEventListener("close",()=>{w.current===ve&&(w.current=null),!W&&(y("closed"),Y=window.setTimeout(F,1200))})};return F(),()=>{W=!0,window.clearTimeout(Y),w.current?.close(),w.current=null}},[_,s,G]),d.useEffect(()=>{if(!_)return;const W=w.current;W&&G(W)},[I,_,G]);const te=d.useCallback(()=>{const W=w.current;return W?G(W):!1},[G]);return{frame:c,layout:m,state:g,stats:x,refreshInputs:te}}function X1(n,a=Rn){const s=d.useRef(null),l=d.useRef(0),c=d.useRef(0),u=d.useRef(new Map),m=d.useRef(""),[h,g]=d.useState("idle"),[y,x]=d.useState(""),[b,w]=d.useState(By),j=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});d.useEffect(()=>{if(!n){s.current?.close(),s.current=null,c.current=0,m.current="",u.current.clear(),g("idle"),x(""),w(By);return}let k=!1,N=0;const A=()=>{if(k)return;const T=new WebSocket(Vf("/api/remote/input/ws",a));s.current=T,j.current.sampleStartedAt=performance.now(),g("connecting"),x(""),T.addEventListener("open",()=>{k||s.current!==T||(x(""),g("open"))}),T.addEventListener("message",L=>{if(!(k||s.current!==T||typeof L.data!="string"))try{const O=JSON.parse(L.data),I=Number(O.inputSeq||O.result?.inputSeq||0),B=String(O.deviceId||O.result?.deviceId||""),_=String(O.inputEventId||O.result?.inputEventId||""),G=u.current.get(I);if(B&&(G&&G.deviceId!==B||!G&&m.current&&m.current!==B)||G?.inputEventId&&_&&G.inputEventId!==_)return;if(O?.type==="RemoteInputError"){I>0&&u.current.delete(I),x(String(O.error||O.result?.error||"Remote input failed.")),T.readyState===WebSocket.OPEN&&g("open");return}if(O?.type!=="RemoteInputApplied")return;G&&(j.current.lastRoundTripMs=Math.max(0,performance.now()-G.sentAt),u.current.delete(I)),j.current.lastInputSeq=I,j.current.lastAgentApplyMs=Math.max(0,Number(O.agentApplyMs||0)),x(""),g("open")}catch{}}),T.addEventListener("close",()=>{k||s.current!==T||(s.current=null,g("closed"),N=window.setTimeout(A,1200))}),T.addEventListener("error",()=>{!k&&s.current===T&&g("error")})};return A(),()=>{k=!0,window.clearTimeout(N);const T=s.current;s.current=null,T?.close(),u.current.clear()}},[n,a]),d.useEffect(()=>{if(!n)return;const k=window.setInterval(()=>{const N=performance.now(),A=j.current,T=Math.max(1,N-A.sampleStartedAt);w({totalSent:A.totalSent,totalDropped:A.totalDropped,sentPerSecond:A.sampleSent*1e3/T,droppedPerSecond:A.sampleDropped*1e3/T,bufferedAmount:s.current?.bufferedAmount||0,lastInputType:A.lastInputType,lastInputSeq:A.lastInputSeq,lastRoundTripMs:A.lastRoundTripMs,lastAgentApplyMs:A.lastAgentApplyMs,lastUpdatedAt:Date.now()}),A.sampleSent=0,A.sampleDropped=0,A.sampleStartedAt=N},1e3);return()=>window.clearInterval(k)},[n]);const M=d.useCallback((k,N)=>{const A=s.current;if(!A||A.readyState!==WebSocket.OPEN||!k)return!1;const T=String(N.type||"").toLowerCase(),L=T==="pointermove",I=L||T==="wheel",B=j.current;if(L&&A.bufferedAmount>G1)return B.totalDropped+=1,B.sampleDropped+=1,B.lastInputType="pointermove-drop",!1;const _=l.current+1;l.current=_;const G=`${_}-${crypto.randomUUID()}`,te=Date.now(),W=!I||_-c.current>=W1;for(W&&(u.current.set(_,{sentAt:performance.now(),deviceId:k,inputEventId:G}),I&&(c.current=_)),m.current=k,L||Xx.set(k,{inputSeq:_,inputType:T||"input",sentAt:performance.now()});u.current.size>256;){const Y=u.current.keys().next().value;if(Y===void 0)break;u.current.delete(Y)}return A.send(JSON.stringify({type:"input",requestId:I?"":crypto.randomUUID(),fireAndForget:I,deviceId:k,input:{...N,inputEventId:G,inputSeq:_,requestAck:W,issuedAtEpochMs:te,issuedAt:new Date(te).toISOString()}})),B.totalSent+=1,B.sampleSent+=1,B.lastInputType=T||"input",!0},[]);return{state:h,sendInput:M,stats:b,error:y}}function Z1(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const rf={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,lastUpdatedAt:0},J1=.08,ek=.25,tk=.02,qy=300,nk=4,sf=1500,Th=5e3,ak=2e3,rk=1e4,lf=[0,1e3,3e3];function Gy(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function sk(n,a,s){const l=Math.max(1,Math.min(8,Math.floor(a.channels||2))),c=Math.max(8e3,Math.min(192e3,Math.floor(a.sampleRate||48e3))),u=String(a.mimeType||"").toLowerCase(),m=u.includes("s16le")||u.includes("audio/l16"),h=m?2:4,g=Math.floor(s.byteLength/h),y=Math.floor(g/l),x=n.createBuffer(l,y,c),b=new DataView(s);for(let w=0;w<l;w+=1){const j=x.getChannelData(w);for(let M=0;M<y;M+=1){const N=(M*l+w)*h;j[M]=m?Math.max(-1,Math.min(1,b.getInt16(N,!0)/32768)):Math.max(-1,Math.min(1,b.getFloat32(N,!0)))}}return x}function ik(n,a,s=Rn){const l=d.useRef(null),c=d.useRef(0),[u,m]=d.useState("idle"),[h,g]=d.useState(null),[y,x]=d.useState(rf),[b,w]=d.useState("");return d.useEffect(()=>{if(!a||!n){m("idle"),g(null),x(rf),w("");return}m("connecting"),g(null),x(rf),w("");const j=window.AudioContext||window.webkitAudioContext;if(!j){m("unsupported"),x(rf),w("Audio playback is not supported in this browser.");return}const M=new j;l.current=M,c.current=M.currentTime;const k=new WebSocket(Vf("/api/remote/audio/ws?devices="+encodeURIComponent(n),s));k.binaryType="arraybuffer";const N=new Set,A={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(M.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let T=!1,L=0,O=!1,I=0,B=0;const _=(z=!0)=>{for(const re of N)try{re.stop()}catch{}N.clear(),z&&(c.current=M.currentTime+J1)},G=()=>{A.audioContextState=String(M.state),!T&&(A.audioContextState==="suspended"||A.audioContextState==="interrupted"?m("suspended"):A.audioContextState==="closed"&&(m("error"),w("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},te=async()=>{if(T||String(M.state)==="closed")return!1;try{if(String(M.state)!=="running"&&await M.resume(),A.audioContextState=String(M.state),!T&&!O&&A.audioContextState==="running"){const z=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=sf,re=A.lastCaptureStatusAt>0&&performance.now()-A.lastCaptureStatusAt<=Th&&A.captureAlive&&A.helperAlive;m(z?"playing":re?"silent":"open")}return A.audioContextState==="running"}catch(z){return T||(m("suspended"),w(z instanceof Error?"Audio playback is suspended: "+z.message:"Audio playback is suspended.")),!1}},W=async()=>{if(T||O||k.readyState!==WebSocket.OPEN)return;if(I>=lf.length){m("error"),w("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const z=I;I+=1,O=!0,A.stalledCount+=1,A.automaticRestarts+=1,m("reconnecting");try{const re=await Ye("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},s);if(re.ok===!1)throw new Error(re.error||"Remote audio stop failed.");if(T)return;const V=await Ye("/api/remote/devices/"+encodeURIComponent(n)+"/audio/start",{method:"POST",body:JSON.stringify({streamId:"audio-restart-"+Date.now(),mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},s);if(V.ok===!1)throw new Error(V.error||"Remote audio start failed.");const H=performance.now();L=H,A.lastPacketAt=H,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,B=H+(lf[z+1]??3e3),w(""),T||m("open")}catch(re){T||(B=performance.now()+(lf[z+1]??3e3),m("error"),w(re instanceof Error?"Remote audio restart failed: "+re.message:"Remote audio restart failed."))}finally{O=!1}},Y=()=>{A.drops+=1},F=window.setInterval(()=>{if(T)return;const z=performance.now(),re=A.lastPacketAt>0?Math.max(0,z-A.lastPacketAt):L>0?Math.max(0,z-L):0,V=A.lastAcceptedAt>0?Math.max(0,z-A.lastAcceptedAt):0,H=A.lastCaptureStatusAt>0?Math.max(0,z-A.lastCaptureStatusAt):0,le=k.readyState===WebSocket.OPEN,oe=A.lastCaptureStatusAt>0,X=oe&&H<=Th,be=oe&&(!A.captureAlive||!A.helperAlive)&&H>ak,me=oe&&H>Th,he=!oe&&L>0&&z-L>rk,J=L>0&&(A.lastAcceptedAt<=0?z-L>sf:V>sf);le&&L>0&&(be||me||he)?I>=lf.length&&!O?(m("error"),w("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!O&&z>=B?W():O||m("stalled"):le&&J&&!O&&A.audioContextState!=="suspended"&&A.audioContextState!=="interrupted"&&m(X?"silent":"open"),x({queuedMs:Math.max(0,(c.current-M.currentTime)*1e3),browserAgeMs:A.browserAgeMs,captureAgeMs:A.captureAgeMs,captureStatusAgeMs:H,silentForMs:A.silentForMs,captureAlive:A.captureAlive,helperAlive:A.helperAlive,captureRestartCount:A.captureRestartCount,localProcessingAgeMs:A.localProcessingAgeMs,lastPacketAgeMs:re,lastAcceptedAgeMs:V,framesReceived:A.framesReceived,drops:A.drops,resyncs:A.resyncs,pendingDecodes:A.pendingDecodes,lastFrameSeq:A.lastFrameSeq,audioContextState:A.audioContextState,stalledCount:A.stalledCount,automaticRestarts:A.automaticRestarts,lastUpdatedAt:Date.now()})},250),ve=()=>{G(),(String(M.state)==="suspended"||String(M.state)==="interrupted")&&te()},fe=()=>{document.visibilityState==="visible"&&te()},Q=()=>{te()};return M.addEventListener("statechange",ve),document.addEventListener("visibilitychange",fe),window.addEventListener("pageshow",Q),window.addEventListener("pointerdown",Q),window.addEventListener("keydown",Q),m("connecting"),w(""),G(),k.addEventListener("open",()=>{T||(L=performance.now(),A.lastPacketAt=L,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,m("open"),k.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),te())}),k.addEventListener("message",z=>{if(typeof z.data=="string")return;const re=z.data instanceof ArrayBuffer?z.data:null;if(!re||re.byteLength<5)return;const V=performance.now();A.lastPacketAt=V,(async()=>{try{const le=new DataView(re).getUint32(0,!1);if(le<=0||le+4>re.byteLength){Y();return}const oe=new Uint8Array(re,4,le),X=JSON.parse(Dp.decode(oe)),be=re.slice(4+le),me=String(X.frameKind||X.kind||"").toLowerCase();if(X.type==="remote.audio.status"||me==="audio-status"){if(A.lastCaptureStatusAt=V,A.captureAlive=X.captureAlive===!0,A.helperAlive=X.helperAlive===!0,A.captureRestartCount=Math.max(0,Number(X.restartCount||0)||0),A.lastPcmAtEpochMs=Math.max(0,Number(X.lastPcmAtEpochMs||0)||0),A.silentForMs=Math.max(0,Number(X.silentForMs||0)||0),A.captureAgeMs=A.lastPcmAtEpochMs>0?Math.max(0,Date.now()-A.lastPcmAtEpochMs):A.silentForMs,A.captureAlive&&A.helperAlive){if(I=0,B=0,!O){w("");const J=String(M.state)==="running",Ce=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=sf;m(J?Ce?"playing":"silent":"suspended")}}else O||m("stalled");return}const he={deviceId:String(X.deviceId||""),frameSeq:Number(X.frameSeq||0),streamId:String(X.streamId||""),mimeType:String(X.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(X.sampleRate||48e3),channels:Number(X.channels||2),capturedAt:String(X.capturedAt||""),receivedAt:String(X.receivedAt||""),byteLength:Number(X.byteLength||be.byteLength),payload:be};if(!he.deviceId||T)return;if(performance.now()-V>qy){Y();return}if(A.pendingDecodes>=nk){Y();return}A.pendingDecodes+=1;try{const J=Z1(he.mimeType)?sk(M,he,be):await M.decodeAudioData(be.slice(0));if(A.localProcessingAgeMs=Math.max(0,performance.now()-V),T)return;if(A.localProcessingAgeMs>qy){Y();return}if(he.frameSeq>0&&he.frameSeq<=A.lastFrameSeq){Y();return}if(A.activeStreamId&&he.streamId!==A.activeStreamId&&he.frameSeq<=A.lastFrameSeq){Y();return}he.streamId&&he.streamId!==A.activeStreamId&&(A.activeStreamId=he.streamId,A.lastFrameSeq=0,_());const Ce=M.currentTime;Math.max(0,c.current-Ce)>ek&&(_(),A.resyncs+=1);const He=M.createBufferSource();He.buffer=J,He.connect(M.destination),N.add(He),He.onended=()=>{N.delete(He),He.onended=null};const ee=Math.max(M.currentTime+tk,c.current);He.start(ee),c.current=ee+J.duration,A.browserAgeMs=Gy(he.receivedAt),A.captureAgeMs=Gy(he.capturedAt),A.lastAcceptedAt=performance.now(),A.framesReceived+=1,A.lastFrameSeq=he.frameSeq,I=0,B=0,g(he),te();const Ue=String(M.state)==="running";Ue&&w(""),m(Ue?"playing":"suspended")}finally{A.pendingDecodes=Math.max(0,A.pendingDecodes-1)}}catch(H){T||(m("error"),w(H instanceof Error?H.message:String(H)))}})()}),k.addEventListener("error",()=>{T||(m("error"),w("Remote audio WebSocket error."))}),k.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(F),M.removeEventListener("statechange",ve),document.removeEventListener("visibilitychange",fe),window.removeEventListener("pageshow",Q),window.removeEventListener("pointerdown",Q),window.removeEventListener("keydown",Q),_(!1),k.close(),M.close().catch(()=>{}),l.current===M&&(l.current=null)}},[n,a,s]),{state:u,lastFrame:h,stats:y,error:b}}const lk=3;function Vy(n,a,s){const l=Math.max(1,Number(s)||1),c=Math.max(0,Math.min(l,Number(n)-Number(a))),u=Math.min(l/2,lk);return c<=u?0:c>=l-u?1:c/l}function ok(n,a,s){return{normalizedX:Vy(n,s.left,s.width),normalizedY:Vy(a,s.top,s.height)}}const Hf=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),ck=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),Wy=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),fp=64;function Yf(n,a=80){return String(n||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,a)}function mp(n){const a=Yf(n);return Object.prototype.hasOwnProperty.call(Wy,a)?Wy[a]:a}function uk(n={}){const a=Yf(n.key),s=Number.isFinite(Number(n.location))?Math.max(0,Math.min(3,Math.trunc(Number(n.location)))):0,l=s===2?"Right":"Left";return a==="Shift"?`Shift${l}`:a==="Control"?`Control${l}`:a==="Alt"||a==="AltGraph"?`Alt${l}`:a==="Meta"||a==="OS"?`Meta${l}`:a?`Key:${s}:${a}`.slice(0,80):""}function hp(n={}){return mp(n.code)||uk(n)}function Af(n){for(const[a,s]of Object.entries(Hf))if(s.includes(n))return a;return""}function Dl(n,a){return Hf[a].some(s=>n.has(s))}function Yy(n,a,s={}){for(const l of Object.keys(Hf)){const c=s[l]===!0,u=Hf[l];if(c){!Dl(n,l)&&n.size<fp&&n.add(ck[l]);continue}for(const m of u)a.has(m)||n.delete(m)}}function dk(n,a){if(n.length!==a.size)return!1;let s=0;for(const l of a){if(n[s]!==l)return!1;s+=1}return!0}function Ky(n){for(const a of[...n])Af(a)||n.delete(a)}function pp(n){return{shiftKey:Dl(n,"shiftKey"),ctrlKey:Dl(n,"ctrlKey"),altKey:Dl(n,"altKey"),metaKey:Dl(n,"metaKey")}}function fk(n={},a={}){return{shiftKey:n.shiftKey===!0||a.shiftKey===!0,ctrlKey:n.ctrlKey===!0||a.ctrlKey===!0,altKey:n.altKey===!0||a.altKey===!0,metaKey:n.metaKey===!0||a.metaKey===!0}}function mk(n,a,s){const l=hp(n),c=Yf(n.key),u=Number(n.keyCode??n.which),m=Number(n.location);return{type:a,key:c,code:l,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(m)?Math.max(0,Math.min(255,Math.trunc(m))):0,text:c.length===1?c:"",repeat:a==="keydown"&&n.repeat===!0,pressedCodes:[...s],...pp(s)}}function hk(){const n=new Set,a=new Set,s=()=>({pressedCodes:[...n]});return{event(l={},c=""){if(c!=="keydown"&&c!=="keyup")return null;const u=hp(l);if(!u)return null;const m=Af(u),h=n.has(u),g=[...n];return m?(c==="keydown"?n.size<fp&&n.add(u):a.has(u)||n.delete(u),Yy(n,a,l)):(Yy(n,a,l),c==="keydown"?n.size<fp&&n.add(u):n.delete(u)),c==="keyup"&&m==="metaKey"&&!Dl(n,"metaKey")&&Ky(n),c==="keydown"&&h&&l.repeat!==!0&&dk(g,n)?null:mk(l,c,n)},modifier(l,c){const u=mp(l),m=Af(u);if(!m)return null;const h=a.has(u);return c===h?null:(c?(a.add(u),n.add(u)):(a.delete(u),n.delete(u),m==="metaKey"&&!Dl(n,"metaKey")&&Ky(n)),{type:c?"keydown":"keyup",key:m==="metaKey"?"Meta":m==="ctrlKey"?"Control":m==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...s(),...pp(n)})},reset(l="keyboard-owner-reset",c=!1){const u=n.size>0;return n.clear(),a.clear(),!u&&!c?null:{type:"keyboard.reset",reason:Yf(l,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(l={}){const c=typeof l=="string"?mp(l):hp(l);if(n.has(c))return!0;const u=Af(c);return!!u&&Dl(n,u)},snapshot(){return{...s(),latchedCodes:[...a],...pp(n)}}}}const Zx=64,pk=2;function Jx(n){const a=Math.floor(Number(n));return Number.isFinite(a)?Math.max(1,Math.min(Zx,a)):1}function Lp(n){const a=Math.floor(Number(n));return Number.isFinite(a)?Math.max(0,Math.min(Zx-1,a)):0}function ew(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"||a==="linux"||a.startsWith("linux ")}function gk(n,a,s){const l=String(a||"").trim();if(!l)return n||null;const c=String(s||"").trim();return n&&n.fingerprint===l&&(c?n.sampleId===c:n.sampleId==="")?n:{fingerprint:l,sampleId:c,consecutiveSamples:n?.fingerprint===l?n.consecutiveSamples+1:1}}function tw({platform:n,topologyFingerprint:a,consecutiveTopologySamples:s}){return ew(n)?!!String(a||"").trim()&&Number(s)>=pk:!0}function vk({requestedIndex:n,monitorCount:a,platform:s,topologyFingerprint:l,consecutiveTopologySamples:c}){const u=Lp(n),m=Jx(a);return u<m||!tw({platform:s,topologyFingerprint:l,consecutiveTopologySamples:c})?u:m-1}function yk(n,a,s){const l=Lp(n),c=Jx(a);return l<c||ew(s)?l:c-1}function Tc(n){const a=Number(n);return Number.isSafeInteger(a)&&a>0?a:0}function ta(n){return String(n||"").trim()}function of(n,a,s={}){return{deviceId:ta(n),transitionGeneration:Tc(a),sessionId:ta(s.sessionId),streamId:ta(s.streamId),commandId:ta(s.commandId),captureGeneration:Tc(s.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(s.monitorIndex)||0))}}function vr(n,a){return!!n&&!!a&&ta(n.deviceId)===ta(a.deviceId)&&Tc(n.transitionGeneration)===Tc(a.transitionGeneration)}function Qy(n,a){const s=Promise.resolve(n).catch(()=>{}).then(a);return{result:s,tail:s.then(()=>{},()=>{})}}function cf(n,a,s){const l=ta(n);return!l||!a||ta(a.deviceId)!==l?!1:!s||ta(s.deviceId)!==l}function Xy(n,a){if(!n||!a)return!1;const s=Tc(a.captureGeneration),l=ta(a.commandId),c=ta(a.sessionId),u=ta(a.streamId),m=Number(n.monitorIndex);return!s||!l||!c||!u||!Number.isInteger(m)||m<0?!1:ta(n.deviceId)===ta(a.deviceId)&&ta(n.sessionId)===c&&ta(n.streamId)===u&&ta(n.commandId)===l&&Tc(n.captureGeneration)===s&&ta(n.streamPurpose).toLowerCase()==="control"&&m===a.monitorIndex}const br=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,directFullFpsDeviceLimit:6,directMinAdaptiveFps:8,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,maxDirectFramesPerSecond:180,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function bk(n,a){const s=Math.max(0,Math.floor(Number(a)||0));return n===!0&&s>0}function Lu({mode4Enabled:n,directMode4WallEnabled:a,isMac:s}){return"direct"}function xk({mode4Enabled:n,directMode4WallEnabled:a,adaptiveFps:s,directDeviceCount:l,adaptive:c=!0}){const u=Math.max(1,Math.floor(Number(s)||1));if(!c)return u;const m=Math.max(1,Math.floor(Number(l)||1));return m<=br.directFullFpsDeviceLimit?u:Math.max(br.directMinAdaptiveFps,Math.min(u,Math.floor(br.maxDirectFramesPerSecond/m)))}function wk({deviceCount:n,targetFps:a,adaptive:s=!0}){const l=Math.max(1,Math.floor(Number(n)||1)),c=Math.max(1,Math.min(br.scalableAtlasMaxInputFps,Math.floor(Number(a)||br.scalableAtlasMaxInputFps)));if(!s)return c;const u=Math.max(br.scalableAtlasMinInputFps,Math.min(br.scalableAtlasMaxInputFps,Math.floor(br.scalableAtlasAggregateInputFps/l)));return Math.min(c,u)}function Sk(n,a){return{acceleration:br.directDecodeAcceleration,latencyMode:br.directLatencyMode}}const bo={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},Ck=[{id:"connection",label:"Connection",icon:qf},{id:"remote-access",label:"Remote Access",icon:Yn},{id:"capture-audio",label:"Capture & Audio",icon:Zh},{id:"agent",label:"Agent",icon:Il}];function Nf(n,a){return n?.settings?.[a]||bo.settings[a]||{}}function Zy(n,a){return{...n,settings:{...n.settings,[a.section]:{...Nf(n,a.section),[a.key]:a.value}}}}function Rh(n){return{revision:Number(n.revision||0),updatedAt:n.updatedAt,settings:n.settings}}function vc({icon:n,title:a,description:s,children:l,recommended:c=!1}){return i.jsxs("div",{className:"product-setting-row",children:[i.jsx("div",{className:"product-setting-control",children:l}),n&&i.jsx("span",{className:"product-setting-icon",children:i.jsx(n,{size:17})}),i.jsxs("div",{className:"product-setting-copy",children:[i.jsx("strong",{children:a}),c&&i.jsx("em",{children:"Recommended"}),i.jsx("small",{children:s})]})]})}function uf({checked:n,onChange:a,label:s}){return i.jsxs("label",{className:"product-switch",children:[i.jsx("input",{"aria-label":s,type:"checkbox",checked:n,onChange:l=>a(l.target.checked)}),i.jsx("span",{})]})}function Jy({value:n,onChange:a,options:s,label:l}){return i.jsx("select",{"aria-label":l,value:String(n),onChange:c=>a(c.target.value),children:s.map(([c,u])=>i.jsx("option",{value:c,children:u},c))})}function kk({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:s="",sessionAccessToken:l="",initialTab:c="connection",pin:u,agent:m,captureGallery:h}){const[g,y]=d.useState(c),[x,b]=d.useState(null),[w,j]=d.useState("loading"),[M,k]=d.useState(""),[N,A]=d.useState("idle"),[T,L]=d.useState(""),O=d.useRef(null),I=d.useRef(null),B=d.useRef([]),_=d.useRef(Promise.resolve()),G=d.useRef(0),te=d.useRef(0);d.useEffect(()=>{const oe=++te.current;let X=!0;return B.current=[],I.current=null,O.current=null,_.current=Promise.resolve(),j("loading"),Ye("/api/settings",void 0,n).then(be=>{if(!X||oe!==te.current)return;const me=Rh(be);I.current=me,O.current=me,b(me),j("saved")}).catch(be=>{!X||oe!==te.current||(k(be instanceof Error?be.message:String(be)),I.current=bo,O.current=bo,b(bo),j("failed"))}),()=>{X=!1}},[n]);const W=async(oe,X,be)=>{const me={id:++G.current,section:oe,key:X,value:be},he=te.current;B.current.push(me);const J=Zy(O.current||I.current||bo,me);O.current=J,b(J),j("saving"),k(""),_.current=_.current.then(async()=>{if(he!==te.current)return;let Ce=null,Te=null;for(let Ue=0;Ue<2&&!Ce;Ue+=1){const ft=I.current||bo;try{const ne=await Ye("/api/settings",{method:"PATCH",body:JSON.stringify({revision:ft.revision,[me.section]:{[me.key]:me.value}})},n);Ce=Rh(ne)}catch(ne){if(Te=ne,Ue!==0||!String(ne instanceof Error?ne.message:ne).startsWith("409 "))break;try{const xe=await Ye("/api/settings",void 0,n);if(he!==te.current)return;I.current=Rh(xe)}catch(xe){Te=xe;break}}}if(he!==te.current)return;B.current=B.current.filter(Ue=>Ue.id!==me.id),Ce&&(I.current=Ce);const He=I.current||bo,ee=B.current.reduce(Zy,He);O.current=ee,b(ee),Ce?(k(""),j(B.current.length>0?"saving":"saved")):(j(B.current.length>0?"saving":"failed"),k(Te instanceof Error?Te.message:String(Te||"Settings could not be saved.")))}),await _.current},Y=(oe,X)=>be=>{W(oe,X,be)},F=async()=>{if(a!=="hub"||!s||!l){A("failed"),L("Sign in to this Hub before changing its runtime role.");return}A("changing"),L("");try{const oe=await Ye("/api/runtime/status",void 0,n);await Ye("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),A("accepted"),await Ax({baseUrl:n,targetRole:"client",previousRuntimePid:Number(oe.runtimePid||0),allowedStates:["running","waiting-auth"]}),qC(5179)}catch(oe){A("failed"),L(oe instanceof Error?oe.message:String(oe))}},ve=Nf(x,"security"),fe=Nf(x,"control"),Q=Nf(x,"filesAudio"),z=`settings-panel-${g}`,re=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,i.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Runtime role"}),i.jsx("h3",{children:"Use this computer as a Client"})]}),i.jsx(gx,{size:20})]}),i.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),N==="accepted"?i.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):T?i.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:T}):null,i.jsx("button",{className:"settings-reset",onClick:()=>{F()},disabled:N==="changing"||a!=="hub",type:"button",children:N==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),V=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Remote access"}),i.jsx("h3",{children:"Who may connect?"})]}),i.jsx(Di,{size:20})]}),i.jsx(vc,{icon:Yn,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:i.jsx(Jy,{value:String(ve.accessMode),onChange:Y("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Session permissions"}),i.jsx("h3",{children:"What may remote users do?"})]}),i.jsx(Ea,{size:20})]}),i.jsx(vc,{icon:Ea,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:i.jsx(uf,{checked:!!fe.allowKeyboardMouse,onChange:Y("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),i.jsx(vc,{icon:Zh,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:i.jsx(uf,{checked:!!Q.allowFileTransfer,onChange:Y("filesAudio","allowFileTransfer"),label:"File transfer"})}),i.jsx(vc,{icon:jo,title:"Remote audio",description:"Allow sound capture from connected computers.",children:i.jsx(uf,{checked:!!Q.allowRemoteAudio,onChange:Y("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),H=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Capture"}),i.jsx("h3",{children:"Recording defaults"})]}),i.jsx(Zh,{size:20})]}),i.jsx(vc,{icon:jo,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:i.jsx(uf,{checked:!!Q.rollingBufferEnabled,onChange:Y("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),i.jsx(vc,{icon:jo,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:i.jsx(Jy,{value:Number(Q.timelapseIntervalSeconds),onChange:oe=>Y("filesAudio","timelapseIntervalSeconds")(Number(oe)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),le=g==="connection"?re:g==="remote-access"?V:g==="capture-audio"?H:m;return i.jsxs("section",{className:"settings-page",children:[i.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:Ck.map(({id:oe,label:X,icon:be})=>i.jsxs("button",{className:g===oe?"active":"",id:`settings-tab-${oe}`,role:"tab","aria-selected":g===oe,"aria-controls":`settings-panel-${oe}`,tabIndex:g===oe?0:-1,onClick:()=>y(oe),type:"button",children:[i.jsx(be,{size:16}),X]},oe))}),w==="saving"&&i.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),M&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:M}),i.jsx("section",{className:"settings-page-panel",id:z,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:le})]})}function jk({children:n}){return i.jsx("div",{className:"settings-tab-content",children:n})}const eb={enabled:!1};function tb(n){return{enabled:n?.enabled===!0}}async function Mk(n,a,s){let l=null;for(let c=0;c<2;c+=1){const u=await Ye("/api/settings",{signal:s},a);if(u.settings.agent?.enabled===n)return;try{await Ye("/api/settings",{method:"PATCH",signal:s,body:JSON.stringify({revision:u.revision,agent:{enabled:n}})},a);return}catch(m){if(l=m,c!==0||!String(m instanceof Error?m.message:m).startsWith("409 "))throw m}}throw l}function Ak({hubUrl:n}){const[a,s]=d.useState(eb),[l,c]=d.useState(null),[u,m]=d.useState(""),[h,g]=d.useState(""),[y,x]=d.useState(""),b=d.useRef(0),w=d.useRef(null);d.useEffect(()=>{let I=!0;w.current?.abort();const B=new AbortController;w.current=B;const _=++b.current;return c(null),s(eb),m(""),x(""),g(""),Ye("/api/settings/agent",{signal:B.signal},n).then(G=>{!I||B.signal.aborted||_!==b.current||(c(G.settings),s(tb(G.settings)))}).catch(G=>{I&&!B.signal.aborted&&_===b.current&&x(G instanceof Error?G.message:String(G))}),()=>{I=!1,B.abort(),w.current===B&&(w.current=null)}},[n]);const j=(I,B)=>s(_=>({..._,[I]:B})),M=I=>{c(I),s(tb(I))},k=()=>({generation:b.current,controller:w.current}),N=I=>I.generation===b.current&&I.controller!==null&&I.controller===w.current&&!I.controller.signal.aborted,A=async()=>{if(!l){x("Agent settings are not available yet.");return}const I=k();if(N(I)){m("save"),x(""),g("");try{if(await Mk(a.enabled,n,I.controller.signal),!N(I))return;const B=await Ye("/api/settings/agent",{signal:I.controller.signal},n);if(!N(I))return;M(B.settings),g("Codex Agent settings saved.")}catch(B){N(I)&&x(B instanceof Error?B.message:String(B))}finally{N(I)&&m("")}}},T=async()=>{const I=k();if(N(I)){m("test"),x(""),g("");try{const B=await Ye("/api/settings/agent/test",{method:"POST",signal:I.controller.signal,body:JSON.stringify({})},n);if(!N(I))return;const _=await Ye("/api/settings/agent",{signal:I.controller.signal},n);if(!N(I))return;M(_.settings);const G=Number.isFinite(B.connection?.latencyMs)?Math.max(0,Math.round(B.connection.latencyMs)):null;g(`Codex Agent connection verified${G!==null?` in ${G} ms.`:"."}`)}catch(B){N(I)&&x(B instanceof Error?B.message:String(B))}finally{N(I)&&m("")}}},L=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",O=l!==null;return i.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[i.jsx("section",{className:"settings-section-card agent-enable-card",children:i.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[i.jsx("input",{type:"checkbox",checked:a.enabled,onChange:I=>j("enabled",I.target.checked),disabled:!O||u!==""}),i.jsx("span",{children:"Enable Codex Agent"})]})}),y&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),h&&i.jsx("div",{className:"agent-settings-alert success",role:"status",children:h}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Runtime"}),i.jsx("h3",{children:"Codex SDK / CLI"})]}),i.jsx(Yn,{size:20})]}),i.jsxs("div",{className:"agent-connection-row",children:[i.jsx("span",{className:`agent-connection-dot ${L?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),i.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),i.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:u!=="",type:"button",children:[i.jsx(M0,{size:15})," ",u==="test"?"Testing":"Test connection"]})]}),i.jsxs("p",{className:"settings-help",children:[i.jsx(A0,{size:12})," The Hub uses the installed Codex SDK / CLI to plan and run approved computer commands. LiveDesk does not install, configure, or manage models, Ollama, LM Studio, or other inference runtimes."]})]}),i.jsx("div",{className:"settings-action-row agent-settings-actions",children:i.jsxs("button",{className:"text-button primary",onClick:()=>{A()},disabled:!O||u!=="",type:"button",children:[i.jsx(N0,{size:15})," ",u==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function Ps(n){const[a,s]=d.useState(n),l=d.useRef(n);return d.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,s(n)}},[n]),[a,s]}function _p(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function Rc(n,a="data-id"){let s=n;for(!s.tagName&&n.target&&(s=n.target);s;){if(s.getAttribute&&s.getAttribute(a))return s;s=s.parentNode}return null}function Nk(n,a="data-id"){const s=Rc(n,a);return s?s.getAttribute(a):null}function Xu(n,a="data-id"){const s=Rc(n,a);return s?Kf(s,a):null}function Kf(n,a="data-id"){const s=n.getAttribute(a);return s?Tk(s):null}function na(n){return typeof n=="string"?":"+n:n}function Tk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Rk(){return{detect:()=>!0,addEvent:function(n,a,s){return n.addEventListener(a,s),()=>n.removeEventListener(a,s)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var ir=Rk();function Ip(n){Object.assign(ir,n)}function nb(n,a,s){function l(c){const u=Rc(c);if(!u)return;const m=Kf(u);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[s]&&a[s](m,c)}ir.addEvent(n,s,l)}function Ec(n,a){nb(n,a,"click"),a.dblclick&&nb(n,a.dblclick,"dblclick")}function Ek(n,a){for(let s=n.length-1;s>=0;s--)if(n[s]===a){n.splice(s,1);break}}function Dk(n,a,s){for(let l=0;l<Li.length;l++){if(l===s)continue;const c=Li[l],u=c.props.parent?.();if(u&&n.contains(u)&&c.node.contains(a))return!0}return!1}var nw=new Date,Pf=!1,df=[],Li=[],ab=n=>{const a=n.target;if(Pf||!a.isConnected){Pf=!1;return}for(let s=Li.length-1;s>=0;s--){const{node:l,date:c,props:u}=Li[s];if(!(c>nw)&&!l.contains(a)&&l!==a&&(Dk(l,a,s)||(u.callback&&u.callback(n),u.modal||n.defaultPrevented)))break}},Lk=n=>{nw=new Date,Pf=!0;for(let a=Li.length-1;a>=0;a--){const{node:s}=Li[a];if(!s.contains(n.target)&&s!==n.target){Pf=!1;break}}};function Fs(n,a){df.length||(df=[ir.addGlobalEvent("click",ab,n),ir.addGlobalEvent("contextmenu",ab,n),ir.addGlobalEvent("mousedown",Lk,n)]),typeof a!="object"&&(a={callback:a});const s={node:n,date:new Date,props:a};return Li.push(s),{destroy(){Ek(Li,s),Li.length||(df.forEach(l=>l()),df=[])}}}var ff=n=>n.indexOf("bottom")!==-1,mf=n=>n.indexOf("left")!==-1,hf=n=>n.indexOf("right")!==-1,Eh=n=>n.indexOf("top")!==-1,rb=n=>n.indexOf("fit")!==-1,_u=n=>n.indexOf("overlap")!==-1,_k=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),Ik=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function zk(n,a){let s=0;const l=ir.getTopNode(n);for(;n&&n!==l;){const c=getComputedStyle(n).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(s=parseInt(getComputedStyle(n).zIndex)||0),n=n.parentNode,n===a)break}return s}var On,ja,Iu,ga;function aw(n,a,s="bottom",l=0,c=0){if(!n)return null;On=l,ja=c,Iu="auto";let u=0,m=0,h=s;const g=rw(n),y=_u(s)?ir.getTopNode(n):g;if(!g)return null;const x=g.getBoundingClientRect(),b=n.getBoundingClientRect(),w=y.getBoundingClientRect(),j=window.getComputedStyle(y),M={left:0,top:0,bottom:0,right:0};for(const O in M){const I=`border-${O}-width`;M[O]=parseFloat(j.getPropertyValue(I))}if(a){const O=zk(a,g);u=Math.max(O+1,20)}if(a){if(ga=a.getBoundingClientRect(),rb(s)&&(Iu=ga.width+"px"),s!=="point")if(_k(s))rb(s)?On=0:(On=w.width/2,m=1),ja=(w.height-b.height)/2;else{const O=_u(s)?0:1;On=hf(s)?ga.right+O:ga.left-O,ja=ff(s)?ga.bottom+1:ga.top;const I=Ik(s);I&&(hf(s)||mf(s)?I==="center"?ja-=(b.height-ga.height)/2:I==="end"&&(ja-=b.height-ga.height):(ff(s)||Eh(s))&&(I==="center"?On-=(b.width-ga.width)/2:I==="end"&&(On-=b.width-ga.width),_u(s)||(On+=1)))}}else ga={left:l,right:l,top:c,bottom:c};const k=(mf(s)||hf(s))&&(ff(s)||Eh(s));mf(s)&&(m=2);const N=On-b.width-w.left;a&&mf(s)&&!k&&N<0&&(On=ga.right,m=0,h=h.replace("left","right"));const A=On+b.width*(1-m/2)-w.right;if(A>0)if(!hf(s))On=w.right-M.right-b.width;else{const O=ga.left-w.x-b.width;a&&!k&&O>=0?(On=ga.left-b.width,h=h.replace("right","left")):On-=A+M.right}m&&(On=Math.round(On-b.width*m/2));const T=N<0||A>0||!k;Eh(s)&&(ja=ga.top-b.height,a&&ja<w.y&&T&&(ja=ga.bottom,h=h.replace("top","bottom")));const L=ja+b.height-w.bottom;return L>0&&(a&&ff(s)&&T?(ja-=b.height+ga.height+1,h=h.replace("bottom","top")):ja-=L+M.bottom),On-=x.left+M.left,ja-=x.top+M.top,On=(_u(s)?On:Math.max(On,0))+y.scrollLeft,ja=(_u(s)?ja:Math.max(ja,0))+y.scrollTop,Iu=Iu||"auto",{at:h,x:On,y:ja,z:u,width:Iu}}function rw(n){const a=ir.getTopNode(n);for(n&&(n=n.parentElement);n;){const s=getComputedStyle(n).position;if(n===a||s==="relative"||s==="absolute"||s==="fixed")return n;n=n.parentNode}return null}function Ok(n){const a=[];let s=n;const l=ir.getTopNode(n);for(;s&&s!==l&&!s.getAttribute("data-wx-portal-root");)getComputedStyle(s).position==="absolute"&&a.push(s),s=s.parentNode;return a}var sb=new Date().valueOf();function zp(){return sb+=1,sb}function Aa(n){return n<10?"0"+n:n.toString()}function Hk(n){const a=Aa(n);return a.length==2?"0"+a:a}function sw(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function Dh(n){const a=(n.getDay()+6)%7,s=new Date(n.valueOf());s.setDate(n.getDate()+(3-a)),s.setHours(0,0,0,0);const l=new Date(s.getFullYear(),0,1),c=Math.round((s.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var ib=["",""];function Pk(n,a,s){switch(n){case"%d":return Aa(a.getDate());case"%m":return Aa(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return Aa(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return s.dayShort[a.getDay()];case"%l":return s.dayFull[a.getDay()];case"%M":return s.monthShort[a.getMonth()];case"%F":return s.monthFull[a.getMonth()];case"%h":return Aa((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return Aa(a.getHours());case"%i":return Aa(a.getMinutes());case"%a":return((a.getHours()>11?s.pm:s.am)||ib)[0];case"%A":return((a.getHours()>11?s.pm:s.am)||ib)[1];case"%s":return Aa(a.getSeconds());case"%S":return Hk(a.getMilliseconds());case"%W":return Aa(Dh(a));case"%w":{const l=s.weekStart??1;if(l===1)return Aa(Dh(a));const c=(a.getDay()-l+7)%7,u=(1-l+7)%7,m=new Date(a.valueOf());return m.setDate(a.getDate()+(u-c)),Aa(Dh(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+Aa(a.getMonth()+1),l+="-"+Aa(a.getDate()),l+="T",l+=Aa(a.getHours()),l+=":"+Aa(a.getMinutes()),l+=":"+Aa(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var Fk=/%[a-zA-Z]/g;function kc(n,a){return typeof n=="function"?n:function(s){return s?(s.getMonth||(s=new Date(s)),n.replace(Fk,l=>Pk(l,s,a))):""}}function lb(n){return n&&typeof n=="object"&&!Array.isArray(n)}function gp(n,a){for(const s in a){const l=a[s];lb(n[s])&&lb(l)?n[s]=gp({...n[s]},a[s]):n[s]=a[s]}return n}function Ju(n){return{getGroup(a){const s=n[a];return l=>s&&s[l]||l},getRaw(){return n},extend(a,s){if(!a)return this;let l;return s?l=gp({...a},n):l=gp({...n},a),Ju(l)}}}var $k=kx();const Bk="en-US",Uk={monthFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hours:"Hours",minutes:"Minutes",done:"Done",clear:"Clear",today:"Today",am:["am","AM"],pm:["pm","PM"],weekStart:0,clockFormat:24},qk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Gk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},iw={core:qk,calendar:Uk,formats:Gk,lang:Bk},Op=d.createContext(""),lw=d.createContext({}),ds=d.createContext(null),ow=d.createContext(null),ra=Object.freeze(Object.defineProperty({__proto__:null,fieldId:ow,helpers:lw,i18n:ds,theme:Op},Symbol.toStringTag,{value:"Module"}));function cw(n){const a=d.useContext(ow),[s]=d.useState(()=>n||a||zp());return s}function Gu({type:n="",css:a="",icon:s="",disabled:l=!1,title:c="",tooltip:u,text:m="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=n?n.split(" ").filter(w=>w!=="").map(w=>"wx-"+w).join(" "):"";return a+(a?" ":"")+b},[n,a]),x=b=>{g&&g(b)};return i.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${y} ${s&&!h?"wx-icon":""}`,disabled:l,onClick:x,"data-tooltip-text":u,children:[s&&i.jsx("i",{className:"wx-2ZWgb4 "+s}),h||m||" "]})}function Vk({id:n,label:a="",inputValue:s="",value:l=!1,onChange:c,disabled:u=!1,css:m=""}){const h=cw(n),[g,y]=Ps(l),x=({target:b})=>{const w=b.checked;y(w),c&&c({value:w,inputValue:s})};return i.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[i.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:s,onChange:x}),i.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[i.jsx("span",{className:"wx-2IvefP wx-before"}),a&&i.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function Hp({theme:n="",target:a,children:s}){const l=d.useRef(null),c=d.useRef(null),[u,m]=d.useState(null);l.current||(l.current=document.createElement("div"));const h=d.useContext(Op);return d.useEffect(()=>{m(a||Wk(c.current)||ir.getTopNode(c.current))},[c.current]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:c,style:{display:"none"}}),c.current&&u?$k.createPortal(i.jsx("div",{className:`wx-3ZWsT0 wx-${n||h}-theme`,children:s}),u):null]})}function Wk(n){const a=ir.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function Yk({left:n=0,top:a=0,at:s="bottom",parent:l=null,width:c="auto",css:u="",onCancel:m,children:h,trackScroll:g=!1}){const[y,x]=d.useState(0),[b,w]=d.useState(0),[j,M]=d.useState("auto"),[k,N]=d.useState(!1),A=d.useRef(null),T=d.useRef(null),L=d.useRef(m);d.useEffect(()=>{L.current=m},[m]);function O(B){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(_,G)=>(G=G*l.offsetWidth/100+"px",c.replace(_,G))):c&&c!=="auto"?c:B}const I=d.useCallback(()=>{if(!A.current)return;const B=aw(A.current,l,s,n,a);B&&(x(B.x),w(B.y),M(O(B.width)))},[A,l,s,n,a,c]);return d.useLayoutEffect(()=>{const B=G=>{L.current&&G.target!==T.current&&A.current&&!A.current.contains(G.target)&&L.current(G)};let _;return requestAnimationFrame(()=>{I(),N(!0),g&&A.current&&(T.current=rw(A.current),T.current&&T.current.addEventListener("scroll",B,!0)),l&&(_=new ResizeObserver(I),_.observe(l))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",B,!0),_?.disconnect()}},[]),d.useLayoutEffect(()=>{I()},[l,s,n,a]),d.useEffect(()=>{const B=_=>{L.current&&L.current(_)};if(A.current)return Fs(A.current,{callback:B,parent:()=>l}).destroy},[l]),i.jsx("div",{ref:A,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:k?"visible":"hidden",top:b+"px",left:y+"px",width:j},children:h})}function Kk({position:n="bottom",align:a="start",autoFit:s=!0,onCancel:l=null,width:c="100%",css:u="",children:m}){const h=d.useRef(null),[g,y]=d.useState(n),[x,b]=d.useState(a),w=d.useRef(l);return d.useEffect(()=>{w.current=l},[l]),d.useEffect(()=>{if(s){const j=h.current;if(j){const M=j.getBoundingClientRect(),k=document.body.getBoundingClientRect();M.right>=k.right&&b("end"),M.bottom>=k.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const j=M=>{w.current&&w.current(M)};return Fs(h.current,j).destroy}},[]),i.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${x}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function Pp({position:n="bottom",align:a="start",autoFit:s=!0,inline:l=!1,onCancel:c,width:u="100%",children:m,...h}){const[g,y]=d.useState(void 0),x=d.useRef(null),b=d.useMemo(()=>`${n}-${a}`,[n,a]);return d.useLayoutEffect(()=>{x.current&&y(x.current.parentNode)},[]),i.jsxs(i.Fragment,{children:[g&&(l?i.jsx(Kk,{onCancel:c,position:n,align:a,autoFit:s,width:u,...h,children:m}):i.jsx(Hp,{children:i.jsx(Yk,{parent:g,at:b,onCancel:c,width:u,...h,children:m})})),i.jsx("span",{ref:x,className:"wx-portal-node wx-32GZ52"})]})}function Qf(){return Ju(iw)}function Qk(){let n=null,a=!1,s=!1,l,c,u,m;const h=(b,w,j,M,k)=>{l=b,c=w,u=j,m=M,s=k},g=b=>{n=b,a=n!==null,u(n)},y=(b,w)=>{if(!s&&b!==null&&l){const j=l.querySelectorAll(".wx-list > .wx-item")[b];j&&(j.scrollIntoView({block:"nearest"}),w&&w.preventDefault())}},x=(b,w)=>{const j=b===null?null:Math.max(0,Math.min(n+b,c.length-1));j!==n&&(g(j),l?y(j,w):requestAnimationFrame(()=>y(j,w)))};return{move:b=>{const w=Xu(b),j=c.findIndex(M=>M.id===w);j!==n&&g(j)},keydown:(b,w)=>{switch(b.code){case"Enter":a?m():g(0);break;case"Space":a||g(0);break;case"Escape":u(n=null);break;case"Tab":u(n=null);break;case"ArrowDown":x(a?1:w||0,b);break;case"ArrowUp":x(a?-1:w||0,b);break}},init:h,navigate:x}}const ob=10,Xk=d.memo(function({data:n,checkboxes:a,itemTemplate:s,value:l}){return i.jsxs(i.Fragment,{children:[a&&i.jsx(Vk,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),s?_p(s,{option:n}):n.label]})});function cb({visibleItems:n,visibleRange:a,navIndex:s,checkboxes:l,itemTemplate:c,value:u,measureRefCallback:m}){return n.map((h,g)=>{const y=a.start+g;return i.jsx("div",{ref:g===0?m:void 0,className:`wx-233fr7 wx-item ${y===s?"wx-focus":""}`,"data-id":h.id,children:i.jsx(Xk,{data:h,checkboxes:l,itemTemplate:c,value:u})},h.id)})}function Xf({items:n=[],children:a,onSelect:s,onReady:l,virtualized:c=!1,checkboxes:u,multiselect:m,value:h,...g}){const y=d.useRef(),x=d.useRef(!1),b=d.useRef(Qk()),[w,j]=d.useState(null),M=d.useRef(w),[k,N]=d.useState(0),[A,T]=d.useState(24),L=d.useRef(!1),O=(d.useContext(ds)||Qf()).getGroup("core"),I=d.useRef(n);d.useEffect(()=>{I.current=n},[n]);const B=d.useRef(h);d.useEffect(()=>{B.current=h},[h]);const _=d.useRef(0);d.useEffect(()=>{_.current=A},[A]);const G=d.useCallback(X=>{X&&X.stopPropagation();const be=I.current,me=B.current,he=M.current;let J;const Ce=be[he]?.id;m?me&&me.includes(Ce)?J=me.filter(Te=>Te!==Ce):J=[...me||[],Ce]:J=Ce,s&&s({id:J})},[m,s]),te=d.useRef(G);d.useEffect(()=>{te.current=G},[G]);const W=d.useCallback(X=>{if(y.current){let be=X*_.current-y.current.clientHeight+_.current;N(be),y.current.scrollTop=be}},[_.current]),Y=d.useCallback(X=>{y.current=X,c&&(X&&!x.current&&M.current!==null&&requestAnimationFrame(()=>{y.current&&(W(M.current),x.current=!0)}),X||(x.current=!1))},[W]),F=d.useCallback(X=>{if(!X||L.current)return;const be=X.getBoundingClientRect().height;be&&(T(be),_.current=be,L.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,n,X=>{j(X),M.current=X},X=>te.current(X),c)},[n,y.current,c]),d.useEffect(()=>{const X=(me,he)=>{b.current.navigate(me,he),W(M.current)},be=(me,he)=>{const J=M.current,Ce=I.current;if(J!==0&&J!==Ce.length-1&&(me.key==="ArrowDown"||me.key==="ArrowUp")&&me.preventDefault(),b.current.keydown(me,he),y.current){const Te=y.current.scrollTop<=M.current*_.current,He=y.current.scrollTop+y.current.clientHeight>=M.current*_.current+_.current;Te?He||W(M.current):(y.current.scrollTop=M.current*_.current,N(y.current.scrollTop))}};l&&l({navigate:c?X:b.current.navigate,keydown:c?be:b.current.keydown,move:b.current.move})},[]);const ve=d.useRef(0),fe=d.useRef(n);fe.current!==n&&(fe.current=n,ve.current+=1);const Q=d.useCallback(()=>{b.current.navigate(null)},[b]),z=d.useCallback(X=>{c&&N(X.target.scrollTop)},[c]),re=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/A),[A,k]),V=d.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const X=Math.floor(k/A),be=X+re;return{start:Math.max(0,X-ob),end:Math.min(n.length,be+ob)}},[c,n,k,A,re]),H=d.useMemo(()=>{if(!c)return n;const{start:X,end:be}=V;return n.slice(X,be).map(me=>({...me}))},[c,n,V]),le=V.start*A,oe=n.length*A;return d.useEffect(()=>{c&&N(0)},[n,c]),d.useEffect(()=>{w===null&&(x.current=!1)},[w]),w===null?null:i.jsx(Pp,{onCancel:Q,...g,children:i.jsx("div",{className:"wx-233fr7 wx-list",ref:Y,onClick:G,onMouseMove:b.current.move,onScroll:z,children:n.length?c?i.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${oe}px`},children:i.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${le}px)`},children:i.jsx(cb,{visibleRange:V,visibleItems:H,navIndex:w,measureRefCallback:F,checkboxes:u,itemTemplate:a,value:h})})}):i.jsx(cb,{visibleRange:V,visibleItems:H,navIndex:w,measureRefCallback:F,checkboxes:u,itemTemplate:a,value:h}):i.jsx("div",{className:"wx-233fr7 wx-no-data",children:O("No data")})})},ve.current)}function Fp({value:n="",id:a,readonly:s=!1,focus:l=!1,select:c=!1,type:u="text",placeholder:m="",disabled:h=!1,error:g=!1,title:y="",tooltip:x,css:b="",icon:w="",clear:j=!1,onChange:M}){const k=cw(a),[N,A]=Ps(n),T=d.useRef(null),L=d.useMemo(()=>w&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[w,b]),O=d.useMemo(()=>w&&b.indexOf("wx-icon-left")!==-1,[w,b]);d.useEffect(()=>{const te=setTimeout(()=>{l&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(te)},[l,c]);const I=d.useCallback(te=>{const W=te.target.value;A(W),M&&M({value:W,input:!0})},[M]),B=d.useCallback(te=>M&&M({value:te.target.value}),[M]);function _(te){te.stopPropagation(),A(""),M&&M({value:""})}let G=u;return u!=="password"&&u!=="number"&&(G="text"),d.useEffect(()=>{const te=B,W=T.current;return W.addEventListener("change",te),()=>{W&&W.removeEventListener("change",te)}},[B]),i.jsxs("div",{className:`wx-hQ64J4 wx-text ${L} ${g?"wx-error":""} ${h?"wx-disabled":""} ${j?"wx-clear":""}`,"data-tooltip-text":x,children:[i.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:k,readOnly:s,disabled:h,placeholder:m,type:G,title:y,value:N,onInput:I}),j&&!h&&N?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:_}),O&&i.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`})]}):w?i.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`}):null]})}function Zk({date:n,type:a,part:s,onShift:l}){const{calendar:c,formats:u}=d.useContext(ds).getRaw(),m=n.getFullYear(),h=d.useMemo(()=>{switch(a){case"month":return kc(u.monthYearFormat,c)(n);case"year":return kc(u.yearFormat,c)(n);case"duodecade":{const{start:y,end:x}=sw(m),b=kc(u.yearFormat,c);return`${b(new Date(y,0,1))} - ${b(new Date(x,11,31))}`}default:return""}},[n,a,m,c,u]);function g(){l&&l({diff:0,type:a})}return i.jsxs("div",{className:"wx-8HQVQV wx-header",children:[s!=="right"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"}),i.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),s!=="left"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function $p({onClick:n,children:a}){return i.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function Jk({value:n,current:a,part:s="",markers:l=null,css:c="",onCancel:u,onChange:m}){const h=(d.useContext(ds)||Qf()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),x=(I,B,_)=>new Date(I.getFullYear(),I.getMonth()+(B||0),I.getDate()+(_||0));let b=s!=="normal";function w(I){const B=I.getDay();return B===0||B===6}function j(){const I=x(a,0,1-a.getDate());return I.setDate(I.getDate()-(I.getDay()-(g-7))%7),I}function M(){const I=x(a,1,-a.getDate());return I.setDate(I.getDate()+(6-I.getDay()+g)%7),I}const k=d.useRef(0);function N(I,B){B.timeStamp!==k.current&&(k.current=B.timeStamp,B.stopPropagation(),m&&m(new Date(I)),u&&u())}const A=d.useMemo(()=>s=="normal"?[n?x(n).valueOf():0]:n?[n.start?x(n.start).valueOf():0,n.end?x(n.end).valueOf():0]:[0,0],[s,n]),T=d.useMemo(()=>{const I=j(),B=M(),_=a.getMonth();let G=[];for(let te=I;te<=B;te.setDate(te.getDate()+1)){const W={day:te.getDate(),in:te.getMonth()===_,date:te.valueOf()};let Y="";if(Y+=W.in?"":" wx-inactive",Y+=A.indexOf(W.date)>-1?" wx-selected":"",b){const F=W.date==A[0],ve=W.date==A[1];F&&!ve?Y+=" wx-left":ve&&!F&&(Y+=" wx-right"),W.date>A[0]&&W.date<A[1]&&(Y+=" wx-inrange")}if(Y+=w(te)?" wx-weekend":"",l){const F=l(te);F&&(Y+=" "+F)}G.push({...W,css:Y})}return G},[a,A,b,l]),L=d.useRef(null);let O=d.useRef({});return O.current.click=N,d.useEffect(()=>{Ec(L.current,O.current)},[]),i.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[i.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(I=>i.jsx("div",{className:"wx-398RBS wx-weekday",children:I},I))}),i.jsx("div",{className:"wx-398RBS wx-days",ref:L,children:T.map(I=>i.jsx("div",{className:`wx-398RBS wx-day ${I.css} ${I.in?"":"wx-out"}`,"data-id":I.date,children:I.day},I.date))})]})}function ej({value:n,current:a,part:s,onCancel:l,onChange:c,onShift:u}){const m=d.useRef(new Date),[h,g]=Ps(n||m.current),[y,x]=Ps(a||m.current),b=d.useContext(ds).getRaw().calendar,w=b.monthShort||[],j=d.useMemo(()=>y.getMonth(),[y]),M=d.useCallback((A,T)=>{if(A!=null){T.stopPropagation();const L=new Date(y);L.setMonth(A),x(L),u&&u({current:L})}s==="normal"&&g(new Date(y)),l&&l()},[y,s,u,l]),k=d.useCallback(()=>{const A=new Date(uw(h,s)||y);A.setMonth(y.getMonth()),A.setFullYear(y.getFullYear()),c&&c(A)},[h,y,s,c]),N=d.useCallback(A=>{const T=A.target.closest("[data-id]");if(T){const L=parseInt(T.getAttribute("data-id"),10);M(L,A)}},[M]);return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-34U8T8 wx-months",onClick:N,children:w.map((A,T)=>i.jsx("div",{className:"wx-34U8T8 wx-month"+(j===T?" wx-current":""),"data-id":T,children:A},T))}),i.jsx("div",{className:"wx-34U8T8 wx-buttons",children:i.jsx($p,{onClick:k,children:b.done})})]})}const Lh="wx-1XEF33",tj=({value:n,current:a,onCancel:s,onChange:l,onShift:c,part:u})=>{const m=d.useContext(ds).getRaw().calendar,[h,g]=Ps(a),[y,x]=Ps(n),b=d.useMemo(()=>h.getFullYear(),[h]),w=d.useMemo(()=>{const{start:A,end:T}=sw(b),L=[];for(let O=A;O<=T;++O)L.push(O);return L},[b]),j={click:M};function M(A,T){if(A){T.stopPropagation();const L=new Date(h);L.setFullYear(A),g(L),c&&c({current:L})}u==="normal"&&x(new Date(h)),s&&s()}function k(){const A=new Date(uw(y,u)||h);A.setFullYear(h.getFullYear()),l&&l(A)}const N=d.useRef(null);return d.useEffect(()=>{N.current&&Ec(N.current,j)},[]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:Lh+" wx-years",ref:N,children:w.map((A,T)=>i.jsx("div",{className:Lh+` wx-year ${b==A?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":A,children:A},T))}),i.jsx("div",{className:Lh+" wx-buttons",children:i.jsx($p,{onClick:k,children:m.done})})]})},ub={month:{component:Jk,next:aj,prev:nj},year:{component:ej,next:sj,prev:rj},duodecade:{component:tj,next:lj,prev:ij}};function nj(n){return n=new Date(n),n.setMonth(n.getMonth()-1),n}function aj(n){return n=new Date(n),n.setMonth(n.getMonth()+1),n}function rj(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function sj(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function ij(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function lj(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function uw(n,a){let s;if(a==="normal")s=n;else{const{start:l,end:c}=n;a==="left"?s=l:a=="right"?s=c:s=l&&c}return s}const oj=["clear","today"];function cj(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function uj({value:n,current:a,onCurrentChange:s,part:l="normal",markers:c=null,buttons:u,css:m="",onShift:h,onChange:g}){const y=d.useContext(ds).getGroup("calendar"),[x,b]=d.useState("month"),w=Array.isArray(u)?u:u?oj:[],j=(T,L)=>{T.preventDefault(),g&&g({value:L})},M=()=>{x==="duodecade"?b("year"):x==="year"&&b("month")},k=T=>{const{diff:L,current:O}=T;if(L===0){x==="month"?b("year"):x==="year"&&b("duodecade");return}if(L){const I=ub[x];s(L>0?I.next(a):I.prev(a))}else O&&s(O);h&&h()},N=T=>{b("month"),g&&g({select:!0,value:T})},A=d.useMemo(()=>ub[x].component,[x]);return i.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:i.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[i.jsx(Zk,{date:a,part:l,type:x,onShift:k}),i.jsxs("div",{children:[i.jsx(A,{value:n,current:a,onCurrentChange:s,part:l,markers:c,onCancel:M,onChange:N,onShift:k}),x==="month"&&w.length>0&&i.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:w.map(T=>i.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:i.jsx($p,{onClick:L=>j(L,cj(T)),children:y(T)})},T))})]})]})})}function Bp(n){let{words:a=null,optional:s=!1,children:l}=n,c=d.useContext(ds);const u=d.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=Ju(iw)),a!==null&&(m=m.extend(a,s)),m},[a,s,c]);return i.jsx(ds.Provider,{value:u,children:l})}function db(n,a,s,l){if(!n||l){const c=a?new Date(a):new Date;c.setDate(1),s(c)}else if(n.getDate()!==1){const c=new Date(n);c.setDate(1),s(c)}}const dj=["clear","today"];function dw({value:n,current:a,markers:s=null,buttons:l=dj,css:c="",onChange:u}){const[m,h]=Ps(n),[g,y]=Ps(a);d.useEffect(()=>{db(g,m,y,!1)},[m,g]);const x=d.useCallback(w=>{const j=w.value;j?(h(new Date(j)),db(g,new Date(j),y,!0)):h(null),u&&u({value:j?new Date(j):null})},[u,g]),b=d.useCallback(w=>{y(w)},[y]);return g?i.jsx(Bp,{children:i.jsx(uj,{value:m,current:g,markers:s,buttons:l,css:c,onChange:x,onCurrentChange:b})}):null}function fj(n){return n||(n={}),n.width||(n.width="unset"),n}const mj=["clear","today"];function hj({value:n,id:a,disabled:s=!1,error:l=!1,placeholder:c="",format:u="",buttons:m=mj,css:h="",title:g="",tooltip:y,editable:x=!1,clear:b=!1,onChange:w,dropdown:j={}}){const{calendar:M,formats:k}=(d.useContext(ds)||Qf()).getRaw(),N=u||k?.dateFormat;let A=typeof N=="function"?N:kc(N,M);const[T,L]=d.useState(n),[O,I]=d.useState(!1);d.useEffect(()=>{L(n)},[n]);function B(){I(!1)}function _(W){const Y=W===T||W&&T&&W.valueOf()===T.valueOf()||!W&&!T;L(W),Y||w&&w({value:W}),setTimeout(B,1)}const G=d.useMemo(()=>T?A(T):"",[T,A]);function te({value:W,input:Y}){if(!x&&!b||Y)return;let F=typeof x=="function"?x(W):W?new Date(W):null;F=isNaN(F)?T||null:F||null,_(F)}return d.useEffect(()=>{const W=B;return window.addEventListener("scroll",W),()=>window.removeEventListener("scroll",W)},[]),i.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>I(!0),children:[i.jsx(Fp,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:G,id:a,readonly:!x,disabled:s,error:l,placeholder:c,onInput:B,onChange:te,icon:"wxi-calendar",clear:b}),O&&!s&&i.jsx(Pp,{onCancel:B,...fj(j),children:i.jsx(dw,{buttons:m,value:T,onChange:W=>_(W.value)})})]})}function pj({value:n="",options:a=[],textOptions:s=null,placeholder:l="",disabled:c=!1,error:u=!1,title:m="",tooltip:h,textField:g="label",clear:y=!1,css:x="",children:b,onChange:w,dropdown:j={}}){const M=d.useRef(null),k=d.useRef(null);let[N,A]=Ps(n);function T(_){M.current=_.navigate,k.current=_.keydown}const L=d.useMemo(()=>N||N===0?(s||a).find(_=>_.id===N):null,[N,s,a]),O=d.useCallback(({id:_})=>{(_||_===0)&&(A(_),M.current(null),w&&w({value:_}))},[A,w]),I=d.useCallback(_=>{_.stopPropagation(),A(""),w&&w({value:""})},[A,w]),B=d.useCallback(()=>a.findIndex(_=>_.id===N),[a,N]);return i.jsxs("div",{className:`wx-2YgblL wx-richselect ${x} ${u?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>M.current(B()),onKeyDown:_=>k.current(_,B()),tabIndex:0,"data-tooltip-text":h,children:[i.jsx("div",{className:"wx-2YgblL wx-label",children:L?b?b(L):L[g]:l?i.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),y&&!c&&N?i.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:I}):i.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&i.jsx(Xf,{items:a,onReady:T,onSelect:O,...j,children:({option:_})=>b?b(_):_[g]})]})}const gj=({options:n=[],value:a="",css:s="",children:l,onChange:c})=>{const[u,m]=d.useState(a),h=g=>{m(g),c&&c({value:g})};return d.useEffect(()=>{m(a)},[a]),i.jsx("div",{className:`wx-0hMO7P wx-segmented ${s}`,children:n.map(g=>i.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:l?_p(l,{option:g}):i.jsxs(i.Fragment,{children:[g.icon&&i.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&i.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function vj({notice:n={}}){function a(){n.remove&&n.remove()}return i.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${n.type?n.type:""}`,role:"status","aria-live":"polite",children:[i.jsx("div",{className:"wx-11sNg5 wx-text",children:n.text}),i.jsx("div",{className:"wx-11sNg5 wx-button",children:i.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function yj({data:n=[]}){return i.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>i.jsx(vj,{notice:a},a.id))})}function vp({title:n="",buttons:a=["cancel","ok"],header:s,children:l,footer:c,css:u="",onConfirm:m,onCancel:h}){const g=(d.useContext(ds)||Qf()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function x(w){switch(w.code){case"Enter":{const j=w.target.tagName;if(j==="TEXTAREA"||j==="BUTTON")return;m&&m({event:w});break}case"Escape":h&&h({event:w});break}}function b(w,j){const M={event:w,button:j};j==="cancel"?h&&h(M):m&&m(M)}return i.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:x,children:i.jsxs("div",{className:"wx-1FxkZa wx-window",children:[s||(n?i.jsx("div",{className:"wx-1FxkZa wx-header",children:n}):null),i.jsx("div",{children:l}),c||a&&i.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(w=>i.jsx("div",{className:"wx-1FxkZa wx-button",children:i.jsx(Gu,{type:`block ${w==="ok"?"primary":"secondary"}`,onClick:j=>b(j,w),children:g(w)})},w))})]})})}function bj({children:n},a){const[s,l]=d.useState(null),[c,u]=d.useState([]);return d.useImperativeHandle(a,()=>({showModal:m=>{const h={...m};return l(h),new Promise((g,y)=>{h.resolve=x=>{l(null),g(x)},h.reject=x=>{l(null),y(x)}})},showNotice:m=>{m={...m},m.id=m.id||zp(),m.remove=()=>u(h=>h.filter(g=>g.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),u(h=>[...h,m])}}),[]),i.jsxs(i.Fragment,{children:[n,s&&i.jsx(vp,{title:s.title,buttons:s.buttons,onConfirm:s.resolve,onCancel:s.reject,children:s.message}),i.jsx(yj,{data:c})]})}const xj=d.forwardRef(bj);function wj(n){let{children:a}=n,s=d.useRef();const l=d.useMemo(()=>({showNotice:c=>s.current.showNotice(c),showModal:c=>s.current.showModal(c)}),[]);return i.jsx(lw.Provider,{value:l,children:i.jsx(xj,{ref:s,children:a})})}const Sj=({value:n=!1,type:a="",icon:s="",disabled:l=!1,iconActive:c="",onClick:u,title:m="",tooltip:h,css:g="",text:y="",textActive:x="",children:b,active:w,onChange:j})=>{const[M,k]=Ps(n),N=d.useMemo(()=>(M?"pressed":"")+(a?" "+a:""),[M,a]),A=d.useCallback(T=>{let L=!M;u&&u(T),T.defaultPrevented||(k(L),j&&j({value:L}))},[M,u,j]);return M&&w?i.jsx(Gu,{title:m,tooltip:h,text:M&&x||y,css:g,type:N,icon:M&&c||s,onClick:A,disabled:l,children:_p(w,{value:M})}):b?i.jsx(Gu,{title:m,tooltip:h,text:M&&x||y,css:g,type:N,icon:M&&c||s,onClick:A,disabled:l,children:b}):i.jsx(Gu,{title:m,tooltip:h,text:M&&x||y,css:g,type:N,icon:M&&c||s,onClick:A,disabled:l})};function Cj(){return i.jsx(i.Fragment,{})}function fb(n){const{fonts:a=!0,children:s}=n;return i.jsx(Op.Provider,{value:"willow",children:i.jsxs(i.Fragment,{children:[s&&s&&i.jsx("div",{className:"wx-theme wx-willow-theme",children:s}),a&&i.jsxs(i.Fragment,{children:[i.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),i.jsx(Cj,{}),i.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Ip(ir);const Up={grid:{"Add before":"Add before","Add after":"Add after",Copy:"Copy",Cut:"Cut",Paste:"Paste",Delete:"Delete","New row":"New row","Move up":"Move up","Move down":"Move down",Undo:"Undo",Redo:"Redo",selected:"selected"}};new Date().valueOf();var fw=class{constructor(n){this._nextHandler=null,this._dispatch=n,this.exec=this.exec.bind(this)}async exec(n,a){return this._dispatch(n,a),this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};new Date().valueOf();var kj=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},s=new Map;s.set(0,a),this._pool=s,n&&n.length&&this.parse(n,0)}parse(n,a){const s=this._pool;for(let c=0;c<n.length;c++){const u=n[c];u.parent=u.parent||a,u.data=null,s.set(u.id,u)}for(let c=0;c<n.length;c++){const u=n[c],m=s.get(u.parent);m&&(m.data||(m.data=[]),m.data.push(u))}const l=s.get(a);this.setLevel(l,l.$level+1,!1)}add(n,a){const s=this._pool.get(n.parent||0);n.$level=s.$level+1,this._pool.set(n.id,n),s.data?a===-1?s.data=[...s.data,n]:mb(s,a,n):s.data=[n]}addAfter(n,a){if(!a)return this.add(n,-1);const s=this.byId(a),l=this.byId(s.parent),c=pf(l,s.id)+1;n.parent=l.id,n.$level=l.$level+1,this.add(n,c)}remove(n){const a=this._pool.get(n);this._remove(a);const s=this._pool.get(a.parent);s.data=s.data.filter(l=>l.id!=n),this._clearBranch(s)}_remove(n){n.data&&n.data.forEach(a=>this._remove(a)),this._pool.delete(n.id)}update(n,a){let s=this._pool.get(n);const l=this._pool.get(s.parent),c=pf(l,s.id);s={...s,...a},l&&c>=0&&(l.data[c]=s,l.data=[...l.data]),this._pool.set(s.id,s)}move(n,a,s){const l=this._pool.get(n),c=a==="child",u=this._pool.get(s),m=u.$level+(c?1:0);if(!l||!u)return;const h=this._pool.get(l.parent),g=c?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=pf(h,l.id);jj(h,y);const x=c?g.data.length:pf(g,u.id)+(a==="after"?1:0);if(mb(g,x,l),h.id===g.id&&y===x)return null;l.parent=g.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(h)}_clearBranch(n){n.data&&!n.data.length&&(n.open&&delete n.open,this.update(n.id,{data:null}))}toArray(){const n=[],a=this._pool.get(0).data;return a&&mw(a,n),n}byId(n){return this._pool.get(n)}getBranch(n){return this._pool.get(n).data}forEach(n){this._pool.forEach((a,s)=>{s!==0&&n(a)})}eachChild(n,a){const s=this.byId(a);!s||!s.data||s.data.forEach((l,c)=>{n(this.byId(l.id),c),this.eachChild(n,l.id)})}setLevel(n,a,s){n.data&&(n.data=n.data.map(l=>(s&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,s),l)))}};function mw(n,a){n.forEach(s=>{a.push(s),s.open===!0&&mw(s.data,a)})}function jj(n,a){const s=[...n.data];s.splice(a,1),n.data=s}function mb(n,a,s){const l=[...n.data];l.splice(a,0,s),n.data=l}function pf(n,a){return n?.data.findIndex(s=>s.id===a)}var hw=2,Mj=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,s=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,s),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,s,l,c,u,m){for(const h in a){const g=s[h],y=l[h],x=a[h];if(g&&(y===x&&typeof x!="object"||x instanceof Date&&y instanceof Date&&y.getTime()===x.getTime()))continue;const b=c+(c?".":"")+h;g?(g.__parse(x,b,u,m)&&(l[h]=x),m&hw?u[b]=g.__trigger:g.__trigger()):(x&&x.__reactive?s[h]=this._wrapNested(x,x,b,u):s[h]=this._wrapWritable(x),l[h]=x),u[b]=u[b]||null}}_wrapNested(a,s,l,c){const u=this._wrapWritable(a);return this._wrapProperties(a,u,s,l,c,0),u.__parse=(m,h,g,y)=>(this._wrapProperties(m,u,s,h,g,y),!1),u}_wrapWritable(a){const s=[],l=function(){for(let c=0;c<s.length;c++)s[c](a)};return{subscribe:c=>(s.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const u=s.indexOf(c);u>=0&&s.splice(u,1)}),__trigger:()=>{s.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function hb(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var Aj=class{constructor(a,s,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=s,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(m=>{const h=this._triggers.get(m)||[];h.push(u),this._triggers.set(m,h)}),u.out.forEach(m=>{const h=this._sources.get(m)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(m,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(m=>pw(m,this._sources,1)))}),this._bus=c}init(a){const s={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];s[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(s),this._bus&&this._bus.exec("init-state",s)}setStateAsync(a){const s=this._setter(a,hw);return this._async?Object.assign(this._async.signals,s):this._async={signals:s,timer:setTimeout(this._applyState.bind(this),1)},s}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const s in a.signals){const l=a.signals[s];l&&l()}}}setState(a,s=[]){const l=this._setter(a);return this._triggerUpdates(l,s),l}_triggerUpdates(a,s){const l=Object.keys(a),c=!s.length;s=s||[];for(let u=0;u<l.length;u++){const m=l[u],h=this._triggers.get(m);h&&h.forEach(g=>{s.indexOf(g)==-1&&s.push(g)})}c&&this._execNext(s)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const s=a[a.length-1];a.splice(a.length-1),s.exec(a)}}};function pw(n,a,s){const l=a.get(n);if(!l)return s;const c=Object.keys(l).map(u=>pw(u,a,s+1));return Math.max(...c)}var Nj=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,s,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(s):c.push(s):c=this._handlers[a]=[s],l&&l.tag&&this._tag.set(s,l.tag)}intercept(a,s,l){this.on(a,s,{...l,intercept:!0})}detach(a){for(const s in this._handlers){const l=this._handlers[s];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,s){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const u=l[c](s);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,s),s}setNext(a){return this._nextHandler=a}};const yc=1024;function Zu(n){return n<yc?`${n} B`:n<yc**2?`${(n/yc).toFixed(1)} KB`:n<yc**3?`${(n/yc**2).toFixed(1)} MB`:`${(n/yc**3).toFixed(1)} GB`}function pb(n,a){a||(a={key:"name",order:"asc"});const s=n.filter(m=>m.type==="folder"),l=n.filter(m=>m.type!=="folder"),c=s.sort(gb(a)),u=l.sort(gb(a));return[...c,...u]}function Tj(n,a){return typeof n=="string"?n.localeCompare(a,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-a.getTime():(n??0)-(a??0)}function Rj(n,a){return typeof n=="string"?-n.localeCompare(a,void 0,{numeric:!0}):typeof a=="object"?a.getTime()-n.getTime():(a??0)-(n??0)}function gb({key:n,order:a}){const s=a==="asc"?Tj:Rj;return(l,c)=>s(l[n],c[n])}function qp(n,a){const s=n==="/"?1:n.split("/").length;return s>=a.length?null:a[s].id}function Ej(n){return n.length>1?n[n.length-2].id:null}let Dj=class extends kj{constructor(a){const s={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([s]),this.parse(a,"/")}parse(a,s,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?s:void 0)),super.parse(a,s))}parseId(a,s){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=s??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const u=a.name.lastIndexOf("."),m=u!==-1?a.name.slice(u+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const s=[];let l=this.byId(a);if(!l)return s;for(;l.id!==0;)s.push(l),l=this.byId(l.parent);return s.reverse()}findFiles(a,s="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(c)!==-1&&l.push(u)},s),l}add(a,s){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,s??l.data?l.data.length:0),c&&c.forEach(u=>this.add(u))}renameFiles(a,s,l){const c=this.byId(a),u=this.normalizeFile(c,s),m=[];return u.data?.forEach(h=>m.push(this.renameFiles(h.id,u.id,l))),m.length&&(u.data=m),l[a]=u.id,u}copyFiles(a,s,l){const c={};return a.forEach(u=>{const m=this.renameFiles(u,s,c);this.add(m),l&&this.remove(u),c[u]=m.id}),c}moveFiles(a,s){if(this.byId(a[0]).parent!==s)return this.copyFiles(a,s,!0)}serialize(a="/"){const s=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:u,date:m,type:h,size:g,lazy:y}=c,x={id:u,date:m,type:h??"file"};y&&(x.lazy=y),g&&(x.size=g),s.push(x);const b=this.serialize(u);b.length&&s.push(...b)}),s):null}normalizeFile(a,s){const l=a.name,c=l.lastIndexOf("."),u=c!==-1?l.slice(c+1):"",m=u?`.${u}`:"";let h=c!==-1?l.slice(0,c):l,g=s+(s==="/"?"":"/")+h;for(;this.byId(g+m);){const y=".new";g+=y,h+=y}return{...a,id:g+m,name:h+m,parent:s,ext:u.toLocaleLowerCase()}}},Lj=class extends Mj{in;_router;constructor(a){super({writable:a,async:!1});const s=[];for(let u=0;u<2;u++)s.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},m)}}),s.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:m=>{const{data:h,panels:g,search:y}=this.getState();let x;y?x=h.findFiles(y,g[u].path):x=h.byId(g[u].path)?.data||[];const{path:b,_sorts:w}=g[u];x=pb(x,w[b]);const j=[];j[u]={_files:x},this.setState({panels:j},m)}}),s.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(M=>{const k=h.byId(M);k&&y.push(k)});const{path:x,_sorts:b}=g[u],w=pb(y,b[x]),j=[];j[u]={_selected:w},this.setState({panels:j},m)}});this._router=new Aj(super.setState.bind(this),s,{data:u=>new Dj(u)});const l=this.in=new Nj;l.on("select-file",({id:u,toggle:m,range:h,panel:g,type:y})=>{const{panels:x,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(m=h=!1);let w=[...x[g].selected];if(m){const M=w.indexOf(u);M===-1?w.push(u):w.splice(M,1)}else if(h&&x[g]._lastSelected){const M=x[g]._files;let k=M.findIndex(T=>T.id==x[g]._lastSelected),N=M.findIndex(T=>T.id==u);N<k&&([k,N]=[N,k]);const A=M.slice(k,N+1).map(T=>T.id);w=[...new Set([...w,...A])]}else w=u?[u]:[];const j=[];j[g]={selected:w,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:j})}),l.on("set-path",({id:u,panel:m,selected:h})=>{const{data:g,activePanel:y}=this.getState(),x=g.byId(u);if(x){const b=[];typeof m>"u"&&(m=y),b[m]={path:u},this.setState({panels:b}),l.exec("select-file",{panel:m}),h&&h.forEach(w=>l.exec("select-file",{id:w,panel:m,toggle:!0})),x.lazy&&l.exec("request-data",{id:u})}}),l.on("provide-data",({id:u,data:m})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(m,u,h==="search"),this.setState({data:g}))}),l.on("open-tree-folder",({id:u,mode:m})=>{const{data:h}=this.getState();h.update(u,{open:m}),this.setState({data:h})}),l.on("show-preview",({mode:u})=>{this.setState({preview:u})}),l.on("rename-file",u=>{const{id:m,name:h}=u,{data:g,panels:y}=this.getState(),x=g.byId(m);if(x.name!==h){x.name=h;const b=g.normalizeFile(x,x.parent);u.newId=b.id,b.data=null,g.add(b);let w={[m]:b.id};x.data?.forEach(M=>w={...g.moveFiles([M.id],b.id),...w});const j=y.map(M=>({selected:M.selected,_crumbs:M._crumbs,_lastSelected:M._lastSelected,_sorts:M._sorts}));g.remove(m),this._updatePanels(j,w),this.setState({data:g,panels:j})}}),l.on("create-file",u=>{const{file:m,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(m,h);y.type=m.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),l.exec("select-file",{id:y.id})}),l.on("delete-files",({ids:u})=>{const{data:m,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>m.remove(y)),this._updatePanels(g,{}),this.setState({data:m,panels:g})}),l.on("copy-files",u=>{const{ids:m,target:h}=u;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.copyFiles(m,h);u.newIds=m.map(w=>b[w]),this.setState({data:g}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(w=>{l.exec("select-file",{id:b[w],toggle:!0})}))}),l.on("move-files",u=>{const{ids:m,target:h}=u;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.moveFiles(m,h);if(b){u.newIds=m.map(j=>b[j]);const w=y.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));this._updatePanels(w,b,!0),this.setState({data:g,panels:w}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(j=>{l.exec("select-file",{id:b[j],toggle:!0})}))}});let c=null;l.on("filter-files",({text:u})=>{if(!u){c&&this.setState({...c});return}l.exec("select-file",{});const{panels:m,mode:h}=this.getState();c||(c={panels:m,mode:h,search:""}),this.setState({mode:"search",search:u})}),l.on("set-mode",({mode:u})=>{const{activePanel:m}=this.getState(),h=[];h[m]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};c=null,this.setState(g)}),l.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),l.on("sort-files",({key:u,order:m,panel:h,path:g})=>{const{activePanel:y,panels:x}=this.getState();h=h??y,g=g??x[h].path;const b=[];b[h]={_sorts:{...x[h]._sorts,[g]:{key:u,order:m}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=hb({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const s={panels:hb(a),data:[],search:""};this._router.init(s)}init(a){const s={...a};this._router.init(s)}setState(a,s){return this._router.setState(a,s)}getFile(a){const{data:s}=this.getState();return s.byId(a)||null}serialize(a){const{data:s}=this.getState();return s.serialize(a)}_updatePanels(a,s,l){const{data:c}=this.getState();a.forEach(u=>{const m=[];u.selected.forEach(y=>{c.byId(y)?m.push(y):!l&&s[y]&&m.push(s[y])}),u.selected=m,c.byId(u._lastSelected)||(u._lastSelected=l?null:s[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{c.byId(y)?h[y]=u._sorts[y]:s[y]&&!l&&(h[s[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(s[g.id]?u.path=s[g.id]:c.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(a,s){return a.some(l=>l===s||this.getState().data.getParents(s).some(c=>c.id===l))}};function _j(n){switch(n){case"body":return[{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"}];case"add":return[{icon:"mdi mdi-folder-plus-outline",text:"Add new file",id:"add-file"},{icon:"mdi mdi-file-plus-outline",text:"Add new folder",id:"add-folder"},{icon:"mdi mdi-file-upload-outline",text:"Upload file",id:"upload",comp:"upload"}];case"multiselect":return[{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{comp:"separator"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}];default:return[n==="folder"?null:{icon:"wxi-download",text:"Download",hotkey:"Ctrl+D",id:"download"},{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"},{comp:"separator"},{icon:"wxi-edit",text:"Rename",hotkey:"Ctrl+R",id:"rename"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}].filter(a=>a!==null)}}function Ij(n,a="data-id"){let s=n;for(!s.tagName&&n.target&&(s=n.target);s;){if(s.getAttribute&&s.getAttribute(a))return s;s=s.parentNode}return null}function zj(n,a="data-id"){const s=Ij(n,a);return s?s.getAttribute(a):null}new Date().valueOf();function Oj(n,a){const{api:s}=a;function l(u,m){const h=a.getPanel(),g=h.selected,y=m.ctrlKey||m.metaKey,x=m.shiftKey;let b;const w=g?.[0]?s.getFile(g[0]):null;g?.length?g.length>1?b=a.menuOptions("multiselect"):b=a.menuOptions(w.type,w):b=a.menuOptions("body");const j=`${y?"ctrl+":""}${x?"shift+":""}${u}`,M=b?b.find(N=>N.hotkey?.toLowerCase()===j):!1,k=a.performAction;if(M)switch(j){case"ctrl+c":k("copy");break;case"ctrl+x":k("move");break;case"ctrl+v":k("paste",w);break;case"delete":k("delete");break;case"ctrl+r":m.preventDefault(),k("rename",w);break;case"ctrl+d":m.preventDefault(),k("download",w);break;default:M.handler?.({context:w})}switch(u){case"enter":{if(y||x)break;const{_crumbs:N,_selectNavigation:A}=h;if(A){const T=Ej(N);if(T){const L=qp(T,N);s.exec("set-path",{id:T,selected:[L]})}}else if(g.length===1){const T=s.getFile(g[0]);T&&s.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:N,_selected:A,path:T,_selectNavigation:L}=h;let O;if(A.length){const I=A.at(0).id,B=N.findIndex(_=>_.id===I);if(B!==-1){const _=B-1;N[_]?O=N[_].id:T!=="/"&&!(y||x)&&s.exec("select-file",{type:"navigation"})}}else{if(L)break;if(T!=="/"){s.exec("select-file",{type:"navigation"});break}O=N.at(0)?.id}O&&s.exec("select-file",{id:O,toggle:y,range:x});break}case"arrowdown":case"arrowright":{const{_files:N,_selected:A,path:T,_selectNavigation:L}=h;let O;if(A.length){const I=A.at(-1).id,B=N.findIndex(_=>_.id===I);if(B!==-1){const _=B+1;N[_]&&(O=N[_].id)}}else{if(T!=="/"&&!L){s.exec("select-file",{type:"navigation"});break}O=N.at(0)?.id}O&&s.exec("select-file",{id:O,toggle:y,range:x});break}}}function c(u){const m=u.code.replace("Key","").toLowerCase();l(m,u),m=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&s.exec("set-active-panel",{panel:+zj(h,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Hj(n,a="data-id"){let s=n;for(!s.tagName&&n.target&&(s=n.target);s;){if(s.getAttribute&&s.getAttribute(a))return s;s=s.parentNode}return null}function Pj(n,a="data-id"){const s=n.getAttribute(a);return s?Fj(s):null}function Fj(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function $j(){return{detect:()=>!0,addEvent:function(n,a,s){return n.addEventListener(a,s),()=>n.removeEventListener(a,s)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var Bj=$j();new Date().valueOf();function gw(n){const[a,s]=d.useState(n),l=d.useRef(n);return d.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,s(n)}},[n]),[a,s]}function Uj(n,a,s){const[l,c]=d.useState(()=>a);return n||console.warn(`Writable ${s} is not defined`),d.useEffect(()=>n?n.subscribe(m=>{c(()=>m)}):void 0,[n]),l}function ht(n,a){const s=n.getState(),l=n.getReactiveState();return Uj(l[a],s[a],a)}function qj(n,a){const s=d.useRef(a);s.current=a;const[l,c]=d.useState(1);return d.useEffect(()=>n.subscribe(m=>{s.current=m,c(h=>h+1)}),[n]),[s.current,l]}function Pr(n,a){const s=n.getState(),l=n.getReactiveState();return qj(l[a],s[a])}function vw(n){const a={};return n.split(";").forEach(s=>{const[l,c]=s.split(":");if(c){let u=l.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(m,h)=>h.toUpperCase())),a[u]=c.trim()}}),a}function yw(n){let a=n,s=[];return{subscribe:h=>{s.push(h),h(a)},unsubscribe:h=>{s=s.filter(g=>g!==h)},set:h=>{a=h,s.forEach(g=>g(a))},update:h=>{a=h(a),s.forEach(g=>g(a))}}}function vb(n,a,s){function l(c){const u=Hj(c);if(!u)return;const m=Pj(u);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[s]&&a[s](m,c)}return Bj.addEvent(n,s,l)}function Gj(n,a){const s=[vb(n,a,"click")];return a.dblclick&&s.push(vb(n,a.dblclick,"dblclick")),()=>{s.forEach(l=>l())}}function bw(n,a){return n.map((s,l)=>{const c=a(s,l);return s.data&&s.data.length&&(c.data=bw(s.data,a)),c}).filter(Boolean)}function xw(n,a){const s=[];return n.forEach(l=>{if(l.data){const c=xw(l.data,a);c.length&&s.push({...l,data:c})}else a(l)&&s.push(l)}),s}function Vj(n){return bw(n,(a,s)=>{const l={...a,id:a.id||zp()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[s-1]?.comp==="separator"?null:l})}const ww={};function Wj(n){return ww[n]||n}function Yj(n,a){ww[n]=a}function Kj({onClick:n,onShow:a,option:s}){const l=d.useRef(null),c=d.useCallback(()=>{a(s.data?s.id:!1,l.current)},[a,s]),u=d.useCallback(h=>{if(s.data){h.stopPropagation(),a(s.id,l.current);return}n(h)},[n,a,s]),m=d.useMemo(()=>s&&s.comp?Wj(s.comp):null,[s]);return i.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${s.css||""} ${s.disabled?"wx-disabled":""}`,"data-id":na(s.id),onMouseEnter:c,onClick:u,children:[s.icon?i.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${s.icon}`}):null,s.comp?m?i.jsx(m,{item:s,option:s}):null:i.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",s.text," "]}),s.subtext?i.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:s.subtext}):null,s.data?i.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Gp({options:n,left:a=0,top:s=0,at:l="bottom",parent:c=null,mount:u=null,context:m=null,css:h="",onClick:g,onCancel:y}){const[x,b]=d.useState(-1e4),[w,j]=d.useState(-1e4),[M,k]=d.useState(20),[N,A]=d.useState(),T=d.useRef(null),[L,O]=d.useState(!1),[I,B]=d.useState(null),_=d.useCallback(()=>{const fe=aw(T.current,c,l,a,s);fe&&(b(fe.x),j(fe.y),A(fe.width));let Q=fe?.z??20;const z=c?Ok(c):[];let re=0;for(const V of z){const H=parseInt(getComputedStyle(V).zIndex,10);H>re&&(re=H)}re>=Q&&(Q=re+1),k(Q)},[c,l,a,s]);d.useEffect(()=>{u&&u(_)},[]);const G=d.useCallback(()=>{O(!1)},[]),te=d.useCallback((fe,Q)=>{O(fe),B(Q)},[]),W=d.useMemo(()=>Vj(n),[n]);d.useEffect(()=>{_()},[c,_]);const Y=d.useRef(g),F=d.useRef(y),ve=d.useRef(c);return d.useEffect(()=>{Y.current=g},[g]),d.useEffect(()=>{F.current=y},[y]),d.useEffect(()=>{ve.current=c},[c]),d.useEffect(()=>{if(!T.current)return;function fe(Q){F.current?F.current(Q):Y.current&&Y.current({action:null,option:null})}return Fs(T.current,{callback:fe,modal:!0,parent:()=>ve.current}).destroy},[]),i.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:w+"px",left:x+"px",width:N,zIndex:M},onMouseLeave:G,children:W.map(fe=>i.jsxs(d.Fragment,{children:[fe.comp==="separator"?i.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):i.jsx(Kj,{option:fe,onShow:te,onClick:Q=>{if(!fe.data&&!Q.defaultPrevented){const z={context:m,action:fe,option:fe,event:Q};fe.handler&&fe.handler(z),g&&g(z),Q.stopPropagation()}}}),fe.data&&L===fe.id?i.jsx(Gp,{css:h,options:fe.data,at:"right-overlap",parent:I,context:m,onClick:g,onCancel:y}):null]},fe.id))})}const Sw=d.forwardRef(function(n,a){const{options:s,at:l="bottom",resolver:c=null,dataKey:u="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,[x,b]=d.useState(null),[w,j]=d.useState(null),[M,k]=d.useState(0),[N,A]=d.useState(0),T=d.useRef(null),L=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),O=d.useMemo(()=>x!==null&&m?xw(s,G=>m(G,x)):s,[x,m,s]);function I(G){j(null),y&&y(G)}function B(G){if(T.current===G){T.current=null;return}j(null),y&&y({action:null,option:null})}const _=d.useCallback((G,te)=>{if(!G){j(null);return}if(G.defaultPrevented)return;const W=G.target;if(W&&W.dataset&&W.dataset.menuIgnore)return;if(w&&w===W){j(null),G.preventDefault();return}k(G.clientX+1),A(G.clientY+1);let Y=typeof te<"u"?te:Xu(W,L);c&&(Y=c(Y,G),!Y)||(b(Y),j(W),T.current=G.nativeEvent||G,G.preventDefault())},[w,L,c]);return d.useImperativeHandle(a,()=>({show:_}),[_]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onClick:_,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,w?i.jsx(Hp,{children:i.jsx(Gp,{css:h,at:l,top:N,left:M,parent:w,context:x,onClick:I,onCancel:B,options:O},w)}):null]})}),Qj=d.forwardRef(function(n,a){const{options:s,at:l="bottom",css:c="",children:u,onClick:m}=n,[h,g]=d.useState(null),y=d.useRef(null);function x(M){g(null),m&&m(M)}function b(M){if(y.current===M){y.current=null;return}g(null),m&&m({action:null,option:null})}const w=d.useCallback(M=>{g(M.target),y.current=M.nativeEvent||M,M.preventDefault()},[]);d.useImperativeHandle(a,()=>({show:w}),[w]);function j(M){let k=M.target;for(;!k.dataset.menuIgnore;)g(k),k=k.parentNode}return i.jsxs(i.Fragment,{children:[i.jsx("span",{onClick:j,"data-menu-ignore":"true",children:u}),h?i.jsx(Hp,{children:i.jsx(Gp,{css:c,at:l,parent:h,options:s,onClick:x,onCancel:b})}):null]})}),Xj=d.forwardRef(function(n,a){const{options:s,at:l="bottom",resolver:c=null,dataKey:u="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,x=d.useRef(null),b=d.useCallback((w,j)=>{x.current.show(w,j)},[]);return d.useImperativeHandle(a,()=>({show:b}),[b]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,i.jsx(Sw,{css:h,at:l,options:s,resolver:c,dataKey:u,filter:m,ref:x,onClick:y})]})}),Zj={uploader:{B:"B",KB:"KB",MB:"MB",GB:"GB",TB:"TB",PB:"PB",EB:"EB","Drop files here or":"Drop files here or","select files":"select files"}};let Jj=class{constructor(a,s,l,c,u){this.setFiles=a,this.setReady=s,this.setSignal=l,this.setDrag=c,u&&u.length&&this.setFiles(u)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const s=this.files;for(let l=0;l<s.length;l++){if(s[l].status==="client")return"client";s[l].status==="error"&&(a="error")}return a}droparea(a,s){s=s||{};const l=()=>{s.dragEnter&&s.dragEnter(),this.setDrag(!0)},c=()=>{s.dragLeave&&s.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},m=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",s,h]),s.dragLeave&&s.dragLeave(),s.drop&&s.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",u,!0),a.addEventListener("drop",m,!0),()=>{a.removeEventListener("dragenter",l),a.removeEventListener("dragleave",c),a.removeEventListener("dragover",u,!0),a.removeEventListener("drop",m,!0)}}updateFile(a,s){const l=this.files.findIndex(u=>u.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...s},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(s=>s.id!==a),this.setFiles(this.files)}addFile(a,s){s?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function Cw(n){const[a,s]=d.useState([]),[l,c]=d.useState(Promise.resolve(null)),[u,m]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new Jj(s,c,m,g,n)),y.current.files=a,y.current.ready=l,y.current.signal=u,y.current.drag=h,y.current}function eM(n,a){{if(n){const s=n.getGroup(a);if(s)return s}return Ju(Zj).getGroup(a)}}const tM=()=>Math.random().toString(36).substr(2,9),nM=({data:n,accept:a="",multiple:s=!0,folder:l=!1,uploadURL:c="",apiOnly:u=!1,disabled:m=!1,children:h,onChange:g,onUpload:y})=>{const x=d.useRef(null),b=d.useRef(null),[w,j]=d.useState({}),M=Cw(),k=n||M,N=d.useContext(ra.i18n),A=eM(N,"uploader");d.useEffect(()=>{x.current&&l&&(x.current.webkitdirectory=!0)},[l]),d.useEffect(()=>{if(!u&&b.current&&!m)return k.droparea(b.current)},[u,m,b]);const T=W=>{const Y=new FormData;return Y.append("upload",W.file),fetch(c,{method:"POST",body:Y}).then(F=>F.json()).then(F=>({id:W.id,...F}),()=>({id:W.id,status:"error"})).catch(F=>(console.log(F),{id:W.id,status:"error"}))},L=(W,Y)=>{const F=k.updateFile(W,Y),ve={...F,status:k.getState()};F&&F.uploaded&&F.uploaded(ve),y&&y(ve),F.temp&&k.deleteFile(F.id)},O=W=>{if(!W)return;const Y=typeof c=="function"?c(W):T(W);k.setReady(Y.then(F=>{F.status=F.status||"server",L(W.id,F)}).catch(F=>{L(W.id,{status:"error",error:F})}))},I=(W,Y)=>{const F={...Y||w,id:tM(),status:"client",name:W.name,file:W};F.selected&&F.selected(F),g&&g(F),k.addFile(F,s),O(F),x.current&&(x.current.value="")},B=(W,Y,F)=>{W.isFile?W.file(ve=>{I(ve,F)}):W.isDirectory&&W.createReader().readEntries(ve=>{ve.forEach(fe=>{B(fe,Y+fe.name+"/",F)})})},_=W=>{Array.from(W.target.files).forEach(Y=>I(Y))},G=(W,Y)=>{Array.from(W.dataTransfer.items).forEach(F=>{const ve=F.webkitGetAsEntry();ve&&B(ve,"",Y)})},te=()=>{x.current&&x.current.click()};return d.useEffect(()=>{if(k.signal){const[W,Y,F]=k.signal;j(Y),W==="click"?te():W==="drop"&&G(F,Y),k.setSignal(null)}},[k.signal]),u?i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:s,disabled:m}),h]}):i.jsxs("div",{className:`wx-at1A8tb8 wx-label ${k.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:b,children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:s,disabled:m}),h||i.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:i.jsxs("span",{children:[A("Drop files here or")," ",i.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:te,children:A("select files")})]})})]})};new Date().valueOf();function aM(n,a){if(Object.keys(n).length!==Object.keys(a).length)return!1;for(const s in a){const l=n[s],c=a[s];if(!Zf(l,c))return!1}return!0}function Zf(n,a){if(typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null)return n===a;if(typeof n!=typeof a||(n===null||a===null)&&n!==a||n instanceof Date&&a instanceof Date&&n.getTime()!==a.getTime())return!1;if(typeof n=="object")if(Array.isArray(n)&&Array.isArray(a)){if(n.length!==a.length)return!1;for(let s=n.length-1;s>=0;s--)if(!Zf(n[s],a[s]))return!1;return!0}else return aM(n,a);return n===a}function yp(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(yp);const a={};for(const s in n)a[s]=yp(n[s]);return a}var kw=2,rM=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,a=0){const s={};return this._wrapProperties(n,this._state,this._values,"",s,a),s}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,a,s,l,c,u){for(const m in n){const h=a[m],g=s[m],y=n[m];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const x=l+(l?".":"")+m;h?(h.__parse(y,x,c,u)&&(s[m]=y),u&kw?c[x]=h.__trigger:h.__trigger()):(y&&y.__reactive?a[m]=this._wrapNested(y,y,x,c):a[m]=this._wrapWritable(y),s[m]=y),c[x]=c[x]||null}}_wrapNested(n,a,s,l){const c=this._wrapWritable(n);return this._wrapProperties(n,c,a,s,l,0),c.__parse=(u,m,h,g)=>(this._wrapProperties(u,c,a,m,h,g),!1),c}_wrapWritable(n){const a=[],s=function(){for(let l=0;l<a.length;l++)a[l](n)};return{subscribe:l=>(a.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const c=a.indexOf(l);c>=0&&a.splice(c,1)}),__trigger:()=>{a.length&&(this._async?setTimeout(s,1):s())},__parse:function(l){return n=l,!0}}}},sM=class{constructor(n,a,s,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=a,this._parsers=s,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(c=>{c.in.forEach(u=>{const m=this._triggers.get(u)||[];m.push(c),this._triggers.set(u,m)}),c.out.forEach(u=>{const m=this._sources.get(u)||{};c.in.forEach(h=>m[h]=!0),this._sources.set(u,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(u=>jw(u,this._sources,1)))}),this._bus=l}init(n){const a={};for(const s in n)if(this._prev[s]!==n[s]){const l=this._parsers[s];a[s]=l?l(n[s]):n[s]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(a),this._bus&&this._bus.exec("init-state",a)}setStateAsync(n){const a=this._setter(n,kw);return this._async?Object.assign(this._async.signals,a):this._async={signals:a,timer:setTimeout(this._applyState.bind(this),1)},a}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const a in n.signals){const s=n.signals[a];s&&s()}}}setState(n,a=[]){const s=this._setter(n);return this._triggerUpdates(s,a),s}_triggerUpdates(n,a){const s=Object.keys(n),l=!a.length;a=a||[];for(let c=0;c<s.length;c++){const u=s[c],m=this._triggers.get(u);m&&m.forEach(h=>{a.indexOf(h)==-1&&a.push(h)})}l&&this._execNext(a)}_execNext(n){for(;n.length;){n.sort((s,l)=>s.length<l.length?1:-1);const a=n[n.length-1];n.splice(n.length-1),a.exec(n)}}};function jw(n,a,s){const l=a.get(n);if(!l)return s;const c=Object.keys(l).map(u=>jw(u,a,s+1));return Math.max(...c)}var iM=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,a,s){let l=this._handlers[n];l?s&&s.intercept?l.unshift(a):l.push(a):l=this._handlers[n]=[a],s&&s.tag&&this._tag.set(a,s.tag)}intercept(n,a,s){this.on(n,a,{...s,intercept:!0})}detach(n){for(const a in this._handlers){const s=this._handlers[a];for(let l=s.length-1;l>=0;l--)this._tag.get(s[l])===n&&s.splice(l,1)}}async exec(n,a){const s=this._handlers[n];if(s)for(let l=0;l<s.length;l++){const c=s[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};function lM(n){return a=>a[n]}function oM(n){return(a,s)=>a[n]=s}function Ol(n,a){return(a.getter||lM(a.id))(n)}function _h(n,a,s){return(a.setter||oM(a.id))(n,s)}function cM(n,a){const s=document.createElement("a");s.href=URL.createObjectURL(n),s.download=a,document.body.appendChild(s),s.click(),document.body.removeChild(s)}function zl(n,a){let s=Ol(n,a)??"";return a.template?s=a.template(s,n,a):a.optionsMap&&(Array.isArray(s)?s=s.map(l=>a.optionsMap.get(l)).join(", "):s=a.optionsMap.get(s)),typeof s>"u"?"":s+""}function uM(n,a){const s=/\n|"|;|,/;let l="";const c=a.rows||`
|
|
12
|
+
`):String(n||""),M=d.useMemo(()=>H1(n),[j]),k=d.useMemo(()=>M.find(T=>Uu(T)==="loopback")||M[0]||Rn,[M]),N=d.useCallback(async()=>{if(!a){l(null),u([]),y(""),h("");return}let T=null;const L=Date.now(),O=M.filter(I=>(w.current.get(I)||0)<=L);if(O.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const I of O)try{const[B,_]=await Promise.all([Ye("/api/remote/status",void 0,I),Ye("/api/remote/devices",void 0,I)]);if(!Array.isArray(_.devices))throw new Error("Invalid Hub devices response.");w.current.delete(I),l(B),u(_.devices),y(I),h("");return}catch(B){T=B,w.current.set(I,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,M]),A=d.useCallback(()=>{w.current.clear(),N().catch(T=>{h(T instanceof Error?T.message:String(T))}),b(T=>T+1)},[N]);return d.useEffect(()=>{if(!a){l(null),u([]),y(""),h("");return}let T=!0;const L=async()=>{try{await N()}catch(I){T&&h(I instanceof Error?I.message:String(I))}};L();const O=window.setInterval(L,2500);return()=>{T=!1,window.clearInterval(O)}},[a,N,x]),{status:s,devices:c,error:m,refresh:A,hubBaseUrl:g||k,hubCandidates:M}}function $1(n){const[a,s]=d.useState(null),[l,c]=d.useState(""),u=n?.user?.id||"",m=d.useCallback(async()=>{if(!u){s(null);return}const{data:h,error:g}=await bt.from($y).select("*").eq("user_id",u).maybeSingle();if(g){c(g.message);return}s(h),c("")},[u]);return d.useEffect(()=>{m()},[m]),d.useEffect(()=>{if(!u)return;const h=bt.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:$y,filter:`user_id=eq.${u}`},g=>s(g.new)).subscribe();return()=>{bt.removeChannel(h)}},[u]),{target:a,error:l,refresh:m}}function B1(n){const[a,s]=d.useState(null),[l,c]=d.useState(!1),[u,m]=d.useState(""),h=n?.user?.id||"",g=d.useCallback(async()=>{if(!h){s(null),m(""),c(!1);return}c(!0);const{data:x,error:b}=await bt.from(O1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){m(b.message),c(!1);return}s(x),m(""),c(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:y,loading:l,error:u,refresh:g}}const qu={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},U1=2500,q1=3e4,G1=64*1024,V1=6,W1=V1,Xx=new Map;function Y1(n){return Xx.get(n)}const By={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function K1(n,a,s){const l=Number(a);if(!Number.isFinite(l)||l<=0)return 0;const c=s-l,u=n.minimumHubClockOffsetMs;if(!Number.isFinite(u)||c<Number(u))return n.minimumHubClockOffsetMs=c,0;const m=Math.max(0,c-Number(u));return m>q1?(n.minimumHubClockOffsetMs=c,0):m}function Du(n){if(n==null||n==="")return;const a=Number(n);return Number.isFinite(a)?a:void 0}function Uy(n,a,s=Rn,l={}){const[c,u]=d.useState(new Map),[m,h]=d.useState("idle"),[g,y]=d.useState(""),[x,b]=d.useState(qu),w=d.useRef(new Map),j=d.useRef(new Map),M=d.useRef(0),k=d.useRef(new Map),N=d.useRef({enabled:!1,token:"",reason:""}),A=d.useRef(new Set),[T,L]=d.useState(0),O=d.useRef(l.onFrame),I=d.useRef(l.onStreamReady),B=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),_=d.useMemo(()=>[...n].sort().join(","),[n]),G=Number.isFinite(l.fps)?Number(l.fps):2,te=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,W=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,Y=Number.isFinite(l.quality)?Number(l.quality):45,F=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ve=l.streamPurpose==="control"?"control":"wall",fe=l.forceRestart===!0,Q=String(l.forceRestartToken||"").trim(),z=String(l.restartReason||"").trim();N.current={enabled:fe,token:Q,reason:z};const re=d.useMemo(()=>{const me=Object.entries(l.monitorSelections||{}).filter(([he])=>!!he).sort(([he],[J])=>he.localeCompare(J));return JSON.stringify(Object.fromEntries(me))},[l.monitorSelections]);d.useEffect(()=>{O.current=l.onFrame},[l.onFrame]),d.useEffect(()=>{I.current=l.onStreamReady},[l.onStreamReady]);const V=d.useCallback((me,he="livedesk-frame-socket-release")=>{me.disposed=!0;try{me.socket.readyState===WebSocket.CONNECTING||me.socket.readyState===WebSocket.OPEN?me.socket.close(1e3,he):me.socket.close()}catch{}},[]),H=d.useCallback(()=>{const me=[...j.current.values()].map(he=>he.socket);if(me.length===0){h("idle");return}if(me.some(he=>he.readyState===WebSocket.OPEN)){h("open");return}if(me.some(he=>he.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),le=d.useCallback((me,he,J,Ce)=>{if(he.disposed||he.socket.readyState!==WebSocket.OPEN)return!1;try{return he.socket.send(JSON.stringify({...he.payload,type:"restart-live",deviceIds:[me],forceRestart:!0,restartReason:J,restartToken:Ce})),!0}catch{return!1}},[]),oe=d.useCallback((me,he)=>{if(!me||me.byteLength<5)return;const J=Date.now(),Te=new DataView(me).getUint32(0,!1);if(Te<=0||Te+4>me.byteLength)return;const He=new Uint8Array(me,4,Te),ee=JSON.parse(Dp.decode(He)),Ue=Du(ee.hubPacketEpochMs),ft=Ue!==void 0&&Ue>0?Ue:void 0,ne=K1(he,ft,J);if(ne>U1)return;const xe=new Uint8Array(me,4+Te),Oe={deviceId:String(ee.deviceId||""),kind:ee.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(ee.frameSeq||0),streamFrameSeq:Number(ee.streamFrameSeq||0)||void 0,streamId:String(ee.streamId||""),commandId:ee.commandId?String(ee.commandId):void 0,sessionId:ee.sessionId?String(ee.sessionId):void 0,captureGeneration:Number(ee.captureGeneration||0)||void 0,streamPurpose:ee.streamPurpose?String(ee.streamPurpose):void 0,width:Number(ee.width||0),height:Number(ee.height||0),sourceWidth:Number(ee.sourceWidth||0)||void 0,sourceHeight:Number(ee.sourceHeight||0)||void 0,mimeType:String(ee.mimeType||"image/jpeg"),mode:ee.mode?String(ee.mode):void 0,frameMode:ee.frameMode?String(ee.frameMode):void 0,frameProfile:ee.frameProfile?String(ee.frameProfile):void 0,encoding:ee.encoding?String(ee.encoding):void 0,codec:ee.codec?String(ee.codec):void 0,compression:ee.compression?String(ee.compression):void 0,pixelFormat:ee.pixelFormat?String(ee.pixelFormat):void 0,bytesPerPixel:Number(ee.bytesPerPixel||0)||0,uncompressedByteLength:Number(ee.uncompressedByteLength||0)||0,h264Format:ee.h264Format?String(ee.h264Format):void 0,isKeyFrame:ee.isKeyFrame===!0,chunkType:ee.chunkType?String(ee.chunkType):void 0,timestampUs:Number(ee.timestampUs||0)||0,durationUs:Number(ee.durationUs||0)||0,sourceGapMs:Number(ee.sourceGapMs||0)||0,agentSendGapMs:Number(ee.agentSendGapMs||0)||0,agentSendDurationMs:Number(ee.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(ee.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(ee.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(ee.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(ee.agentFrameAgeMs||0)||0,nativeCaptureTelemetryAvailable:ee.nativeCaptureTelemetryAvailable===!0,nativeEncoderHardwareAccelerationKnown:ee.nativeEncoderHardwareAccelerationKnown===!0,nativeEncoderHardwareAccelerated:typeof ee.nativeEncoderHardwareAccelerated=="boolean"?ee.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:ee.nativeEncoderHardwareQueryStatus?String(ee.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureFps:Number(ee.nativeCaptureFps||0)||0,nativeEncodedFps:Number(ee.nativeEncodedFps||0)||0,nativeCaptureSampleCount:Number(ee.nativeCaptureSampleCount||0)||0,nativeEncodableFrameCount:Number(ee.nativeEncodableFrameCount||0)||0,nativeSkippedFrameCount:Number(ee.nativeSkippedFrameCount||0)||0,nativeEncodedFrameCount:Number(ee.nativeEncodedFrameCount||0)||0,nativeEncodeFramesInFlight:Number(ee.nativeEncodeFramesInFlight||0)||0,nativeBackpressureSkippedFrameCount:Number(ee.nativeBackpressureSkippedFrameCount||0)||0,nativeIdleSkippedFrameCount:Number(ee.nativeIdleSkippedFrameCount||0)||0,nativeCaptureTelemetryAt:ee.nativeCaptureTelemetryAt?String(ee.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(ee.droppedByAgent||0)||0,hubIngressDropped:Number(ee.hubIngressDropped||0)||0,hubClientDropped:Number(ee.hubClientDropped||0)||0,transport:ee.transport?String(ee.transport):void 0,videoTransport:ee.videoTransport?String(ee.videoTransport):void 0,frameTransportActive:ee.frameTransportActive?String(ee.frameTransportActive):void 0,frameTransportProtocol:ee.frameTransportProtocol?String(ee.frameTransportProtocol):void 0,frameTransportState:ee.frameTransportState?String(ee.frameTransportState):void 0,frameTransportReason:ee.frameTransportReason?String(ee.frameTransportReason):void 0,frameTransportChangedAt:ee.frameTransportChangedAt?String(ee.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(ee.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(ee.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:ee.frameTransportP2pReady===!0,hubClientQueueDepth:Number(ee.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(ee.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(ee.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(ee.udpIncompleteFrames||0)||0,hardwareEncoder:ee.hardwareEncoder?String(ee.hardwareEncoder):void 0,platformProfile:ee.platformProfile?String(ee.platformProfile):void 0,monitorIndex:Number.isFinite(Number(ee.monitorIndex))?Number(ee.monitorIndex):void 0,monitorCount:Number.isFinite(Number(ee.monitorCount))?Number(ee.monitorCount):void 0,requestedFps:Number(ee.requestedFps||0)||0,effectiveFps:Number(ee.effectiveFps||0)||0,captureTimingAvailable:ee.captureTimingAvailable===!0,captureAverageMs:Du(ee.captureAverageMs),captureP95Ms:Du(ee.captureP95Ms),slowFrameCount:Number(ee.slowFrameCount||0)||0,captureHelperRestarts:Number(ee.captureHelperRestarts||0)||0,capturedAt:String(ee.capturedAt||""),receivedAt:String(ee.receivedAt||""),hubPacketAt:ee.hubPacketAt?String(ee.hubPacketAt):void 0,hubPacketEpochMs:ft,browserReceivedEpochMs:J,hubPacketTransitAgeMs:ft!==void 0?ne:void 0,byteLength:Number(ee.byteLength||xe.byteLength),contentHash:ee.contentHash?String(ee.contentHash):void 0,captureMs:Du(ee.captureMs),captureStageMs:Du(ee.captureStageMs),convertMs:Number(ee.convertMs||0)||0,compressMs:Number(ee.compressMs||0)||0,captureSourceSerial:Number(ee.captureSourceSerial||0)||0,captureSourceSkipped:Number(ee.captureSourceSkipped||0)||0,deltaTileSize:Number(ee.deltaTileSize||0)||0,deltaTileCount:Number(ee.deltaTileCount||0)||0,deltaVisualTileCount:Number(ee.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(ee.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(ee.deltaTotalTiles||0)||0,payload:xe};if(!Oe.deviceId)return;const $e=Number(he.payload.monitorSelections?.[Oe.deviceId]);if(Number.isFinite($e)&&Number.isFinite(Number(Oe.monitorIndex))&&Number(Oe.monitorIndex)!==$e)return;const ze={streamId:he.lastFrameStreamId,commandId:he.lastFrameCommandId,order:he.lastFrameOrder},Qe=Number(Oe.streamFrameSeq||Oe.frameSeq||0),qe=!!ze.commandId&&!!Oe.commandId,We=ze.streamId===Oe.streamId&&(!qe||ze.commandId===Oe.commandId),lt=ze.order;if(We&<>=Qe&&(lt===Qe||qe))return;he.lastFrameStreamId=Oe.streamId,he.lastFrameCommandId=Oe.commandId||"",he.lastFrameOrder=Qe;const U=B.current;U.totalFrames+=1,U.totalBytes+=xe.byteLength,U.sampleFrames+=1,U.sampleBytes+=xe.byteLength;const ye=!w.current.has(Oe.deviceId);w.current.set(Oe.deviceId,Oe),ye&&u(new Map(w.current)),O.current?.(Oe)},[]);d.useEffect(()=>{const me=window.setInterval(()=>{const he=performance.now(),J=B.current,Ce=Math.max(1,he-J.sampleStartedAt);b({totalFrames:J.totalFrames,totalBytes:J.totalBytes,framesPerSecond:J.sampleFrames*1e3/Ce,bytesPerSecond:J.sampleBytes*1e3/Ce,sampleMs:Ce,lastUpdatedAt:Date.now()}),u(new Map(w.current)),J.sampleFrames=0,J.sampleBytes=0,J.sampleStartedAt=he},2e3);return()=>{window.clearInterval(me)}},[]),d.useEffect(()=>{const me=_?_.split(",").filter(Boolean):[],he=new Set(me),J=performance.now();for(const[Ce,Te]of j.current.entries())he.has(Ce)||(V(Te,"livedesk-device-unsubscribed"),j.current.delete(Ce),k.current.delete(Ce),w.current.delete(Ce));if(me.length===0){for(const Ce of j.current.values())V(Ce,"livedesk-no-devices");j.current.clear(),k.current.clear(),w.current=new Map,u(new Map),y(""),B.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},b(qu),H();return}B.current.sampleStartedAt<=0&&(B.current.sampleStartedAt=J,b({...qu,lastUpdatedAt:Date.now()}));for(const Ce of me){const Te=Number(l.monitorSelections?.[Ce]),He=Number.isInteger(Te)&&Te>=0?Te:0,ee={[Ce]:He},Ue={type:"subscribe",deviceIds:[Ce],autoStartLive:a,fps:G,maxWidth:te,maxHeight:W,quality:Y,mode:F,frameMode:F,streamPurpose:ve,monitorSelections:ee},ft=JSON.stringify(Ue),ne=j.current.get(Ce),xe=Number(ne?.payload.monitorSelections?.[Ce]),Oe=Number(ee[Ce]),$e=!!ne&&Number.isFinite(xe)&&Number.isFinite(Oe)&&xe!==Oe;if(ne){const We=ne.socket.readyState===WebSocket.CONNECTING||ne.socket.readyState===WebSocket.OPEN;if(ne.payloadKey===ft&&We&&!ne.disposed)continue}const ze=ne&&(ne.socket.readyState===WebSocket.CONNECTING||ne.socket.readyState===WebSocket.OPEN)&&!ne.disposed?ne.handoffFrom&&!ne.handoffCompleted?ne.handoffFrom:ne:void 0;ne&&ne!==ze&&V(ne,"livedesk-subscription-superseded");const Qe=new WebSocket(Vf(`/api/remote/frames/ws?devices=${encodeURIComponent(Ce)}`,s));Qe.binaryType="arraybuffer";const qe={socket:Qe,payload:Ue,payloadKey:ft,generation:M.current+1,monitorRestartToken:$e?`monitor-${Ce}-${Oe}-${M.current+1}`:"",disposed:!1,handoffFrom:ze,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};M.current=qe.generation,$e&&(w.current.delete(Ce),u(new Map(w.current))),j.current.set(Ce,qe),Qe.addEventListener("open",()=>{if(qe.disposed||j.current.get(Ce)!==qe){V(qe,"livedesk-stale-frame-socket");return}y("");const We=N.current,lt=We.enabled&&(!We.token||k.current.get(Ce)!==We.token),U=lt||qe.monitorRestartToken!=="",ye=lt?We.token:qe.monitorRestartToken,je=lt?We.reason:qe.monitorRestartToken?"monitor-selection-change":"";Qe.send(JSON.stringify({...qe.payload,forceRestart:U,restartReason:U?je:"",restartToken:U?ye:""})),lt&&We.token&&k.current.set(Ce,We.token);const Fe=qe.handoffFrom;qe.handoffFrom=void 0,qe.handoffCompleted=!0,Fe&&!Fe.disposed&&V(Fe,"livedesk-subscription-replaced"),H()}),Qe.addEventListener("message",We=>{if(qe.disposed||j.current.get(Ce)!==qe)return;if(typeof We.data=="string"){try{const U=JSON.parse(We.data);if(U?.type==="RemoteFrameSubscriptionError")y(String(U.error||"control-stream-start-failed"));else if(U?.type==="RemoteFrameLiveAutoStart"){const je=(Array.isArray(U.skipped)?U.skipped:[]).find(Fe=>Fe?.deviceId===Ce);if(je)y(String(je.reason||"control-stream-start-failed"));else if(Array.isArray(U.started)){const Fe=U.started.find(ut=>ut?.deviceId===Ce);Fe&&(y(""),Fe.ready===!0&&Fe.streamPurpose==="control"&&Fe.sessionId&&Fe.commandId&&Number(Fe.captureGeneration||0)>0&&I.current?.({deviceId:Ce,sessionId:String(Fe.sessionId),streamId:String(Fe.streamId||""),streamPurpose:"control",commandId:String(Fe.commandId),captureGeneration:Number(Fe.captureGeneration),monitorIndex:Number(Fe.monitorIndex||0)}))}}else U?.type==="RemoteFrameStreamReady"&&U.deviceId===Ce&&U.streamPurpose==="control"&&U.sessionId&&U.commandId&&Number(U.captureGeneration||0)>0&&(y(""),I.current?.({deviceId:Ce,sessionId:String(U.sessionId),streamId:String(U.streamId||""),streamPurpose:"control",commandId:String(U.commandId),captureGeneration:Number(U.captureGeneration),monitorIndex:Number(U.monitorIndex||0)}))}catch{}return}const lt=We.data instanceof ArrayBuffer?We.data:null;lt&&(y(""),oe(lt,qe))}),Qe.addEventListener("error",()=>{qe.disposed||j.current.get(Ce)!==qe||h("connecting")}),Qe.addEventListener("close",()=>{const We=!qe.disposed;qe.disposed=!0;const lt=j.current.get(Ce);let U=!1;if(lt===qe){const ye=qe.handoffFrom;qe.handoffFrom=void 0,ye&&!ye.disposed&&(ye.socket.readyState===WebSocket.CONNECTING||ye.socket.readyState===WebSocket.OPEN)?(j.current.set(Ce,ye),U=!0):j.current.delete(Ce)}if(H(),We&<===qe&&!U){const ye=window.setTimeout(()=>{A.current.delete(ye),L(je=>je+1)},750);A.current.add(ye)}})}H()},[a,V,_,G,F,oe,s,W,te,re,l.monitorSelections,Y,T,ve,H]),d.useEffect(()=>{if(!fe||!Q)return;const me=_?_.split(",").filter(Boolean):[];for(const he of me){if(k.current.get(he)===Q)continue;const J=j.current.get(he);!J||!le(he,J,z,Q)||k.current.set(he,Q)}},[_,fe,Q,z,le]),d.useEffect(()=>()=>{for(const me of j.current.values())V(me,"livedesk-hook-unmount");j.current.clear();for(const me of A.current)window.clearTimeout(me);A.current.clear()},[V]);const X=d.useCallback((me,he="browser-stale")=>{const J=Array.isArray(me)&&me.length>0?me:_.split(",").filter(Boolean);if(J.length===0)return!1;let Ce=!1;for(const Te of J){const He=j.current.get(Te);!He||He.socket.readyState!==WebSocket.OPEN||(Ce=le(Te,He,he,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Ce)}return Ce},[_,le]),be=d.useCallback((me,he="browser-reconnect")=>{const J=Array.isArray(me)&&me.length>0?me:_.split(",").filter(Boolean);if(J.length===0)return!1;let Ce=!1;for(const Te of J){const He=j.current.get(Te);He&&(V(He,`livedesk-${he}`),j.current.delete(Te),k.current.delete(Te),w.current.delete(Te),Ce=!0)}return Ce&&u(new Map(w.current)),L(Te=>Te+1),H(),!0},[V,_,H]);return{frames:c,state:m,error:g,stats:x,restartLive:X,reconnectLive:be}}function Q1(n,a,s=Rn,l={}){const[c,u]=d.useState(null),[m,h]=d.useState(null),[g,y]=d.useState("idle"),[x,b]=d.useState(qu),w=d.useRef(null),j=d.useRef(l.onFrame),M=d.useRef(null),k=d.useRef(0),N=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),A=d.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=d.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),L=d.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),O=d.useMemo(()=>({deviceIds:A.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(l.fps||20),inputFps:Number(l.inputFps||8),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[T,A,L,l.fps,l.height,l.inputFps,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),I=d.useMemo(()=>JSON.stringify(O),[O]),B=d.useRef(O);B.current=O;const _=a&&O.deviceIds.length>0,G=d.useCallback(W=>W.readyState!==WebSocket.OPEN?!1:(W.send(JSON.stringify({type:"configure",...B.current})),!0),[]);d.useEffect(()=>{j.current=l.onFrame},[l.onFrame]),d.useEffect(()=>{const W=window.setInterval(()=>{const Y=N.current,F=performance.now(),ve=Math.max(1,F-Y.sampleStartedAt);b({totalFrames:Y.totalFrames,totalBytes:Y.totalBytes,framesPerSecond:Y.sampleFrames*1e3/ve,bytesPerSecond:Y.sampleBytes*1e3/ve,sampleMs:ve,lastUpdatedAt:Date.now()});const fe=M.current;fe&&fe.frameSeq!==k.current&&(k.current=fe.frameSeq,u(fe)),Y.sampleFrames=0,Y.sampleBytes=0,Y.sampleStartedAt=F},1e3);return()=>window.clearInterval(W)},[]),d.useEffect(()=>{if(!_){w.current?.close(),w.current=null,u(null),M.current=null,k.current=0,h(null),y("idle"),b(qu);return}let W=!1,Y=0;const F=()=>{if(W)return;const ve=new WebSocket(Vf("/api/remote/atlas/ws",s));ve.binaryType="arraybuffer",w.current=ve,y("connecting"),ve.addEventListener("open",()=>{N.current.sampleStartedAt=performance.now(),y("open"),G(ve)}),ve.addEventListener("message",fe=>{if(typeof fe.data=="string"){try{const z=JSON.parse(fe.data);z?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(z.layoutVersion||0),width:Number(z.width||1920),height:Number(z.height||1080),columns:Number(z.columns||1),rows:Number(z.rows||1),tiles:Array.isArray(z.tiles)?z.tiles:[]})}catch{}return}const Q=fe.data instanceof ArrayBuffer?fe.data:null;if(!(!Q||Q.byteLength<5))try{const z=Date.now(),V=new DataView(Q).getUint32(0,!1);if(V<=0||V+4>Q.byteLength)return;const H=JSON.parse(Dp.decode(new Uint8Array(Q,4,V))),le=new Uint8Array(Q,4+V),oe={deviceId:String(H.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(H.frameSeq||0),streamFrameSeq:Number(H.streamFrameSeq||0)||void 0,streamId:String(H.streamId||"mode4-atlas"),commandId:H.commandId?String(H.commandId):void 0,width:Number(H.width||1920),height:Number(H.height||1080),sourceWidth:Number(H.sourceWidth||H.width||1920),sourceHeight:Number(H.sourceHeight||H.height||1080),mimeType:String(H.mimeType||"video/h264"),mode:String(H.mode||"mode4-h264-atlas"),frameMode:String(H.frameMode||"mode4-h264-atlas"),frameProfile:String(H.frameProfile||"mode4-h264-atlas-v1"),encoding:String(H.encoding||"video-atlas"),codec:String(H.codec||"h264"),compression:String(H.compression||"video/h264"),h264Format:String(H.h264Format||"annexb"),isKeyFrame:H.isKeyFrame===!0,chunkType:String(H.chunkType||""),timestampUs:Number(H.timestampUs||0),durationUs:Number(H.durationUs||0),transport:H.transport?String(H.transport):void 0,videoTransport:H.videoTransport?String(H.videoTransport):void 0,frameTransportActive:H.frameTransportActive?String(H.frameTransportActive):void 0,frameTransportProtocol:H.frameTransportProtocol?String(H.frameTransportProtocol):void 0,frameTransportState:H.frameTransportState?String(H.frameTransportState):void 0,frameTransportReason:H.frameTransportReason?String(H.frameTransportReason):void 0,frameTransportChangedAt:H.frameTransportChangedAt?String(H.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(H.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(H.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:H.frameTransportP2pReady===!0,hubClientQueueDepth:Number(H.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(H.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(H.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(H.udpIncompleteFrames||0)||0,hardwareEncoder:H.hardwareEncoder?String(H.hardwareEncoder):void 0,platformProfile:H.platformProfile?String(H.platformProfile):void 0,capturedAt:String(H.capturedAt||""),receivedAt:String(H.receivedAt||""),hubPacketAt:H.hubPacketAt?String(H.hubPacketAt):void 0,hubPacketEpochMs:Number(H.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:z,byteLength:le.byteLength,layoutVersion:Number(H.layoutVersion||0),atlasComposeMs:Number(H.atlasComposeMs||0),atlasPoolStarved:Number(H.atlasPoolStarved||0),atlasReadyTiles:Number(H.atlasReadyTiles||0),atlasTileCount:Number(H.atlasTileCount||0),atlasInputRevision:Number(H.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(H.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(H.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(H.atlasSourceMaxAgeMs||0),payload:le},X=N.current;X.totalFrames+=1,X.totalBytes+=le.byteLength,X.sampleFrames+=1,X.sampleBytes+=le.byteLength,M.current=oe,k.current===0&&(k.current=oe.frameSeq,u(oe)),j.current?.(oe)}catch{}}),ve.addEventListener("error",()=>y("error")),ve.addEventListener("close",()=>{w.current===ve&&(w.current=null),!W&&(y("closed"),Y=window.setTimeout(F,1200))})};return F(),()=>{W=!0,window.clearTimeout(Y),w.current?.close(),w.current=null}},[_,s,G]),d.useEffect(()=>{if(!_)return;const W=w.current;W&&G(W)},[I,_,G]);const te=d.useCallback(()=>{const W=w.current;return W?G(W):!1},[G]);return{frame:c,layout:m,state:g,stats:x,refreshInputs:te}}function X1(n,a=Rn){const s=d.useRef(null),l=d.useRef(0),c=d.useRef(0),u=d.useRef(new Map),m=d.useRef(""),[h,g]=d.useState("idle"),[y,x]=d.useState(""),[b,w]=d.useState(By),j=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});d.useEffect(()=>{if(!n){s.current?.close(),s.current=null,c.current=0,m.current="",u.current.clear(),g("idle"),x(""),w(By);return}let k=!1,N=0;const A=()=>{if(k)return;const T=new WebSocket(Vf("/api/remote/input/ws",a));s.current=T,j.current.sampleStartedAt=performance.now(),g("connecting"),x(""),T.addEventListener("open",()=>{k||s.current!==T||(x(""),g("open"))}),T.addEventListener("message",L=>{if(!(k||s.current!==T||typeof L.data!="string"))try{const O=JSON.parse(L.data),I=Number(O.inputSeq||O.result?.inputSeq||0),B=String(O.deviceId||O.result?.deviceId||""),_=String(O.inputEventId||O.result?.inputEventId||""),G=u.current.get(I);if(B&&(G&&G.deviceId!==B||!G&&m.current&&m.current!==B)||G?.inputEventId&&_&&G.inputEventId!==_)return;if(O?.type==="RemoteInputError"){I>0&&u.current.delete(I),x(String(O.error||O.result?.error||"Remote input failed.")),T.readyState===WebSocket.OPEN&&g("open");return}if(O?.type!=="RemoteInputApplied")return;G&&(j.current.lastRoundTripMs=Math.max(0,performance.now()-G.sentAt),u.current.delete(I)),j.current.lastInputSeq=I,j.current.lastAgentApplyMs=Math.max(0,Number(O.agentApplyMs||0)),x(""),g("open")}catch{}}),T.addEventListener("close",()=>{k||s.current!==T||(s.current=null,g("closed"),N=window.setTimeout(A,1200))}),T.addEventListener("error",()=>{!k&&s.current===T&&g("error")})};return A(),()=>{k=!0,window.clearTimeout(N);const T=s.current;s.current=null,T?.close(),u.current.clear()}},[n,a]),d.useEffect(()=>{if(!n)return;const k=window.setInterval(()=>{const N=performance.now(),A=j.current,T=Math.max(1,N-A.sampleStartedAt);w({totalSent:A.totalSent,totalDropped:A.totalDropped,sentPerSecond:A.sampleSent*1e3/T,droppedPerSecond:A.sampleDropped*1e3/T,bufferedAmount:s.current?.bufferedAmount||0,lastInputType:A.lastInputType,lastInputSeq:A.lastInputSeq,lastRoundTripMs:A.lastRoundTripMs,lastAgentApplyMs:A.lastAgentApplyMs,lastUpdatedAt:Date.now()}),A.sampleSent=0,A.sampleDropped=0,A.sampleStartedAt=N},1e3);return()=>window.clearInterval(k)},[n]);const M=d.useCallback((k,N)=>{const A=s.current;if(!A||A.readyState!==WebSocket.OPEN||!k)return!1;const T=String(N.type||"").toLowerCase(),L=T==="pointermove",I=L||T==="wheel",B=j.current;if(L&&A.bufferedAmount>G1)return B.totalDropped+=1,B.sampleDropped+=1,B.lastInputType="pointermove-drop",!1;const _=l.current+1;l.current=_;const G=`${_}-${crypto.randomUUID()}`,te=Date.now(),W=!I||_-c.current>=W1;for(W&&(u.current.set(_,{sentAt:performance.now(),deviceId:k,inputEventId:G}),I&&(c.current=_)),m.current=k,L||Xx.set(k,{inputSeq:_,inputType:T||"input",sentAt:performance.now()});u.current.size>256;){const Y=u.current.keys().next().value;if(Y===void 0)break;u.current.delete(Y)}return A.send(JSON.stringify({type:"input",requestId:I?"":crypto.randomUUID(),fireAndForget:I,deviceId:k,input:{...N,inputEventId:G,inputSeq:_,requestAck:W,issuedAtEpochMs:te,issuedAt:new Date(te).toISOString()}})),B.totalSent+=1,B.sampleSent+=1,B.lastInputType=T||"input",!0},[]);return{state:h,sendInput:M,stats:b,error:y}}function Z1(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const rf={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,lastUpdatedAt:0},J1=.08,ek=.25,tk=.02,qy=300,nk=4,sf=1500,Th=5e3,ak=2e3,rk=1e4,lf=[0,1e3,3e3];function Gy(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function sk(n,a,s){const l=Math.max(1,Math.min(8,Math.floor(a.channels||2))),c=Math.max(8e3,Math.min(192e3,Math.floor(a.sampleRate||48e3))),u=String(a.mimeType||"").toLowerCase(),m=u.includes("s16le")||u.includes("audio/l16"),h=m?2:4,g=Math.floor(s.byteLength/h),y=Math.floor(g/l),x=n.createBuffer(l,y,c),b=new DataView(s);for(let w=0;w<l;w+=1){const j=x.getChannelData(w);for(let M=0;M<y;M+=1){const N=(M*l+w)*h;j[M]=m?Math.max(-1,Math.min(1,b.getInt16(N,!0)/32768)):Math.max(-1,Math.min(1,b.getFloat32(N,!0)))}}return x}function ik(n,a,s=Rn){const l=d.useRef(null),c=d.useRef(0),[u,m]=d.useState("idle"),[h,g]=d.useState(null),[y,x]=d.useState(rf),[b,w]=d.useState("");return d.useEffect(()=>{if(!a||!n){m("idle"),g(null),x(rf),w("");return}m("connecting"),g(null),x(rf),w("");const j=window.AudioContext||window.webkitAudioContext;if(!j){m("unsupported"),x(rf),w("Audio playback is not supported in this browser.");return}const M=new j;l.current=M,c.current=M.currentTime;const k=new WebSocket(Vf("/api/remote/audio/ws?devices="+encodeURIComponent(n),s));k.binaryType="arraybuffer";const N=new Set,A={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(M.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let T=!1,L=0,O=!1,I=0,B=0;const _=(z=!0)=>{for(const re of N)try{re.stop()}catch{}N.clear(),z&&(c.current=M.currentTime+J1)},G=()=>{A.audioContextState=String(M.state),!T&&(A.audioContextState==="suspended"||A.audioContextState==="interrupted"?m("suspended"):A.audioContextState==="closed"&&(m("error"),w("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},te=async()=>{if(T||String(M.state)==="closed")return!1;try{if(String(M.state)!=="running"&&await M.resume(),A.audioContextState=String(M.state),!T&&!O&&A.audioContextState==="running"){const z=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=sf,re=A.lastCaptureStatusAt>0&&performance.now()-A.lastCaptureStatusAt<=Th&&A.captureAlive&&A.helperAlive;m(z?"playing":re?"silent":"open")}return A.audioContextState==="running"}catch(z){return T||(m("suspended"),w(z instanceof Error?"Audio playback is suspended: "+z.message:"Audio playback is suspended.")),!1}},W=async()=>{if(T||O||k.readyState!==WebSocket.OPEN)return;if(I>=lf.length){m("error"),w("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const z=I;I+=1,O=!0,A.stalledCount+=1,A.automaticRestarts+=1,m("reconnecting");try{const re=await Ye("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},s);if(re.ok===!1)throw new Error(re.error||"Remote audio stop failed.");if(T)return;const V=await Ye("/api/remote/devices/"+encodeURIComponent(n)+"/audio/start",{method:"POST",body:JSON.stringify({streamId:"audio-restart-"+Date.now(),mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},s);if(V.ok===!1)throw new Error(V.error||"Remote audio start failed.");const H=performance.now();L=H,A.lastPacketAt=H,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,B=H+(lf[z+1]??3e3),w(""),T||m("open")}catch(re){T||(B=performance.now()+(lf[z+1]??3e3),m("error"),w(re instanceof Error?"Remote audio restart failed: "+re.message:"Remote audio restart failed."))}finally{O=!1}},Y=()=>{A.drops+=1},F=window.setInterval(()=>{if(T)return;const z=performance.now(),re=A.lastPacketAt>0?Math.max(0,z-A.lastPacketAt):L>0?Math.max(0,z-L):0,V=A.lastAcceptedAt>0?Math.max(0,z-A.lastAcceptedAt):0,H=A.lastCaptureStatusAt>0?Math.max(0,z-A.lastCaptureStatusAt):0,le=k.readyState===WebSocket.OPEN,oe=A.lastCaptureStatusAt>0,X=oe&&H<=Th,be=oe&&(!A.captureAlive||!A.helperAlive)&&H>ak,me=oe&&H>Th,he=!oe&&L>0&&z-L>rk,J=L>0&&(A.lastAcceptedAt<=0?z-L>sf:V>sf);le&&L>0&&(be||me||he)?I>=lf.length&&!O?(m("error"),w("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!O&&z>=B?W():O||m("stalled"):le&&J&&!O&&A.audioContextState!=="suspended"&&A.audioContextState!=="interrupted"&&m(X?"silent":"open"),x({queuedMs:Math.max(0,(c.current-M.currentTime)*1e3),browserAgeMs:A.browserAgeMs,captureAgeMs:A.captureAgeMs,captureStatusAgeMs:H,silentForMs:A.silentForMs,captureAlive:A.captureAlive,helperAlive:A.helperAlive,captureRestartCount:A.captureRestartCount,localProcessingAgeMs:A.localProcessingAgeMs,lastPacketAgeMs:re,lastAcceptedAgeMs:V,framesReceived:A.framesReceived,drops:A.drops,resyncs:A.resyncs,pendingDecodes:A.pendingDecodes,lastFrameSeq:A.lastFrameSeq,audioContextState:A.audioContextState,stalledCount:A.stalledCount,automaticRestarts:A.automaticRestarts,lastUpdatedAt:Date.now()})},250),ve=()=>{G(),(String(M.state)==="suspended"||String(M.state)==="interrupted")&&te()},fe=()=>{document.visibilityState==="visible"&&te()},Q=()=>{te()};return M.addEventListener("statechange",ve),document.addEventListener("visibilitychange",fe),window.addEventListener("pageshow",Q),window.addEventListener("pointerdown",Q),window.addEventListener("keydown",Q),m("connecting"),w(""),G(),k.addEventListener("open",()=>{T||(L=performance.now(),A.lastPacketAt=L,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,m("open"),k.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),te())}),k.addEventListener("message",z=>{if(typeof z.data=="string")return;const re=z.data instanceof ArrayBuffer?z.data:null;if(!re||re.byteLength<5)return;const V=performance.now();A.lastPacketAt=V,(async()=>{try{const le=new DataView(re).getUint32(0,!1);if(le<=0||le+4>re.byteLength){Y();return}const oe=new Uint8Array(re,4,le),X=JSON.parse(Dp.decode(oe)),be=re.slice(4+le),me=String(X.frameKind||X.kind||"").toLowerCase();if(X.type==="remote.audio.status"||me==="audio-status"){if(A.lastCaptureStatusAt=V,A.captureAlive=X.captureAlive===!0,A.helperAlive=X.helperAlive===!0,A.captureRestartCount=Math.max(0,Number(X.restartCount||0)||0),A.lastPcmAtEpochMs=Math.max(0,Number(X.lastPcmAtEpochMs||0)||0),A.silentForMs=Math.max(0,Number(X.silentForMs||0)||0),A.captureAgeMs=A.lastPcmAtEpochMs>0?Math.max(0,Date.now()-A.lastPcmAtEpochMs):A.silentForMs,A.captureAlive&&A.helperAlive){if(I=0,B=0,!O){w("");const J=String(M.state)==="running",Ce=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=sf;m(J?Ce?"playing":"silent":"suspended")}}else O||m("stalled");return}const he={deviceId:String(X.deviceId||""),frameSeq:Number(X.frameSeq||0),streamId:String(X.streamId||""),mimeType:String(X.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(X.sampleRate||48e3),channels:Number(X.channels||2),capturedAt:String(X.capturedAt||""),receivedAt:String(X.receivedAt||""),byteLength:Number(X.byteLength||be.byteLength),payload:be};if(!he.deviceId||T)return;if(performance.now()-V>qy){Y();return}if(A.pendingDecodes>=nk){Y();return}A.pendingDecodes+=1;try{const J=Z1(he.mimeType)?sk(M,he,be):await M.decodeAudioData(be.slice(0));if(A.localProcessingAgeMs=Math.max(0,performance.now()-V),T)return;if(A.localProcessingAgeMs>qy){Y();return}if(he.frameSeq>0&&he.frameSeq<=A.lastFrameSeq){Y();return}if(A.activeStreamId&&he.streamId!==A.activeStreamId&&he.frameSeq<=A.lastFrameSeq){Y();return}he.streamId&&he.streamId!==A.activeStreamId&&(A.activeStreamId=he.streamId,A.lastFrameSeq=0,_());const Ce=M.currentTime;Math.max(0,c.current-Ce)>ek&&(_(),A.resyncs+=1);const He=M.createBufferSource();He.buffer=J,He.connect(M.destination),N.add(He),He.onended=()=>{N.delete(He),He.onended=null};const ee=Math.max(M.currentTime+tk,c.current);He.start(ee),c.current=ee+J.duration,A.browserAgeMs=Gy(he.receivedAt),A.captureAgeMs=Gy(he.capturedAt),A.lastAcceptedAt=performance.now(),A.framesReceived+=1,A.lastFrameSeq=he.frameSeq,I=0,B=0,g(he),te();const Ue=String(M.state)==="running";Ue&&w(""),m(Ue?"playing":"suspended")}finally{A.pendingDecodes=Math.max(0,A.pendingDecodes-1)}}catch(H){T||(m("error"),w(H instanceof Error?H.message:String(H)))}})()}),k.addEventListener("error",()=>{T||(m("error"),w("Remote audio WebSocket error."))}),k.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(F),M.removeEventListener("statechange",ve),document.removeEventListener("visibilitychange",fe),window.removeEventListener("pageshow",Q),window.removeEventListener("pointerdown",Q),window.removeEventListener("keydown",Q),_(!1),k.close(),M.close().catch(()=>{}),l.current===M&&(l.current=null)}},[n,a,s]),{state:u,lastFrame:h,stats:y,error:b}}const lk=3;function Vy(n,a,s){const l=Math.max(1,Number(s)||1),c=Math.max(0,Math.min(l,Number(n)-Number(a))),u=Math.min(l/2,lk);return c<=u?0:c>=l-u?1:c/l}function ok(n,a,s){return{normalizedX:Vy(n,s.left,s.width),normalizedY:Vy(a,s.top,s.height)}}const Hf=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),ck=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),Wy=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),fp=64;function Yf(n,a=80){return String(n||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,a)}function mp(n){const a=Yf(n);return Object.prototype.hasOwnProperty.call(Wy,a)?Wy[a]:a}function uk(n={}){const a=Yf(n.key),s=Number.isFinite(Number(n.location))?Math.max(0,Math.min(3,Math.trunc(Number(n.location)))):0,l=s===2?"Right":"Left";return a==="Shift"?`Shift${l}`:a==="Control"?`Control${l}`:a==="Alt"||a==="AltGraph"?`Alt${l}`:a==="Meta"||a==="OS"?`Meta${l}`:a?`Key:${s}:${a}`.slice(0,80):""}function hp(n={}){return mp(n.code)||uk(n)}function Af(n){for(const[a,s]of Object.entries(Hf))if(s.includes(n))return a;return""}function Dl(n,a){return Hf[a].some(s=>n.has(s))}function Yy(n,a,s={}){for(const l of Object.keys(Hf)){const c=s[l]===!0,u=Hf[l];if(c){!Dl(n,l)&&n.size<fp&&n.add(ck[l]);continue}for(const m of u)a.has(m)||n.delete(m)}}function dk(n,a){if(n.length!==a.size)return!1;let s=0;for(const l of a){if(n[s]!==l)return!1;s+=1}return!0}function Ky(n){for(const a of[...n])Af(a)||n.delete(a)}function pp(n){return{shiftKey:Dl(n,"shiftKey"),ctrlKey:Dl(n,"ctrlKey"),altKey:Dl(n,"altKey"),metaKey:Dl(n,"metaKey")}}function fk(n={},a={}){return{shiftKey:n.shiftKey===!0||a.shiftKey===!0,ctrlKey:n.ctrlKey===!0||a.ctrlKey===!0,altKey:n.altKey===!0||a.altKey===!0,metaKey:n.metaKey===!0||a.metaKey===!0}}function mk(n,a,s){const l=hp(n),c=Yf(n.key),u=Number(n.keyCode??n.which),m=Number(n.location);return{type:a,key:c,code:l,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(m)?Math.max(0,Math.min(255,Math.trunc(m))):0,text:c.length===1?c:"",repeat:a==="keydown"&&n.repeat===!0,pressedCodes:[...s],...pp(s)}}function hk(){const n=new Set,a=new Set,s=()=>({pressedCodes:[...n]});return{event(l={},c=""){if(c!=="keydown"&&c!=="keyup")return null;const u=hp(l);if(!u)return null;const m=Af(u),h=n.has(u),g=[...n];return m?(c==="keydown"?n.size<fp&&n.add(u):a.has(u)||n.delete(u),Yy(n,a,l)):(Yy(n,a,l),c==="keydown"?n.size<fp&&n.add(u):n.delete(u)),c==="keyup"&&m==="metaKey"&&!Dl(n,"metaKey")&&Ky(n),c==="keydown"&&h&&l.repeat!==!0&&dk(g,n)?null:mk(l,c,n)},modifier(l,c){const u=mp(l),m=Af(u);if(!m)return null;const h=a.has(u);return c===h?null:(c?(a.add(u),n.add(u)):(a.delete(u),n.delete(u),m==="metaKey"&&!Dl(n,"metaKey")&&Ky(n)),{type:c?"keydown":"keyup",key:m==="metaKey"?"Meta":m==="ctrlKey"?"Control":m==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...s(),...pp(n)})},reset(l="keyboard-owner-reset",c=!1){const u=n.size>0;return n.clear(),a.clear(),!u&&!c?null:{type:"keyboard.reset",reason:Yf(l,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(l={}){const c=typeof l=="string"?mp(l):hp(l);if(n.has(c))return!0;const u=Af(c);return!!u&&Dl(n,u)},snapshot(){return{...s(),latchedCodes:[...a],...pp(n)}}}}const Zx=64,pk=2;function Jx(n){const a=Math.floor(Number(n));return Number.isFinite(a)?Math.max(1,Math.min(Zx,a)):1}function Lp(n){const a=Math.floor(Number(n));return Number.isFinite(a)?Math.max(0,Math.min(Zx-1,a)):0}function ew(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"||a==="linux"||a.startsWith("linux ")}function gk(n,a,s){const l=String(a||"").trim();if(!l)return n||null;const c=String(s||"").trim();return n&&n.fingerprint===l&&(c?n.sampleId===c:n.sampleId==="")?n:{fingerprint:l,sampleId:c,consecutiveSamples:n?.fingerprint===l?n.consecutiveSamples+1:1}}function tw({platform:n,topologyFingerprint:a,consecutiveTopologySamples:s}){return ew(n)?!!String(a||"").trim()&&Number(s)>=pk:!0}function vk({requestedIndex:n,monitorCount:a,platform:s,topologyFingerprint:l,consecutiveTopologySamples:c}){const u=Lp(n),m=Jx(a);return u<m||!tw({platform:s,topologyFingerprint:l,consecutiveTopologySamples:c})?u:m-1}function yk(n,a,s){const l=Lp(n),c=Jx(a);return l<c||ew(s)?l:c-1}function Tc(n){const a=Number(n);return Number.isSafeInteger(a)&&a>0?a:0}function ta(n){return String(n||"").trim()}function of(n,a,s={}){return{deviceId:ta(n),transitionGeneration:Tc(a),sessionId:ta(s.sessionId),streamId:ta(s.streamId),commandId:ta(s.commandId),captureGeneration:Tc(s.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(s.monitorIndex)||0))}}function vr(n,a){return!!n&&!!a&&ta(n.deviceId)===ta(a.deviceId)&&Tc(n.transitionGeneration)===Tc(a.transitionGeneration)}function Qy(n,a){const s=Promise.resolve(n).catch(()=>{}).then(a);return{result:s,tail:s.then(()=>{},()=>{})}}function cf(n,a,s){const l=ta(n);return!l||!a||ta(a.deviceId)!==l?!1:!s||ta(s.deviceId)!==l}function Xy(n,a){if(!n||!a)return!1;const s=Tc(a.captureGeneration),l=ta(a.commandId),c=ta(a.sessionId),u=ta(a.streamId),m=Number(n.monitorIndex);return!s||!l||!c||!u||!Number.isInteger(m)||m<0?!1:ta(n.deviceId)===ta(a.deviceId)&&ta(n.sessionId)===c&&ta(n.streamId)===u&&ta(n.commandId)===l&&Tc(n.captureGeneration)===s&&ta(n.streamPurpose).toLowerCase()==="control"&&m===a.monitorIndex}const br=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,directFullFpsDeviceLimit:6,directMinAdaptiveFps:8,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,maxDirectFramesPerSecond:180,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function bk(n,a){const s=Math.max(0,Math.floor(Number(a)||0));return n===!0&&s>0}function Lu({mode4Enabled:n,directMode4WallEnabled:a,isMac:s}){return"direct"}function xk({mode4Enabled:n,directMode4WallEnabled:a,adaptiveFps:s,directDeviceCount:l,adaptive:c=!0}){const u=Math.max(1,Math.floor(Number(s)||1));if(!c)return u;const m=Math.max(1,Math.floor(Number(l)||1));return m<=br.directFullFpsDeviceLimit?u:Math.max(br.directMinAdaptiveFps,Math.min(u,Math.floor(br.maxDirectFramesPerSecond/m)))}function wk({deviceCount:n,targetFps:a,adaptive:s=!0}){const l=Math.max(1,Math.floor(Number(n)||1)),c=Math.max(1,Math.min(br.scalableAtlasMaxInputFps,Math.floor(Number(a)||br.scalableAtlasMaxInputFps)));if(!s)return c;const u=Math.max(br.scalableAtlasMinInputFps,Math.min(br.scalableAtlasMaxInputFps,Math.floor(br.scalableAtlasAggregateInputFps/l)));return Math.min(c,u)}function Sk(n,a){return{acceleration:br.directDecodeAcceleration,latencyMode:br.directLatencyMode}}const bo={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},Ck=[{id:"connection",label:"Connection",icon:qf},{id:"remote-access",label:"Remote Access",icon:Yn},{id:"capture-audio",label:"Capture & Audio",icon:Zh},{id:"agent",label:"Agent",icon:Il}];function Nf(n,a){return n?.settings?.[a]||bo.settings[a]||{}}function Zy(n,a){return{...n,settings:{...n.settings,[a.section]:{...Nf(n,a.section),[a.key]:a.value}}}}function Rh(n){return{revision:Number(n.revision||0),updatedAt:n.updatedAt,settings:n.settings}}function vc({icon:n,title:a,description:s,children:l,recommended:c=!1}){return i.jsxs("div",{className:"product-setting-row",children:[i.jsx("div",{className:"product-setting-control",children:l}),n&&i.jsx("span",{className:"product-setting-icon",children:i.jsx(n,{size:17})}),i.jsxs("div",{className:"product-setting-copy",children:[i.jsx("strong",{children:a}),c&&i.jsx("em",{children:"Recommended"}),i.jsx("small",{children:s})]})]})}function uf({checked:n,onChange:a,label:s}){return i.jsxs("label",{className:"product-switch",children:[i.jsx("input",{"aria-label":s,type:"checkbox",checked:n,onChange:l=>a(l.target.checked)}),i.jsx("span",{})]})}function Jy({value:n,onChange:a,options:s,label:l}){return i.jsx("select",{"aria-label":l,value:String(n),onChange:c=>a(c.target.value),children:s.map(([c,u])=>i.jsx("option",{value:c,children:u},c))})}function kk({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:s="",sessionAccessToken:l="",initialTab:c="connection",pin:u,agent:m,captureGallery:h}){const[g,y]=d.useState(c),[x,b]=d.useState(null),[w,j]=d.useState("loading"),[M,k]=d.useState(""),[N,A]=d.useState("idle"),[T,L]=d.useState(""),O=d.useRef(null),I=d.useRef(null),B=d.useRef([]),_=d.useRef(Promise.resolve()),G=d.useRef(0),te=d.useRef(0);d.useEffect(()=>{const oe=++te.current;let X=!0;return B.current=[],I.current=null,O.current=null,_.current=Promise.resolve(),j("loading"),Ye("/api/settings",void 0,n).then(be=>{if(!X||oe!==te.current)return;const me=Rh(be);I.current=me,O.current=me,b(me),j("saved")}).catch(be=>{!X||oe!==te.current||(k(be instanceof Error?be.message:String(be)),I.current=bo,O.current=bo,b(bo),j("failed"))}),()=>{X=!1}},[n]);const W=async(oe,X,be)=>{const me={id:++G.current,section:oe,key:X,value:be},he=te.current;B.current.push(me);const J=Zy(O.current||I.current||bo,me);O.current=J,b(J),j("saving"),k(""),_.current=_.current.then(async()=>{if(he!==te.current)return;let Ce=null,Te=null;for(let Ue=0;Ue<2&&!Ce;Ue+=1){const ft=I.current||bo;try{const ne=await Ye("/api/settings",{method:"PATCH",body:JSON.stringify({revision:ft.revision,[me.section]:{[me.key]:me.value}})},n);Ce=Rh(ne)}catch(ne){if(Te=ne,Ue!==0||!String(ne instanceof Error?ne.message:ne).startsWith("409 "))break;try{const xe=await Ye("/api/settings",void 0,n);if(he!==te.current)return;I.current=Rh(xe)}catch(xe){Te=xe;break}}}if(he!==te.current)return;B.current=B.current.filter(Ue=>Ue.id!==me.id),Ce&&(I.current=Ce);const He=I.current||bo,ee=B.current.reduce(Zy,He);O.current=ee,b(ee),Ce?(k(""),j(B.current.length>0?"saving":"saved")):(j(B.current.length>0?"saving":"failed"),k(Te instanceof Error?Te.message:String(Te||"Settings could not be saved.")))}),await _.current},Y=(oe,X)=>be=>{W(oe,X,be)},F=async()=>{if(a!=="hub"||!s||!l){A("failed"),L("Sign in to this Hub before changing its runtime role.");return}A("changing"),L("");try{const oe=await Ye("/api/runtime/status",void 0,n);await Ye("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),A("accepted"),await Ax({baseUrl:n,targetRole:"client",previousRuntimePid:Number(oe.runtimePid||0),allowedStates:["running","waiting-auth"]}),qC(5179)}catch(oe){A("failed"),L(oe instanceof Error?oe.message:String(oe))}},ve=Nf(x,"security"),fe=Nf(x,"control"),Q=Nf(x,"filesAudio"),z=`settings-panel-${g}`,re=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,i.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Runtime role"}),i.jsx("h3",{children:"Use this computer as a Client"})]}),i.jsx(gx,{size:20})]}),i.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),N==="accepted"?i.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):T?i.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:T}):null,i.jsx("button",{className:"settings-reset",onClick:()=>{F()},disabled:N==="changing"||a!=="hub",type:"button",children:N==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),V=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Remote access"}),i.jsx("h3",{children:"Who may connect?"})]}),i.jsx(Di,{size:20})]}),i.jsx(vc,{icon:Yn,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:i.jsx(Jy,{value:String(ve.accessMode),onChange:Y("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Session permissions"}),i.jsx("h3",{children:"What may remote users do?"})]}),i.jsx(Ea,{size:20})]}),i.jsx(vc,{icon:Ea,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:i.jsx(uf,{checked:!!fe.allowKeyboardMouse,onChange:Y("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),i.jsx(vc,{icon:Zh,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:i.jsx(uf,{checked:!!Q.allowFileTransfer,onChange:Y("filesAudio","allowFileTransfer"),label:"File transfer"})}),i.jsx(vc,{icon:jo,title:"Remote audio",description:"Allow sound capture from connected computers.",children:i.jsx(uf,{checked:!!Q.allowRemoteAudio,onChange:Y("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),H=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Capture"}),i.jsx("h3",{children:"Recording defaults"})]}),i.jsx(Zh,{size:20})]}),i.jsx(vc,{icon:jo,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:i.jsx(uf,{checked:!!Q.rollingBufferEnabled,onChange:Y("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),i.jsx(vc,{icon:jo,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:i.jsx(Jy,{value:Number(Q.timelapseIntervalSeconds),onChange:oe=>Y("filesAudio","timelapseIntervalSeconds")(Number(oe)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),le=g==="connection"?re:g==="remote-access"?V:g==="capture-audio"?H:m;return i.jsxs("section",{className:"settings-page",children:[i.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:Ck.map(({id:oe,label:X,icon:be})=>i.jsxs("button",{className:g===oe?"active":"",id:`settings-tab-${oe}`,role:"tab","aria-selected":g===oe,"aria-controls":`settings-panel-${oe}`,tabIndex:g===oe?0:-1,onClick:()=>y(oe),type:"button",children:[i.jsx(be,{size:16}),X]},oe))}),w==="saving"&&i.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),M&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:M}),i.jsx("section",{className:"settings-page-panel",id:z,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:le})]})}function jk({children:n}){return i.jsx("div",{className:"settings-tab-content",children:n})}const eb={enabled:!1};function tb(n){return{enabled:n?.enabled===!0}}async function Mk(n,a,s){let l=null;for(let c=0;c<2;c+=1){const u=await Ye("/api/settings",{signal:s},a);if(u.settings.agent?.enabled===n)return;try{await Ye("/api/settings",{method:"PATCH",signal:s,body:JSON.stringify({revision:u.revision,agent:{enabled:n}})},a);return}catch(m){if(l=m,c!==0||!String(m instanceof Error?m.message:m).startsWith("409 "))throw m}}throw l}function Ak({hubUrl:n}){const[a,s]=d.useState(eb),[l,c]=d.useState(null),[u,m]=d.useState(""),[h,g]=d.useState(""),[y,x]=d.useState(""),b=d.useRef(0),w=d.useRef(null);d.useEffect(()=>{let I=!0;w.current?.abort();const B=new AbortController;w.current=B;const _=++b.current;return c(null),s(eb),m(""),x(""),g(""),Ye("/api/settings/agent",{signal:B.signal},n).then(G=>{!I||B.signal.aborted||_!==b.current||(c(G.settings),s(tb(G.settings)))}).catch(G=>{I&&!B.signal.aborted&&_===b.current&&x(G instanceof Error?G.message:String(G))}),()=>{I=!1,B.abort(),w.current===B&&(w.current=null)}},[n]);const j=(I,B)=>s(_=>({..._,[I]:B})),M=I=>{c(I),s(tb(I))},k=()=>({generation:b.current,controller:w.current}),N=I=>I.generation===b.current&&I.controller!==null&&I.controller===w.current&&!I.controller.signal.aborted,A=async()=>{if(!l){x("Agent settings are not available yet.");return}const I=k();if(N(I)){m("save"),x(""),g("");try{if(await Mk(a.enabled,n,I.controller.signal),!N(I))return;const B=await Ye("/api/settings/agent",{signal:I.controller.signal},n);if(!N(I))return;M(B.settings),g("Codex Agent settings saved.")}catch(B){N(I)&&x(B instanceof Error?B.message:String(B))}finally{N(I)&&m("")}}},T=async()=>{const I=k();if(N(I)){m("test"),x(""),g("");try{const B=await Ye("/api/settings/agent/test",{method:"POST",signal:I.controller.signal,body:JSON.stringify({})},n);if(!N(I))return;const _=await Ye("/api/settings/agent",{signal:I.controller.signal},n);if(!N(I))return;M(_.settings);const G=Number.isFinite(B.connection?.latencyMs)?Math.max(0,Math.round(B.connection.latencyMs)):null;g(`Codex Agent connection verified${G!==null?` in ${G} ms.`:"."}`)}catch(B){N(I)&&x(B instanceof Error?B.message:String(B))}finally{N(I)&&m("")}}},L=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",O=l!==null;return i.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[i.jsx("section",{className:"settings-section-card agent-enable-card",children:i.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[i.jsx("input",{type:"checkbox",checked:a.enabled,onChange:I=>j("enabled",I.target.checked),disabled:!O||u!==""}),i.jsx("span",{children:"Enable Codex Agent"})]})}),y&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),h&&i.jsx("div",{className:"agent-settings-alert success",role:"status",children:h}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Runtime"}),i.jsx("h3",{children:"Codex SDK / CLI"})]}),i.jsx(Yn,{size:20})]}),i.jsxs("div",{className:"agent-connection-row",children:[i.jsx("span",{className:`agent-connection-dot ${L?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),i.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),i.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:u!=="",type:"button",children:[i.jsx(M0,{size:15})," ",u==="test"?"Testing":"Test connection"]})]}),i.jsxs("p",{className:"settings-help",children:[i.jsx(A0,{size:12})," The Hub uses the installed Codex SDK / CLI to plan and run approved computer commands. LiveDesk controls computers through Agent tools; it does not configure AI models or inference environments."]})]}),i.jsx("div",{className:"settings-action-row agent-settings-actions",children:i.jsxs("button",{className:"text-button primary",onClick:()=>{A()},disabled:!O||u!=="",type:"button",children:[i.jsx(N0,{size:15})," ",u==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function Ps(n){const[a,s]=d.useState(n),l=d.useRef(n);return d.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,s(n)}},[n]),[a,s]}function _p(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function Rc(n,a="data-id"){let s=n;for(!s.tagName&&n.target&&(s=n.target);s;){if(s.getAttribute&&s.getAttribute(a))return s;s=s.parentNode}return null}function Nk(n,a="data-id"){const s=Rc(n,a);return s?s.getAttribute(a):null}function Xu(n,a="data-id"){const s=Rc(n,a);return s?Kf(s,a):null}function Kf(n,a="data-id"){const s=n.getAttribute(a);return s?Tk(s):null}function na(n){return typeof n=="string"?":"+n:n}function Tk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Rk(){return{detect:()=>!0,addEvent:function(n,a,s){return n.addEventListener(a,s),()=>n.removeEventListener(a,s)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var ir=Rk();function Ip(n){Object.assign(ir,n)}function nb(n,a,s){function l(c){const u=Rc(c);if(!u)return;const m=Kf(u);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[s]&&a[s](m,c)}ir.addEvent(n,s,l)}function Ec(n,a){nb(n,a,"click"),a.dblclick&&nb(n,a.dblclick,"dblclick")}function Ek(n,a){for(let s=n.length-1;s>=0;s--)if(n[s]===a){n.splice(s,1);break}}function Dk(n,a,s){for(let l=0;l<Li.length;l++){if(l===s)continue;const c=Li[l],u=c.props.parent?.();if(u&&n.contains(u)&&c.node.contains(a))return!0}return!1}var nw=new Date,Pf=!1,df=[],Li=[],ab=n=>{const a=n.target;if(Pf||!a.isConnected){Pf=!1;return}for(let s=Li.length-1;s>=0;s--){const{node:l,date:c,props:u}=Li[s];if(!(c>nw)&&!l.contains(a)&&l!==a&&(Dk(l,a,s)||(u.callback&&u.callback(n),u.modal||n.defaultPrevented)))break}},Lk=n=>{nw=new Date,Pf=!0;for(let a=Li.length-1;a>=0;a--){const{node:s}=Li[a];if(!s.contains(n.target)&&s!==n.target){Pf=!1;break}}};function Fs(n,a){df.length||(df=[ir.addGlobalEvent("click",ab,n),ir.addGlobalEvent("contextmenu",ab,n),ir.addGlobalEvent("mousedown",Lk,n)]),typeof a!="object"&&(a={callback:a});const s={node:n,date:new Date,props:a};return Li.push(s),{destroy(){Ek(Li,s),Li.length||(df.forEach(l=>l()),df=[])}}}var ff=n=>n.indexOf("bottom")!==-1,mf=n=>n.indexOf("left")!==-1,hf=n=>n.indexOf("right")!==-1,Eh=n=>n.indexOf("top")!==-1,rb=n=>n.indexOf("fit")!==-1,_u=n=>n.indexOf("overlap")!==-1,_k=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),Ik=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function zk(n,a){let s=0;const l=ir.getTopNode(n);for(;n&&n!==l;){const c=getComputedStyle(n).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(s=parseInt(getComputedStyle(n).zIndex)||0),n=n.parentNode,n===a)break}return s}var On,ja,Iu,ga;function aw(n,a,s="bottom",l=0,c=0){if(!n)return null;On=l,ja=c,Iu="auto";let u=0,m=0,h=s;const g=rw(n),y=_u(s)?ir.getTopNode(n):g;if(!g)return null;const x=g.getBoundingClientRect(),b=n.getBoundingClientRect(),w=y.getBoundingClientRect(),j=window.getComputedStyle(y),M={left:0,top:0,bottom:0,right:0};for(const O in M){const I=`border-${O}-width`;M[O]=parseFloat(j.getPropertyValue(I))}if(a){const O=zk(a,g);u=Math.max(O+1,20)}if(a){if(ga=a.getBoundingClientRect(),rb(s)&&(Iu=ga.width+"px"),s!=="point")if(_k(s))rb(s)?On=0:(On=w.width/2,m=1),ja=(w.height-b.height)/2;else{const O=_u(s)?0:1;On=hf(s)?ga.right+O:ga.left-O,ja=ff(s)?ga.bottom+1:ga.top;const I=Ik(s);I&&(hf(s)||mf(s)?I==="center"?ja-=(b.height-ga.height)/2:I==="end"&&(ja-=b.height-ga.height):(ff(s)||Eh(s))&&(I==="center"?On-=(b.width-ga.width)/2:I==="end"&&(On-=b.width-ga.width),_u(s)||(On+=1)))}}else ga={left:l,right:l,top:c,bottom:c};const k=(mf(s)||hf(s))&&(ff(s)||Eh(s));mf(s)&&(m=2);const N=On-b.width-w.left;a&&mf(s)&&!k&&N<0&&(On=ga.right,m=0,h=h.replace("left","right"));const A=On+b.width*(1-m/2)-w.right;if(A>0)if(!hf(s))On=w.right-M.right-b.width;else{const O=ga.left-w.x-b.width;a&&!k&&O>=0?(On=ga.left-b.width,h=h.replace("right","left")):On-=A+M.right}m&&(On=Math.round(On-b.width*m/2));const T=N<0||A>0||!k;Eh(s)&&(ja=ga.top-b.height,a&&ja<w.y&&T&&(ja=ga.bottom,h=h.replace("top","bottom")));const L=ja+b.height-w.bottom;return L>0&&(a&&ff(s)&&T?(ja-=b.height+ga.height+1,h=h.replace("bottom","top")):ja-=L+M.bottom),On-=x.left+M.left,ja-=x.top+M.top,On=(_u(s)?On:Math.max(On,0))+y.scrollLeft,ja=(_u(s)?ja:Math.max(ja,0))+y.scrollTop,Iu=Iu||"auto",{at:h,x:On,y:ja,z:u,width:Iu}}function rw(n){const a=ir.getTopNode(n);for(n&&(n=n.parentElement);n;){const s=getComputedStyle(n).position;if(n===a||s==="relative"||s==="absolute"||s==="fixed")return n;n=n.parentNode}return null}function Ok(n){const a=[];let s=n;const l=ir.getTopNode(n);for(;s&&s!==l&&!s.getAttribute("data-wx-portal-root");)getComputedStyle(s).position==="absolute"&&a.push(s),s=s.parentNode;return a}var sb=new Date().valueOf();function zp(){return sb+=1,sb}function Aa(n){return n<10?"0"+n:n.toString()}function Hk(n){const a=Aa(n);return a.length==2?"0"+a:a}function sw(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function Dh(n){const a=(n.getDay()+6)%7,s=new Date(n.valueOf());s.setDate(n.getDate()+(3-a)),s.setHours(0,0,0,0);const l=new Date(s.getFullYear(),0,1),c=Math.round((s.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var ib=["",""];function Pk(n,a,s){switch(n){case"%d":return Aa(a.getDate());case"%m":return Aa(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return Aa(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return s.dayShort[a.getDay()];case"%l":return s.dayFull[a.getDay()];case"%M":return s.monthShort[a.getMonth()];case"%F":return s.monthFull[a.getMonth()];case"%h":return Aa((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return Aa(a.getHours());case"%i":return Aa(a.getMinutes());case"%a":return((a.getHours()>11?s.pm:s.am)||ib)[0];case"%A":return((a.getHours()>11?s.pm:s.am)||ib)[1];case"%s":return Aa(a.getSeconds());case"%S":return Hk(a.getMilliseconds());case"%W":return Aa(Dh(a));case"%w":{const l=s.weekStart??1;if(l===1)return Aa(Dh(a));const c=(a.getDay()-l+7)%7,u=(1-l+7)%7,m=new Date(a.valueOf());return m.setDate(a.getDate()+(u-c)),Aa(Dh(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+Aa(a.getMonth()+1),l+="-"+Aa(a.getDate()),l+="T",l+=Aa(a.getHours()),l+=":"+Aa(a.getMinutes()),l+=":"+Aa(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var Fk=/%[a-zA-Z]/g;function kc(n,a){return typeof n=="function"?n:function(s){return s?(s.getMonth||(s=new Date(s)),n.replace(Fk,l=>Pk(l,s,a))):""}}function lb(n){return n&&typeof n=="object"&&!Array.isArray(n)}function gp(n,a){for(const s in a){const l=a[s];lb(n[s])&&lb(l)?n[s]=gp({...n[s]},a[s]):n[s]=a[s]}return n}function Ju(n){return{getGroup(a){const s=n[a];return l=>s&&s[l]||l},getRaw(){return n},extend(a,s){if(!a)return this;let l;return s?l=gp({...a},n):l=gp({...n},a),Ju(l)}}}var $k=kx();const Bk="en-US",Uk={monthFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hours:"Hours",minutes:"Minutes",done:"Done",clear:"Clear",today:"Today",am:["am","AM"],pm:["pm","PM"],weekStart:0,clockFormat:24},qk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Gk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},iw={core:qk,calendar:Uk,formats:Gk,lang:Bk},Op=d.createContext(""),lw=d.createContext({}),ds=d.createContext(null),ow=d.createContext(null),ra=Object.freeze(Object.defineProperty({__proto__:null,fieldId:ow,helpers:lw,i18n:ds,theme:Op},Symbol.toStringTag,{value:"Module"}));function cw(n){const a=d.useContext(ow),[s]=d.useState(()=>n||a||zp());return s}function Gu({type:n="",css:a="",icon:s="",disabled:l=!1,title:c="",tooltip:u,text:m="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=n?n.split(" ").filter(w=>w!=="").map(w=>"wx-"+w).join(" "):"";return a+(a?" ":"")+b},[n,a]),x=b=>{g&&g(b)};return i.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${y} ${s&&!h?"wx-icon":""}`,disabled:l,onClick:x,"data-tooltip-text":u,children:[s&&i.jsx("i",{className:"wx-2ZWgb4 "+s}),h||m||" "]})}function Vk({id:n,label:a="",inputValue:s="",value:l=!1,onChange:c,disabled:u=!1,css:m=""}){const h=cw(n),[g,y]=Ps(l),x=({target:b})=>{const w=b.checked;y(w),c&&c({value:w,inputValue:s})};return i.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[i.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:s,onChange:x}),i.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[i.jsx("span",{className:"wx-2IvefP wx-before"}),a&&i.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function Hp({theme:n="",target:a,children:s}){const l=d.useRef(null),c=d.useRef(null),[u,m]=d.useState(null);l.current||(l.current=document.createElement("div"));const h=d.useContext(Op);return d.useEffect(()=>{m(a||Wk(c.current)||ir.getTopNode(c.current))},[c.current]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:c,style:{display:"none"}}),c.current&&u?$k.createPortal(i.jsx("div",{className:`wx-3ZWsT0 wx-${n||h}-theme`,children:s}),u):null]})}function Wk(n){const a=ir.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function Yk({left:n=0,top:a=0,at:s="bottom",parent:l=null,width:c="auto",css:u="",onCancel:m,children:h,trackScroll:g=!1}){const[y,x]=d.useState(0),[b,w]=d.useState(0),[j,M]=d.useState("auto"),[k,N]=d.useState(!1),A=d.useRef(null),T=d.useRef(null),L=d.useRef(m);d.useEffect(()=>{L.current=m},[m]);function O(B){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(_,G)=>(G=G*l.offsetWidth/100+"px",c.replace(_,G))):c&&c!=="auto"?c:B}const I=d.useCallback(()=>{if(!A.current)return;const B=aw(A.current,l,s,n,a);B&&(x(B.x),w(B.y),M(O(B.width)))},[A,l,s,n,a,c]);return d.useLayoutEffect(()=>{const B=G=>{L.current&&G.target!==T.current&&A.current&&!A.current.contains(G.target)&&L.current(G)};let _;return requestAnimationFrame(()=>{I(),N(!0),g&&A.current&&(T.current=rw(A.current),T.current&&T.current.addEventListener("scroll",B,!0)),l&&(_=new ResizeObserver(I),_.observe(l))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",B,!0),_?.disconnect()}},[]),d.useLayoutEffect(()=>{I()},[l,s,n,a]),d.useEffect(()=>{const B=_=>{L.current&&L.current(_)};if(A.current)return Fs(A.current,{callback:B,parent:()=>l}).destroy},[l]),i.jsx("div",{ref:A,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:k?"visible":"hidden",top:b+"px",left:y+"px",width:j},children:h})}function Kk({position:n="bottom",align:a="start",autoFit:s=!0,onCancel:l=null,width:c="100%",css:u="",children:m}){const h=d.useRef(null),[g,y]=d.useState(n),[x,b]=d.useState(a),w=d.useRef(l);return d.useEffect(()=>{w.current=l},[l]),d.useEffect(()=>{if(s){const j=h.current;if(j){const M=j.getBoundingClientRect(),k=document.body.getBoundingClientRect();M.right>=k.right&&b("end"),M.bottom>=k.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const j=M=>{w.current&&w.current(M)};return Fs(h.current,j).destroy}},[]),i.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${x}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function Pp({position:n="bottom",align:a="start",autoFit:s=!0,inline:l=!1,onCancel:c,width:u="100%",children:m,...h}){const[g,y]=d.useState(void 0),x=d.useRef(null),b=d.useMemo(()=>`${n}-${a}`,[n,a]);return d.useLayoutEffect(()=>{x.current&&y(x.current.parentNode)},[]),i.jsxs(i.Fragment,{children:[g&&(l?i.jsx(Kk,{onCancel:c,position:n,align:a,autoFit:s,width:u,...h,children:m}):i.jsx(Hp,{children:i.jsx(Yk,{parent:g,at:b,onCancel:c,width:u,...h,children:m})})),i.jsx("span",{ref:x,className:"wx-portal-node wx-32GZ52"})]})}function Qf(){return Ju(iw)}function Qk(){let n=null,a=!1,s=!1,l,c,u,m;const h=(b,w,j,M,k)=>{l=b,c=w,u=j,m=M,s=k},g=b=>{n=b,a=n!==null,u(n)},y=(b,w)=>{if(!s&&b!==null&&l){const j=l.querySelectorAll(".wx-list > .wx-item")[b];j&&(j.scrollIntoView({block:"nearest"}),w&&w.preventDefault())}},x=(b,w)=>{const j=b===null?null:Math.max(0,Math.min(n+b,c.length-1));j!==n&&(g(j),l?y(j,w):requestAnimationFrame(()=>y(j,w)))};return{move:b=>{const w=Xu(b),j=c.findIndex(M=>M.id===w);j!==n&&g(j)},keydown:(b,w)=>{switch(b.code){case"Enter":a?m():g(0);break;case"Space":a||g(0);break;case"Escape":u(n=null);break;case"Tab":u(n=null);break;case"ArrowDown":x(a?1:w||0,b);break;case"ArrowUp":x(a?-1:w||0,b);break}},init:h,navigate:x}}const ob=10,Xk=d.memo(function({data:n,checkboxes:a,itemTemplate:s,value:l}){return i.jsxs(i.Fragment,{children:[a&&i.jsx(Vk,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),s?_p(s,{option:n}):n.label]})});function cb({visibleItems:n,visibleRange:a,navIndex:s,checkboxes:l,itemTemplate:c,value:u,measureRefCallback:m}){return n.map((h,g)=>{const y=a.start+g;return i.jsx("div",{ref:g===0?m:void 0,className:`wx-233fr7 wx-item ${y===s?"wx-focus":""}`,"data-id":h.id,children:i.jsx(Xk,{data:h,checkboxes:l,itemTemplate:c,value:u})},h.id)})}function Xf({items:n=[],children:a,onSelect:s,onReady:l,virtualized:c=!1,checkboxes:u,multiselect:m,value:h,...g}){const y=d.useRef(),x=d.useRef(!1),b=d.useRef(Qk()),[w,j]=d.useState(null),M=d.useRef(w),[k,N]=d.useState(0),[A,T]=d.useState(24),L=d.useRef(!1),O=(d.useContext(ds)||Qf()).getGroup("core"),I=d.useRef(n);d.useEffect(()=>{I.current=n},[n]);const B=d.useRef(h);d.useEffect(()=>{B.current=h},[h]);const _=d.useRef(0);d.useEffect(()=>{_.current=A},[A]);const G=d.useCallback(X=>{X&&X.stopPropagation();const be=I.current,me=B.current,he=M.current;let J;const Ce=be[he]?.id;m?me&&me.includes(Ce)?J=me.filter(Te=>Te!==Ce):J=[...me||[],Ce]:J=Ce,s&&s({id:J})},[m,s]),te=d.useRef(G);d.useEffect(()=>{te.current=G},[G]);const W=d.useCallback(X=>{if(y.current){let be=X*_.current-y.current.clientHeight+_.current;N(be),y.current.scrollTop=be}},[_.current]),Y=d.useCallback(X=>{y.current=X,c&&(X&&!x.current&&M.current!==null&&requestAnimationFrame(()=>{y.current&&(W(M.current),x.current=!0)}),X||(x.current=!1))},[W]),F=d.useCallback(X=>{if(!X||L.current)return;const be=X.getBoundingClientRect().height;be&&(T(be),_.current=be,L.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,n,X=>{j(X),M.current=X},X=>te.current(X),c)},[n,y.current,c]),d.useEffect(()=>{const X=(me,he)=>{b.current.navigate(me,he),W(M.current)},be=(me,he)=>{const J=M.current,Ce=I.current;if(J!==0&&J!==Ce.length-1&&(me.key==="ArrowDown"||me.key==="ArrowUp")&&me.preventDefault(),b.current.keydown(me,he),y.current){const Te=y.current.scrollTop<=M.current*_.current,He=y.current.scrollTop+y.current.clientHeight>=M.current*_.current+_.current;Te?He||W(M.current):(y.current.scrollTop=M.current*_.current,N(y.current.scrollTop))}};l&&l({navigate:c?X:b.current.navigate,keydown:c?be:b.current.keydown,move:b.current.move})},[]);const ve=d.useRef(0),fe=d.useRef(n);fe.current!==n&&(fe.current=n,ve.current+=1);const Q=d.useCallback(()=>{b.current.navigate(null)},[b]),z=d.useCallback(X=>{c&&N(X.target.scrollTop)},[c]),re=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/A),[A,k]),V=d.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const X=Math.floor(k/A),be=X+re;return{start:Math.max(0,X-ob),end:Math.min(n.length,be+ob)}},[c,n,k,A,re]),H=d.useMemo(()=>{if(!c)return n;const{start:X,end:be}=V;return n.slice(X,be).map(me=>({...me}))},[c,n,V]),le=V.start*A,oe=n.length*A;return d.useEffect(()=>{c&&N(0)},[n,c]),d.useEffect(()=>{w===null&&(x.current=!1)},[w]),w===null?null:i.jsx(Pp,{onCancel:Q,...g,children:i.jsx("div",{className:"wx-233fr7 wx-list",ref:Y,onClick:G,onMouseMove:b.current.move,onScroll:z,children:n.length?c?i.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${oe}px`},children:i.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${le}px)`},children:i.jsx(cb,{visibleRange:V,visibleItems:H,navIndex:w,measureRefCallback:F,checkboxes:u,itemTemplate:a,value:h})})}):i.jsx(cb,{visibleRange:V,visibleItems:H,navIndex:w,measureRefCallback:F,checkboxes:u,itemTemplate:a,value:h}):i.jsx("div",{className:"wx-233fr7 wx-no-data",children:O("No data")})})},ve.current)}function Fp({value:n="",id:a,readonly:s=!1,focus:l=!1,select:c=!1,type:u="text",placeholder:m="",disabled:h=!1,error:g=!1,title:y="",tooltip:x,css:b="",icon:w="",clear:j=!1,onChange:M}){const k=cw(a),[N,A]=Ps(n),T=d.useRef(null),L=d.useMemo(()=>w&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[w,b]),O=d.useMemo(()=>w&&b.indexOf("wx-icon-left")!==-1,[w,b]);d.useEffect(()=>{const te=setTimeout(()=>{l&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(te)},[l,c]);const I=d.useCallback(te=>{const W=te.target.value;A(W),M&&M({value:W,input:!0})},[M]),B=d.useCallback(te=>M&&M({value:te.target.value}),[M]);function _(te){te.stopPropagation(),A(""),M&&M({value:""})}let G=u;return u!=="password"&&u!=="number"&&(G="text"),d.useEffect(()=>{const te=B,W=T.current;return W.addEventListener("change",te),()=>{W&&W.removeEventListener("change",te)}},[B]),i.jsxs("div",{className:`wx-hQ64J4 wx-text ${L} ${g?"wx-error":""} ${h?"wx-disabled":""} ${j?"wx-clear":""}`,"data-tooltip-text":x,children:[i.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:k,readOnly:s,disabled:h,placeholder:m,type:G,title:y,value:N,onInput:I}),j&&!h&&N?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:_}),O&&i.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`})]}):w?i.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`}):null]})}function Zk({date:n,type:a,part:s,onShift:l}){const{calendar:c,formats:u}=d.useContext(ds).getRaw(),m=n.getFullYear(),h=d.useMemo(()=>{switch(a){case"month":return kc(u.monthYearFormat,c)(n);case"year":return kc(u.yearFormat,c)(n);case"duodecade":{const{start:y,end:x}=sw(m),b=kc(u.yearFormat,c);return`${b(new Date(y,0,1))} - ${b(new Date(x,11,31))}`}default:return""}},[n,a,m,c,u]);function g(){l&&l({diff:0,type:a})}return i.jsxs("div",{className:"wx-8HQVQV wx-header",children:[s!=="right"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"}),i.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),s!=="left"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function $p({onClick:n,children:a}){return i.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function Jk({value:n,current:a,part:s="",markers:l=null,css:c="",onCancel:u,onChange:m}){const h=(d.useContext(ds)||Qf()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),x=(I,B,_)=>new Date(I.getFullYear(),I.getMonth()+(B||0),I.getDate()+(_||0));let b=s!=="normal";function w(I){const B=I.getDay();return B===0||B===6}function j(){const I=x(a,0,1-a.getDate());return I.setDate(I.getDate()-(I.getDay()-(g-7))%7),I}function M(){const I=x(a,1,-a.getDate());return I.setDate(I.getDate()+(6-I.getDay()+g)%7),I}const k=d.useRef(0);function N(I,B){B.timeStamp!==k.current&&(k.current=B.timeStamp,B.stopPropagation(),m&&m(new Date(I)),u&&u())}const A=d.useMemo(()=>s=="normal"?[n?x(n).valueOf():0]:n?[n.start?x(n.start).valueOf():0,n.end?x(n.end).valueOf():0]:[0,0],[s,n]),T=d.useMemo(()=>{const I=j(),B=M(),_=a.getMonth();let G=[];for(let te=I;te<=B;te.setDate(te.getDate()+1)){const W={day:te.getDate(),in:te.getMonth()===_,date:te.valueOf()};let Y="";if(Y+=W.in?"":" wx-inactive",Y+=A.indexOf(W.date)>-1?" wx-selected":"",b){const F=W.date==A[0],ve=W.date==A[1];F&&!ve?Y+=" wx-left":ve&&!F&&(Y+=" wx-right"),W.date>A[0]&&W.date<A[1]&&(Y+=" wx-inrange")}if(Y+=w(te)?" wx-weekend":"",l){const F=l(te);F&&(Y+=" "+F)}G.push({...W,css:Y})}return G},[a,A,b,l]),L=d.useRef(null);let O=d.useRef({});return O.current.click=N,d.useEffect(()=>{Ec(L.current,O.current)},[]),i.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[i.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(I=>i.jsx("div",{className:"wx-398RBS wx-weekday",children:I},I))}),i.jsx("div",{className:"wx-398RBS wx-days",ref:L,children:T.map(I=>i.jsx("div",{className:`wx-398RBS wx-day ${I.css} ${I.in?"":"wx-out"}`,"data-id":I.date,children:I.day},I.date))})]})}function ej({value:n,current:a,part:s,onCancel:l,onChange:c,onShift:u}){const m=d.useRef(new Date),[h,g]=Ps(n||m.current),[y,x]=Ps(a||m.current),b=d.useContext(ds).getRaw().calendar,w=b.monthShort||[],j=d.useMemo(()=>y.getMonth(),[y]),M=d.useCallback((A,T)=>{if(A!=null){T.stopPropagation();const L=new Date(y);L.setMonth(A),x(L),u&&u({current:L})}s==="normal"&&g(new Date(y)),l&&l()},[y,s,u,l]),k=d.useCallback(()=>{const A=new Date(uw(h,s)||y);A.setMonth(y.getMonth()),A.setFullYear(y.getFullYear()),c&&c(A)},[h,y,s,c]),N=d.useCallback(A=>{const T=A.target.closest("[data-id]");if(T){const L=parseInt(T.getAttribute("data-id"),10);M(L,A)}},[M]);return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-34U8T8 wx-months",onClick:N,children:w.map((A,T)=>i.jsx("div",{className:"wx-34U8T8 wx-month"+(j===T?" wx-current":""),"data-id":T,children:A},T))}),i.jsx("div",{className:"wx-34U8T8 wx-buttons",children:i.jsx($p,{onClick:k,children:b.done})})]})}const Lh="wx-1XEF33",tj=({value:n,current:a,onCancel:s,onChange:l,onShift:c,part:u})=>{const m=d.useContext(ds).getRaw().calendar,[h,g]=Ps(a),[y,x]=Ps(n),b=d.useMemo(()=>h.getFullYear(),[h]),w=d.useMemo(()=>{const{start:A,end:T}=sw(b),L=[];for(let O=A;O<=T;++O)L.push(O);return L},[b]),j={click:M};function M(A,T){if(A){T.stopPropagation();const L=new Date(h);L.setFullYear(A),g(L),c&&c({current:L})}u==="normal"&&x(new Date(h)),s&&s()}function k(){const A=new Date(uw(y,u)||h);A.setFullYear(h.getFullYear()),l&&l(A)}const N=d.useRef(null);return d.useEffect(()=>{N.current&&Ec(N.current,j)},[]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:Lh+" wx-years",ref:N,children:w.map((A,T)=>i.jsx("div",{className:Lh+` wx-year ${b==A?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":A,children:A},T))}),i.jsx("div",{className:Lh+" wx-buttons",children:i.jsx($p,{onClick:k,children:m.done})})]})},ub={month:{component:Jk,next:aj,prev:nj},year:{component:ej,next:sj,prev:rj},duodecade:{component:tj,next:lj,prev:ij}};function nj(n){return n=new Date(n),n.setMonth(n.getMonth()-1),n}function aj(n){return n=new Date(n),n.setMonth(n.getMonth()+1),n}function rj(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function sj(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function ij(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function lj(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function uw(n,a){let s;if(a==="normal")s=n;else{const{start:l,end:c}=n;a==="left"?s=l:a=="right"?s=c:s=l&&c}return s}const oj=["clear","today"];function cj(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function uj({value:n,current:a,onCurrentChange:s,part:l="normal",markers:c=null,buttons:u,css:m="",onShift:h,onChange:g}){const y=d.useContext(ds).getGroup("calendar"),[x,b]=d.useState("month"),w=Array.isArray(u)?u:u?oj:[],j=(T,L)=>{T.preventDefault(),g&&g({value:L})},M=()=>{x==="duodecade"?b("year"):x==="year"&&b("month")},k=T=>{const{diff:L,current:O}=T;if(L===0){x==="month"?b("year"):x==="year"&&b("duodecade");return}if(L){const I=ub[x];s(L>0?I.next(a):I.prev(a))}else O&&s(O);h&&h()},N=T=>{b("month"),g&&g({select:!0,value:T})},A=d.useMemo(()=>ub[x].component,[x]);return i.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:i.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[i.jsx(Zk,{date:a,part:l,type:x,onShift:k}),i.jsxs("div",{children:[i.jsx(A,{value:n,current:a,onCurrentChange:s,part:l,markers:c,onCancel:M,onChange:N,onShift:k}),x==="month"&&w.length>0&&i.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:w.map(T=>i.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:i.jsx($p,{onClick:L=>j(L,cj(T)),children:y(T)})},T))})]})]})})}function Bp(n){let{words:a=null,optional:s=!1,children:l}=n,c=d.useContext(ds);const u=d.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=Ju(iw)),a!==null&&(m=m.extend(a,s)),m},[a,s,c]);return i.jsx(ds.Provider,{value:u,children:l})}function db(n,a,s,l){if(!n||l){const c=a?new Date(a):new Date;c.setDate(1),s(c)}else if(n.getDate()!==1){const c=new Date(n);c.setDate(1),s(c)}}const dj=["clear","today"];function dw({value:n,current:a,markers:s=null,buttons:l=dj,css:c="",onChange:u}){const[m,h]=Ps(n),[g,y]=Ps(a);d.useEffect(()=>{db(g,m,y,!1)},[m,g]);const x=d.useCallback(w=>{const j=w.value;j?(h(new Date(j)),db(g,new Date(j),y,!0)):h(null),u&&u({value:j?new Date(j):null})},[u,g]),b=d.useCallback(w=>{y(w)},[y]);return g?i.jsx(Bp,{children:i.jsx(uj,{value:m,current:g,markers:s,buttons:l,css:c,onChange:x,onCurrentChange:b})}):null}function fj(n){return n||(n={}),n.width||(n.width="unset"),n}const mj=["clear","today"];function hj({value:n,id:a,disabled:s=!1,error:l=!1,placeholder:c="",format:u="",buttons:m=mj,css:h="",title:g="",tooltip:y,editable:x=!1,clear:b=!1,onChange:w,dropdown:j={}}){const{calendar:M,formats:k}=(d.useContext(ds)||Qf()).getRaw(),N=u||k?.dateFormat;let A=typeof N=="function"?N:kc(N,M);const[T,L]=d.useState(n),[O,I]=d.useState(!1);d.useEffect(()=>{L(n)},[n]);function B(){I(!1)}function _(W){const Y=W===T||W&&T&&W.valueOf()===T.valueOf()||!W&&!T;L(W),Y||w&&w({value:W}),setTimeout(B,1)}const G=d.useMemo(()=>T?A(T):"",[T,A]);function te({value:W,input:Y}){if(!x&&!b||Y)return;let F=typeof x=="function"?x(W):W?new Date(W):null;F=isNaN(F)?T||null:F||null,_(F)}return d.useEffect(()=>{const W=B;return window.addEventListener("scroll",W),()=>window.removeEventListener("scroll",W)},[]),i.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>I(!0),children:[i.jsx(Fp,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:G,id:a,readonly:!x,disabled:s,error:l,placeholder:c,onInput:B,onChange:te,icon:"wxi-calendar",clear:b}),O&&!s&&i.jsx(Pp,{onCancel:B,...fj(j),children:i.jsx(dw,{buttons:m,value:T,onChange:W=>_(W.value)})})]})}function pj({value:n="",options:a=[],textOptions:s=null,placeholder:l="",disabled:c=!1,error:u=!1,title:m="",tooltip:h,textField:g="label",clear:y=!1,css:x="",children:b,onChange:w,dropdown:j={}}){const M=d.useRef(null),k=d.useRef(null);let[N,A]=Ps(n);function T(_){M.current=_.navigate,k.current=_.keydown}const L=d.useMemo(()=>N||N===0?(s||a).find(_=>_.id===N):null,[N,s,a]),O=d.useCallback(({id:_})=>{(_||_===0)&&(A(_),M.current(null),w&&w({value:_}))},[A,w]),I=d.useCallback(_=>{_.stopPropagation(),A(""),w&&w({value:""})},[A,w]),B=d.useCallback(()=>a.findIndex(_=>_.id===N),[a,N]);return i.jsxs("div",{className:`wx-2YgblL wx-richselect ${x} ${u?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>M.current(B()),onKeyDown:_=>k.current(_,B()),tabIndex:0,"data-tooltip-text":h,children:[i.jsx("div",{className:"wx-2YgblL wx-label",children:L?b?b(L):L[g]:l?i.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),y&&!c&&N?i.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:I}):i.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&i.jsx(Xf,{items:a,onReady:T,onSelect:O,...j,children:({option:_})=>b?b(_):_[g]})]})}const gj=({options:n=[],value:a="",css:s="",children:l,onChange:c})=>{const[u,m]=d.useState(a),h=g=>{m(g),c&&c({value:g})};return d.useEffect(()=>{m(a)},[a]),i.jsx("div",{className:`wx-0hMO7P wx-segmented ${s}`,children:n.map(g=>i.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:l?_p(l,{option:g}):i.jsxs(i.Fragment,{children:[g.icon&&i.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&i.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function vj({notice:n={}}){function a(){n.remove&&n.remove()}return i.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${n.type?n.type:""}`,role:"status","aria-live":"polite",children:[i.jsx("div",{className:"wx-11sNg5 wx-text",children:n.text}),i.jsx("div",{className:"wx-11sNg5 wx-button",children:i.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function yj({data:n=[]}){return i.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>i.jsx(vj,{notice:a},a.id))})}function vp({title:n="",buttons:a=["cancel","ok"],header:s,children:l,footer:c,css:u="",onConfirm:m,onCancel:h}){const g=(d.useContext(ds)||Qf()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function x(w){switch(w.code){case"Enter":{const j=w.target.tagName;if(j==="TEXTAREA"||j==="BUTTON")return;m&&m({event:w});break}case"Escape":h&&h({event:w});break}}function b(w,j){const M={event:w,button:j};j==="cancel"?h&&h(M):m&&m(M)}return i.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:x,children:i.jsxs("div",{className:"wx-1FxkZa wx-window",children:[s||(n?i.jsx("div",{className:"wx-1FxkZa wx-header",children:n}):null),i.jsx("div",{children:l}),c||a&&i.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(w=>i.jsx("div",{className:"wx-1FxkZa wx-button",children:i.jsx(Gu,{type:`block ${w==="ok"?"primary":"secondary"}`,onClick:j=>b(j,w),children:g(w)})},w))})]})})}function bj({children:n},a){const[s,l]=d.useState(null),[c,u]=d.useState([]);return d.useImperativeHandle(a,()=>({showModal:m=>{const h={...m};return l(h),new Promise((g,y)=>{h.resolve=x=>{l(null),g(x)},h.reject=x=>{l(null),y(x)}})},showNotice:m=>{m={...m},m.id=m.id||zp(),m.remove=()=>u(h=>h.filter(g=>g.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),u(h=>[...h,m])}}),[]),i.jsxs(i.Fragment,{children:[n,s&&i.jsx(vp,{title:s.title,buttons:s.buttons,onConfirm:s.resolve,onCancel:s.reject,children:s.message}),i.jsx(yj,{data:c})]})}const xj=d.forwardRef(bj);function wj(n){let{children:a}=n,s=d.useRef();const l=d.useMemo(()=>({showNotice:c=>s.current.showNotice(c),showModal:c=>s.current.showModal(c)}),[]);return i.jsx(lw.Provider,{value:l,children:i.jsx(xj,{ref:s,children:a})})}const Sj=({value:n=!1,type:a="",icon:s="",disabled:l=!1,iconActive:c="",onClick:u,title:m="",tooltip:h,css:g="",text:y="",textActive:x="",children:b,active:w,onChange:j})=>{const[M,k]=Ps(n),N=d.useMemo(()=>(M?"pressed":"")+(a?" "+a:""),[M,a]),A=d.useCallback(T=>{let L=!M;u&&u(T),T.defaultPrevented||(k(L),j&&j({value:L}))},[M,u,j]);return M&&w?i.jsx(Gu,{title:m,tooltip:h,text:M&&x||y,css:g,type:N,icon:M&&c||s,onClick:A,disabled:l,children:_p(w,{value:M})}):b?i.jsx(Gu,{title:m,tooltip:h,text:M&&x||y,css:g,type:N,icon:M&&c||s,onClick:A,disabled:l,children:b}):i.jsx(Gu,{title:m,tooltip:h,text:M&&x||y,css:g,type:N,icon:M&&c||s,onClick:A,disabled:l})};function Cj(){return i.jsx(i.Fragment,{})}function fb(n){const{fonts:a=!0,children:s}=n;return i.jsx(Op.Provider,{value:"willow",children:i.jsxs(i.Fragment,{children:[s&&s&&i.jsx("div",{className:"wx-theme wx-willow-theme",children:s}),a&&i.jsxs(i.Fragment,{children:[i.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),i.jsx(Cj,{}),i.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Ip(ir);const Up={grid:{"Add before":"Add before","Add after":"Add after",Copy:"Copy",Cut:"Cut",Paste:"Paste",Delete:"Delete","New row":"New row","Move up":"Move up","Move down":"Move down",Undo:"Undo",Redo:"Redo",selected:"selected"}};new Date().valueOf();var fw=class{constructor(n){this._nextHandler=null,this._dispatch=n,this.exec=this.exec.bind(this)}async exec(n,a){return this._dispatch(n,a),this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};new Date().valueOf();var kj=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},s=new Map;s.set(0,a),this._pool=s,n&&n.length&&this.parse(n,0)}parse(n,a){const s=this._pool;for(let c=0;c<n.length;c++){const u=n[c];u.parent=u.parent||a,u.data=null,s.set(u.id,u)}for(let c=0;c<n.length;c++){const u=n[c],m=s.get(u.parent);m&&(m.data||(m.data=[]),m.data.push(u))}const l=s.get(a);this.setLevel(l,l.$level+1,!1)}add(n,a){const s=this._pool.get(n.parent||0);n.$level=s.$level+1,this._pool.set(n.id,n),s.data?a===-1?s.data=[...s.data,n]:mb(s,a,n):s.data=[n]}addAfter(n,a){if(!a)return this.add(n,-1);const s=this.byId(a),l=this.byId(s.parent),c=pf(l,s.id)+1;n.parent=l.id,n.$level=l.$level+1,this.add(n,c)}remove(n){const a=this._pool.get(n);this._remove(a);const s=this._pool.get(a.parent);s.data=s.data.filter(l=>l.id!=n),this._clearBranch(s)}_remove(n){n.data&&n.data.forEach(a=>this._remove(a)),this._pool.delete(n.id)}update(n,a){let s=this._pool.get(n);const l=this._pool.get(s.parent),c=pf(l,s.id);s={...s,...a},l&&c>=0&&(l.data[c]=s,l.data=[...l.data]),this._pool.set(s.id,s)}move(n,a,s){const l=this._pool.get(n),c=a==="child",u=this._pool.get(s),m=u.$level+(c?1:0);if(!l||!u)return;const h=this._pool.get(l.parent),g=c?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=pf(h,l.id);jj(h,y);const x=c?g.data.length:pf(g,u.id)+(a==="after"?1:0);if(mb(g,x,l),h.id===g.id&&y===x)return null;l.parent=g.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(h)}_clearBranch(n){n.data&&!n.data.length&&(n.open&&delete n.open,this.update(n.id,{data:null}))}toArray(){const n=[],a=this._pool.get(0).data;return a&&mw(a,n),n}byId(n){return this._pool.get(n)}getBranch(n){return this._pool.get(n).data}forEach(n){this._pool.forEach((a,s)=>{s!==0&&n(a)})}eachChild(n,a){const s=this.byId(a);!s||!s.data||s.data.forEach((l,c)=>{n(this.byId(l.id),c),this.eachChild(n,l.id)})}setLevel(n,a,s){n.data&&(n.data=n.data.map(l=>(s&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,s),l)))}};function mw(n,a){n.forEach(s=>{a.push(s),s.open===!0&&mw(s.data,a)})}function jj(n,a){const s=[...n.data];s.splice(a,1),n.data=s}function mb(n,a,s){const l=[...n.data];l.splice(a,0,s),n.data=l}function pf(n,a){return n?.data.findIndex(s=>s.id===a)}var hw=2,Mj=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,s=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,s),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,s,l,c,u,m){for(const h in a){const g=s[h],y=l[h],x=a[h];if(g&&(y===x&&typeof x!="object"||x instanceof Date&&y instanceof Date&&y.getTime()===x.getTime()))continue;const b=c+(c?".":"")+h;g?(g.__parse(x,b,u,m)&&(l[h]=x),m&hw?u[b]=g.__trigger:g.__trigger()):(x&&x.__reactive?s[h]=this._wrapNested(x,x,b,u):s[h]=this._wrapWritable(x),l[h]=x),u[b]=u[b]||null}}_wrapNested(a,s,l,c){const u=this._wrapWritable(a);return this._wrapProperties(a,u,s,l,c,0),u.__parse=(m,h,g,y)=>(this._wrapProperties(m,u,s,h,g,y),!1),u}_wrapWritable(a){const s=[],l=function(){for(let c=0;c<s.length;c++)s[c](a)};return{subscribe:c=>(s.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const u=s.indexOf(c);u>=0&&s.splice(u,1)}),__trigger:()=>{s.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function hb(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var Aj=class{constructor(a,s,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=s,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(m=>{const h=this._triggers.get(m)||[];h.push(u),this._triggers.set(m,h)}),u.out.forEach(m=>{const h=this._sources.get(m)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(m,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(m=>pw(m,this._sources,1)))}),this._bus=c}init(a){const s={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];s[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(s),this._bus&&this._bus.exec("init-state",s)}setStateAsync(a){const s=this._setter(a,hw);return this._async?Object.assign(this._async.signals,s):this._async={signals:s,timer:setTimeout(this._applyState.bind(this),1)},s}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const s in a.signals){const l=a.signals[s];l&&l()}}}setState(a,s=[]){const l=this._setter(a);return this._triggerUpdates(l,s),l}_triggerUpdates(a,s){const l=Object.keys(a),c=!s.length;s=s||[];for(let u=0;u<l.length;u++){const m=l[u],h=this._triggers.get(m);h&&h.forEach(g=>{s.indexOf(g)==-1&&s.push(g)})}c&&this._execNext(s)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const s=a[a.length-1];a.splice(a.length-1),s.exec(a)}}};function pw(n,a,s){const l=a.get(n);if(!l)return s;const c=Object.keys(l).map(u=>pw(u,a,s+1));return Math.max(...c)}var Nj=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,s,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(s):c.push(s):c=this._handlers[a]=[s],l&&l.tag&&this._tag.set(s,l.tag)}intercept(a,s,l){this.on(a,s,{...l,intercept:!0})}detach(a){for(const s in this._handlers){const l=this._handlers[s];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,s){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const u=l[c](s);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,s),s}setNext(a){return this._nextHandler=a}};const yc=1024;function Zu(n){return n<yc?`${n} B`:n<yc**2?`${(n/yc).toFixed(1)} KB`:n<yc**3?`${(n/yc**2).toFixed(1)} MB`:`${(n/yc**3).toFixed(1)} GB`}function pb(n,a){a||(a={key:"name",order:"asc"});const s=n.filter(m=>m.type==="folder"),l=n.filter(m=>m.type!=="folder"),c=s.sort(gb(a)),u=l.sort(gb(a));return[...c,...u]}function Tj(n,a){return typeof n=="string"?n.localeCompare(a,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-a.getTime():(n??0)-(a??0)}function Rj(n,a){return typeof n=="string"?-n.localeCompare(a,void 0,{numeric:!0}):typeof a=="object"?a.getTime()-n.getTime():(a??0)-(n??0)}function gb({key:n,order:a}){const s=a==="asc"?Tj:Rj;return(l,c)=>s(l[n],c[n])}function qp(n,a){const s=n==="/"?1:n.split("/").length;return s>=a.length?null:a[s].id}function Ej(n){return n.length>1?n[n.length-2].id:null}let Dj=class extends kj{constructor(a){const s={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([s]),this.parse(a,"/")}parse(a,s,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?s:void 0)),super.parse(a,s))}parseId(a,s){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=s??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const u=a.name.lastIndexOf("."),m=u!==-1?a.name.slice(u+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const s=[];let l=this.byId(a);if(!l)return s;for(;l.id!==0;)s.push(l),l=this.byId(l.parent);return s.reverse()}findFiles(a,s="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(c)!==-1&&l.push(u)},s),l}add(a,s){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,s??l.data?l.data.length:0),c&&c.forEach(u=>this.add(u))}renameFiles(a,s,l){const c=this.byId(a),u=this.normalizeFile(c,s),m=[];return u.data?.forEach(h=>m.push(this.renameFiles(h.id,u.id,l))),m.length&&(u.data=m),l[a]=u.id,u}copyFiles(a,s,l){const c={};return a.forEach(u=>{const m=this.renameFiles(u,s,c);this.add(m),l&&this.remove(u),c[u]=m.id}),c}moveFiles(a,s){if(this.byId(a[0]).parent!==s)return this.copyFiles(a,s,!0)}serialize(a="/"){const s=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:u,date:m,type:h,size:g,lazy:y}=c,x={id:u,date:m,type:h??"file"};y&&(x.lazy=y),g&&(x.size=g),s.push(x);const b=this.serialize(u);b.length&&s.push(...b)}),s):null}normalizeFile(a,s){const l=a.name,c=l.lastIndexOf("."),u=c!==-1?l.slice(c+1):"",m=u?`.${u}`:"";let h=c!==-1?l.slice(0,c):l,g=s+(s==="/"?"":"/")+h;for(;this.byId(g+m);){const y=".new";g+=y,h+=y}return{...a,id:g+m,name:h+m,parent:s,ext:u.toLocaleLowerCase()}}},Lj=class extends Mj{in;_router;constructor(a){super({writable:a,async:!1});const s=[];for(let u=0;u<2;u++)s.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},m)}}),s.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:m=>{const{data:h,panels:g,search:y}=this.getState();let x;y?x=h.findFiles(y,g[u].path):x=h.byId(g[u].path)?.data||[];const{path:b,_sorts:w}=g[u];x=pb(x,w[b]);const j=[];j[u]={_files:x},this.setState({panels:j},m)}}),s.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(M=>{const k=h.byId(M);k&&y.push(k)});const{path:x,_sorts:b}=g[u],w=pb(y,b[x]),j=[];j[u]={_selected:w},this.setState({panels:j},m)}});this._router=new Aj(super.setState.bind(this),s,{data:u=>new Dj(u)});const l=this.in=new Nj;l.on("select-file",({id:u,toggle:m,range:h,panel:g,type:y})=>{const{panels:x,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(m=h=!1);let w=[...x[g].selected];if(m){const M=w.indexOf(u);M===-1?w.push(u):w.splice(M,1)}else if(h&&x[g]._lastSelected){const M=x[g]._files;let k=M.findIndex(T=>T.id==x[g]._lastSelected),N=M.findIndex(T=>T.id==u);N<k&&([k,N]=[N,k]);const A=M.slice(k,N+1).map(T=>T.id);w=[...new Set([...w,...A])]}else w=u?[u]:[];const j=[];j[g]={selected:w,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:j})}),l.on("set-path",({id:u,panel:m,selected:h})=>{const{data:g,activePanel:y}=this.getState(),x=g.byId(u);if(x){const b=[];typeof m>"u"&&(m=y),b[m]={path:u},this.setState({panels:b}),l.exec("select-file",{panel:m}),h&&h.forEach(w=>l.exec("select-file",{id:w,panel:m,toggle:!0})),x.lazy&&l.exec("request-data",{id:u})}}),l.on("provide-data",({id:u,data:m})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(m,u,h==="search"),this.setState({data:g}))}),l.on("open-tree-folder",({id:u,mode:m})=>{const{data:h}=this.getState();h.update(u,{open:m}),this.setState({data:h})}),l.on("show-preview",({mode:u})=>{this.setState({preview:u})}),l.on("rename-file",u=>{const{id:m,name:h}=u,{data:g,panels:y}=this.getState(),x=g.byId(m);if(x.name!==h){x.name=h;const b=g.normalizeFile(x,x.parent);u.newId=b.id,b.data=null,g.add(b);let w={[m]:b.id};x.data?.forEach(M=>w={...g.moveFiles([M.id],b.id),...w});const j=y.map(M=>({selected:M.selected,_crumbs:M._crumbs,_lastSelected:M._lastSelected,_sorts:M._sorts}));g.remove(m),this._updatePanels(j,w),this.setState({data:g,panels:j})}}),l.on("create-file",u=>{const{file:m,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(m,h);y.type=m.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),l.exec("select-file",{id:y.id})}),l.on("delete-files",({ids:u})=>{const{data:m,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>m.remove(y)),this._updatePanels(g,{}),this.setState({data:m,panels:g})}),l.on("copy-files",u=>{const{ids:m,target:h}=u;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.copyFiles(m,h);u.newIds=m.map(w=>b[w]),this.setState({data:g}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(w=>{l.exec("select-file",{id:b[w],toggle:!0})}))}),l.on("move-files",u=>{const{ids:m,target:h}=u;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.moveFiles(m,h);if(b){u.newIds=m.map(j=>b[j]);const w=y.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));this._updatePanels(w,b,!0),this.setState({data:g,panels:w}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(j=>{l.exec("select-file",{id:b[j],toggle:!0})}))}});let c=null;l.on("filter-files",({text:u})=>{if(!u){c&&this.setState({...c});return}l.exec("select-file",{});const{panels:m,mode:h}=this.getState();c||(c={panels:m,mode:h,search:""}),this.setState({mode:"search",search:u})}),l.on("set-mode",({mode:u})=>{const{activePanel:m}=this.getState(),h=[];h[m]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};c=null,this.setState(g)}),l.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),l.on("sort-files",({key:u,order:m,panel:h,path:g})=>{const{activePanel:y,panels:x}=this.getState();h=h??y,g=g??x[h].path;const b=[];b[h]={_sorts:{...x[h]._sorts,[g]:{key:u,order:m}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=hb({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const s={panels:hb(a),data:[],search:""};this._router.init(s)}init(a){const s={...a};this._router.init(s)}setState(a,s){return this._router.setState(a,s)}getFile(a){const{data:s}=this.getState();return s.byId(a)||null}serialize(a){const{data:s}=this.getState();return s.serialize(a)}_updatePanels(a,s,l){const{data:c}=this.getState();a.forEach(u=>{const m=[];u.selected.forEach(y=>{c.byId(y)?m.push(y):!l&&s[y]&&m.push(s[y])}),u.selected=m,c.byId(u._lastSelected)||(u._lastSelected=l?null:s[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{c.byId(y)?h[y]=u._sorts[y]:s[y]&&!l&&(h[s[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(s[g.id]?u.path=s[g.id]:c.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(a,s){return a.some(l=>l===s||this.getState().data.getParents(s).some(c=>c.id===l))}};function _j(n){switch(n){case"body":return[{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"}];case"add":return[{icon:"mdi mdi-folder-plus-outline",text:"Add new file",id:"add-file"},{icon:"mdi mdi-file-plus-outline",text:"Add new folder",id:"add-folder"},{icon:"mdi mdi-file-upload-outline",text:"Upload file",id:"upload",comp:"upload"}];case"multiselect":return[{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{comp:"separator"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}];default:return[n==="folder"?null:{icon:"wxi-download",text:"Download",hotkey:"Ctrl+D",id:"download"},{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"},{comp:"separator"},{icon:"wxi-edit",text:"Rename",hotkey:"Ctrl+R",id:"rename"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}].filter(a=>a!==null)}}function Ij(n,a="data-id"){let s=n;for(!s.tagName&&n.target&&(s=n.target);s;){if(s.getAttribute&&s.getAttribute(a))return s;s=s.parentNode}return null}function zj(n,a="data-id"){const s=Ij(n,a);return s?s.getAttribute(a):null}new Date().valueOf();function Oj(n,a){const{api:s}=a;function l(u,m){const h=a.getPanel(),g=h.selected,y=m.ctrlKey||m.metaKey,x=m.shiftKey;let b;const w=g?.[0]?s.getFile(g[0]):null;g?.length?g.length>1?b=a.menuOptions("multiselect"):b=a.menuOptions(w.type,w):b=a.menuOptions("body");const j=`${y?"ctrl+":""}${x?"shift+":""}${u}`,M=b?b.find(N=>N.hotkey?.toLowerCase()===j):!1,k=a.performAction;if(M)switch(j){case"ctrl+c":k("copy");break;case"ctrl+x":k("move");break;case"ctrl+v":k("paste",w);break;case"delete":k("delete");break;case"ctrl+r":m.preventDefault(),k("rename",w);break;case"ctrl+d":m.preventDefault(),k("download",w);break;default:M.handler?.({context:w})}switch(u){case"enter":{if(y||x)break;const{_crumbs:N,_selectNavigation:A}=h;if(A){const T=Ej(N);if(T){const L=qp(T,N);s.exec("set-path",{id:T,selected:[L]})}}else if(g.length===1){const T=s.getFile(g[0]);T&&s.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:N,_selected:A,path:T,_selectNavigation:L}=h;let O;if(A.length){const I=A.at(0).id,B=N.findIndex(_=>_.id===I);if(B!==-1){const _=B-1;N[_]?O=N[_].id:T!=="/"&&!(y||x)&&s.exec("select-file",{type:"navigation"})}}else{if(L)break;if(T!=="/"){s.exec("select-file",{type:"navigation"});break}O=N.at(0)?.id}O&&s.exec("select-file",{id:O,toggle:y,range:x});break}case"arrowdown":case"arrowright":{const{_files:N,_selected:A,path:T,_selectNavigation:L}=h;let O;if(A.length){const I=A.at(-1).id,B=N.findIndex(_=>_.id===I);if(B!==-1){const _=B+1;N[_]&&(O=N[_].id)}}else{if(T!=="/"&&!L){s.exec("select-file",{type:"navigation"});break}O=N.at(0)?.id}O&&s.exec("select-file",{id:O,toggle:y,range:x});break}}}function c(u){const m=u.code.replace("Key","").toLowerCase();l(m,u),m=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&s.exec("set-active-panel",{panel:+zj(h,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Hj(n,a="data-id"){let s=n;for(!s.tagName&&n.target&&(s=n.target);s;){if(s.getAttribute&&s.getAttribute(a))return s;s=s.parentNode}return null}function Pj(n,a="data-id"){const s=n.getAttribute(a);return s?Fj(s):null}function Fj(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function $j(){return{detect:()=>!0,addEvent:function(n,a,s){return n.addEventListener(a,s),()=>n.removeEventListener(a,s)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var Bj=$j();new Date().valueOf();function gw(n){const[a,s]=d.useState(n),l=d.useRef(n);return d.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,s(n)}},[n]),[a,s]}function Uj(n,a,s){const[l,c]=d.useState(()=>a);return n||console.warn(`Writable ${s} is not defined`),d.useEffect(()=>n?n.subscribe(m=>{c(()=>m)}):void 0,[n]),l}function ht(n,a){const s=n.getState(),l=n.getReactiveState();return Uj(l[a],s[a],a)}function qj(n,a){const s=d.useRef(a);s.current=a;const[l,c]=d.useState(1);return d.useEffect(()=>n.subscribe(m=>{s.current=m,c(h=>h+1)}),[n]),[s.current,l]}function Pr(n,a){const s=n.getState(),l=n.getReactiveState();return qj(l[a],s[a])}function vw(n){const a={};return n.split(";").forEach(s=>{const[l,c]=s.split(":");if(c){let u=l.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(m,h)=>h.toUpperCase())),a[u]=c.trim()}}),a}function yw(n){let a=n,s=[];return{subscribe:h=>{s.push(h),h(a)},unsubscribe:h=>{s=s.filter(g=>g!==h)},set:h=>{a=h,s.forEach(g=>g(a))},update:h=>{a=h(a),s.forEach(g=>g(a))}}}function vb(n,a,s){function l(c){const u=Hj(c);if(!u)return;const m=Pj(u);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[s]&&a[s](m,c)}return Bj.addEvent(n,s,l)}function Gj(n,a){const s=[vb(n,a,"click")];return a.dblclick&&s.push(vb(n,a.dblclick,"dblclick")),()=>{s.forEach(l=>l())}}function bw(n,a){return n.map((s,l)=>{const c=a(s,l);return s.data&&s.data.length&&(c.data=bw(s.data,a)),c}).filter(Boolean)}function xw(n,a){const s=[];return n.forEach(l=>{if(l.data){const c=xw(l.data,a);c.length&&s.push({...l,data:c})}else a(l)&&s.push(l)}),s}function Vj(n){return bw(n,(a,s)=>{const l={...a,id:a.id||zp()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[s-1]?.comp==="separator"?null:l})}const ww={};function Wj(n){return ww[n]||n}function Yj(n,a){ww[n]=a}function Kj({onClick:n,onShow:a,option:s}){const l=d.useRef(null),c=d.useCallback(()=>{a(s.data?s.id:!1,l.current)},[a,s]),u=d.useCallback(h=>{if(s.data){h.stopPropagation(),a(s.id,l.current);return}n(h)},[n,a,s]),m=d.useMemo(()=>s&&s.comp?Wj(s.comp):null,[s]);return i.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${s.css||""} ${s.disabled?"wx-disabled":""}`,"data-id":na(s.id),onMouseEnter:c,onClick:u,children:[s.icon?i.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${s.icon}`}):null,s.comp?m?i.jsx(m,{item:s,option:s}):null:i.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",s.text," "]}),s.subtext?i.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:s.subtext}):null,s.data?i.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Gp({options:n,left:a=0,top:s=0,at:l="bottom",parent:c=null,mount:u=null,context:m=null,css:h="",onClick:g,onCancel:y}){const[x,b]=d.useState(-1e4),[w,j]=d.useState(-1e4),[M,k]=d.useState(20),[N,A]=d.useState(),T=d.useRef(null),[L,O]=d.useState(!1),[I,B]=d.useState(null),_=d.useCallback(()=>{const fe=aw(T.current,c,l,a,s);fe&&(b(fe.x),j(fe.y),A(fe.width));let Q=fe?.z??20;const z=c?Ok(c):[];let re=0;for(const V of z){const H=parseInt(getComputedStyle(V).zIndex,10);H>re&&(re=H)}re>=Q&&(Q=re+1),k(Q)},[c,l,a,s]);d.useEffect(()=>{u&&u(_)},[]);const G=d.useCallback(()=>{O(!1)},[]),te=d.useCallback((fe,Q)=>{O(fe),B(Q)},[]),W=d.useMemo(()=>Vj(n),[n]);d.useEffect(()=>{_()},[c,_]);const Y=d.useRef(g),F=d.useRef(y),ve=d.useRef(c);return d.useEffect(()=>{Y.current=g},[g]),d.useEffect(()=>{F.current=y},[y]),d.useEffect(()=>{ve.current=c},[c]),d.useEffect(()=>{if(!T.current)return;function fe(Q){F.current?F.current(Q):Y.current&&Y.current({action:null,option:null})}return Fs(T.current,{callback:fe,modal:!0,parent:()=>ve.current}).destroy},[]),i.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:w+"px",left:x+"px",width:N,zIndex:M},onMouseLeave:G,children:W.map(fe=>i.jsxs(d.Fragment,{children:[fe.comp==="separator"?i.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):i.jsx(Kj,{option:fe,onShow:te,onClick:Q=>{if(!fe.data&&!Q.defaultPrevented){const z={context:m,action:fe,option:fe,event:Q};fe.handler&&fe.handler(z),g&&g(z),Q.stopPropagation()}}}),fe.data&&L===fe.id?i.jsx(Gp,{css:h,options:fe.data,at:"right-overlap",parent:I,context:m,onClick:g,onCancel:y}):null]},fe.id))})}const Sw=d.forwardRef(function(n,a){const{options:s,at:l="bottom",resolver:c=null,dataKey:u="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,[x,b]=d.useState(null),[w,j]=d.useState(null),[M,k]=d.useState(0),[N,A]=d.useState(0),T=d.useRef(null),L=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),O=d.useMemo(()=>x!==null&&m?xw(s,G=>m(G,x)):s,[x,m,s]);function I(G){j(null),y&&y(G)}function B(G){if(T.current===G){T.current=null;return}j(null),y&&y({action:null,option:null})}const _=d.useCallback((G,te)=>{if(!G){j(null);return}if(G.defaultPrevented)return;const W=G.target;if(W&&W.dataset&&W.dataset.menuIgnore)return;if(w&&w===W){j(null),G.preventDefault();return}k(G.clientX+1),A(G.clientY+1);let Y=typeof te<"u"?te:Xu(W,L);c&&(Y=c(Y,G),!Y)||(b(Y),j(W),T.current=G.nativeEvent||G,G.preventDefault())},[w,L,c]);return d.useImperativeHandle(a,()=>({show:_}),[_]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onClick:_,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,w?i.jsx(Hp,{children:i.jsx(Gp,{css:h,at:l,top:N,left:M,parent:w,context:x,onClick:I,onCancel:B,options:O},w)}):null]})}),Qj=d.forwardRef(function(n,a){const{options:s,at:l="bottom",css:c="",children:u,onClick:m}=n,[h,g]=d.useState(null),y=d.useRef(null);function x(M){g(null),m&&m(M)}function b(M){if(y.current===M){y.current=null;return}g(null),m&&m({action:null,option:null})}const w=d.useCallback(M=>{g(M.target),y.current=M.nativeEvent||M,M.preventDefault()},[]);d.useImperativeHandle(a,()=>({show:w}),[w]);function j(M){let k=M.target;for(;!k.dataset.menuIgnore;)g(k),k=k.parentNode}return i.jsxs(i.Fragment,{children:[i.jsx("span",{onClick:j,"data-menu-ignore":"true",children:u}),h?i.jsx(Hp,{children:i.jsx(Gp,{css:c,at:l,parent:h,options:s,onClick:x,onCancel:b})}):null]})}),Xj=d.forwardRef(function(n,a){const{options:s,at:l="bottom",resolver:c=null,dataKey:u="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,x=d.useRef(null),b=d.useCallback((w,j)=>{x.current.show(w,j)},[]);return d.useImperativeHandle(a,()=>({show:b}),[b]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,i.jsx(Sw,{css:h,at:l,options:s,resolver:c,dataKey:u,filter:m,ref:x,onClick:y})]})}),Zj={uploader:{B:"B",KB:"KB",MB:"MB",GB:"GB",TB:"TB",PB:"PB",EB:"EB","Drop files here or":"Drop files here or","select files":"select files"}};let Jj=class{constructor(a,s,l,c,u){this.setFiles=a,this.setReady=s,this.setSignal=l,this.setDrag=c,u&&u.length&&this.setFiles(u)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const s=this.files;for(let l=0;l<s.length;l++){if(s[l].status==="client")return"client";s[l].status==="error"&&(a="error")}return a}droparea(a,s){s=s||{};const l=()=>{s.dragEnter&&s.dragEnter(),this.setDrag(!0)},c=()=>{s.dragLeave&&s.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},m=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",s,h]),s.dragLeave&&s.dragLeave(),s.drop&&s.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",u,!0),a.addEventListener("drop",m,!0),()=>{a.removeEventListener("dragenter",l),a.removeEventListener("dragleave",c),a.removeEventListener("dragover",u,!0),a.removeEventListener("drop",m,!0)}}updateFile(a,s){const l=this.files.findIndex(u=>u.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...s},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(s=>s.id!==a),this.setFiles(this.files)}addFile(a,s){s?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function Cw(n){const[a,s]=d.useState([]),[l,c]=d.useState(Promise.resolve(null)),[u,m]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new Jj(s,c,m,g,n)),y.current.files=a,y.current.ready=l,y.current.signal=u,y.current.drag=h,y.current}function eM(n,a){{if(n){const s=n.getGroup(a);if(s)return s}return Ju(Zj).getGroup(a)}}const tM=()=>Math.random().toString(36).substr(2,9),nM=({data:n,accept:a="",multiple:s=!0,folder:l=!1,uploadURL:c="",apiOnly:u=!1,disabled:m=!1,children:h,onChange:g,onUpload:y})=>{const x=d.useRef(null),b=d.useRef(null),[w,j]=d.useState({}),M=Cw(),k=n||M,N=d.useContext(ra.i18n),A=eM(N,"uploader");d.useEffect(()=>{x.current&&l&&(x.current.webkitdirectory=!0)},[l]),d.useEffect(()=>{if(!u&&b.current&&!m)return k.droparea(b.current)},[u,m,b]);const T=W=>{const Y=new FormData;return Y.append("upload",W.file),fetch(c,{method:"POST",body:Y}).then(F=>F.json()).then(F=>({id:W.id,...F}),()=>({id:W.id,status:"error"})).catch(F=>(console.log(F),{id:W.id,status:"error"}))},L=(W,Y)=>{const F=k.updateFile(W,Y),ve={...F,status:k.getState()};F&&F.uploaded&&F.uploaded(ve),y&&y(ve),F.temp&&k.deleteFile(F.id)},O=W=>{if(!W)return;const Y=typeof c=="function"?c(W):T(W);k.setReady(Y.then(F=>{F.status=F.status||"server",L(W.id,F)}).catch(F=>{L(W.id,{status:"error",error:F})}))},I=(W,Y)=>{const F={...Y||w,id:tM(),status:"client",name:W.name,file:W};F.selected&&F.selected(F),g&&g(F),k.addFile(F,s),O(F),x.current&&(x.current.value="")},B=(W,Y,F)=>{W.isFile?W.file(ve=>{I(ve,F)}):W.isDirectory&&W.createReader().readEntries(ve=>{ve.forEach(fe=>{B(fe,Y+fe.name+"/",F)})})},_=W=>{Array.from(W.target.files).forEach(Y=>I(Y))},G=(W,Y)=>{Array.from(W.dataTransfer.items).forEach(F=>{const ve=F.webkitGetAsEntry();ve&&B(ve,"",Y)})},te=()=>{x.current&&x.current.click()};return d.useEffect(()=>{if(k.signal){const[W,Y,F]=k.signal;j(Y),W==="click"?te():W==="drop"&&G(F,Y),k.setSignal(null)}},[k.signal]),u?i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:s,disabled:m}),h]}):i.jsxs("div",{className:`wx-at1A8tb8 wx-label ${k.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:b,children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:s,disabled:m}),h||i.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:i.jsxs("span",{children:[A("Drop files here or")," ",i.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:te,children:A("select files")})]})})]})};new Date().valueOf();function aM(n,a){if(Object.keys(n).length!==Object.keys(a).length)return!1;for(const s in a){const l=n[s],c=a[s];if(!Zf(l,c))return!1}return!0}function Zf(n,a){if(typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null)return n===a;if(typeof n!=typeof a||(n===null||a===null)&&n!==a||n instanceof Date&&a instanceof Date&&n.getTime()!==a.getTime())return!1;if(typeof n=="object")if(Array.isArray(n)&&Array.isArray(a)){if(n.length!==a.length)return!1;for(let s=n.length-1;s>=0;s--)if(!Zf(n[s],a[s]))return!1;return!0}else return aM(n,a);return n===a}function yp(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(yp);const a={};for(const s in n)a[s]=yp(n[s]);return a}var kw=2,rM=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,a=0){const s={};return this._wrapProperties(n,this._state,this._values,"",s,a),s}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,a,s,l,c,u){for(const m in n){const h=a[m],g=s[m],y=n[m];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const x=l+(l?".":"")+m;h?(h.__parse(y,x,c,u)&&(s[m]=y),u&kw?c[x]=h.__trigger:h.__trigger()):(y&&y.__reactive?a[m]=this._wrapNested(y,y,x,c):a[m]=this._wrapWritable(y),s[m]=y),c[x]=c[x]||null}}_wrapNested(n,a,s,l){const c=this._wrapWritable(n);return this._wrapProperties(n,c,a,s,l,0),c.__parse=(u,m,h,g)=>(this._wrapProperties(u,c,a,m,h,g),!1),c}_wrapWritable(n){const a=[],s=function(){for(let l=0;l<a.length;l++)a[l](n)};return{subscribe:l=>(a.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const c=a.indexOf(l);c>=0&&a.splice(c,1)}),__trigger:()=>{a.length&&(this._async?setTimeout(s,1):s())},__parse:function(l){return n=l,!0}}}},sM=class{constructor(n,a,s,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=a,this._parsers=s,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(c=>{c.in.forEach(u=>{const m=this._triggers.get(u)||[];m.push(c),this._triggers.set(u,m)}),c.out.forEach(u=>{const m=this._sources.get(u)||{};c.in.forEach(h=>m[h]=!0),this._sources.set(u,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(u=>jw(u,this._sources,1)))}),this._bus=l}init(n){const a={};for(const s in n)if(this._prev[s]!==n[s]){const l=this._parsers[s];a[s]=l?l(n[s]):n[s]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(a),this._bus&&this._bus.exec("init-state",a)}setStateAsync(n){const a=this._setter(n,kw);return this._async?Object.assign(this._async.signals,a):this._async={signals:a,timer:setTimeout(this._applyState.bind(this),1)},a}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const a in n.signals){const s=n.signals[a];s&&s()}}}setState(n,a=[]){const s=this._setter(n);return this._triggerUpdates(s,a),s}_triggerUpdates(n,a){const s=Object.keys(n),l=!a.length;a=a||[];for(let c=0;c<s.length;c++){const u=s[c],m=this._triggers.get(u);m&&m.forEach(h=>{a.indexOf(h)==-1&&a.push(h)})}l&&this._execNext(a)}_execNext(n){for(;n.length;){n.sort((s,l)=>s.length<l.length?1:-1);const a=n[n.length-1];n.splice(n.length-1),a.exec(n)}}};function jw(n,a,s){const l=a.get(n);if(!l)return s;const c=Object.keys(l).map(u=>jw(u,a,s+1));return Math.max(...c)}var iM=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,a,s){let l=this._handlers[n];l?s&&s.intercept?l.unshift(a):l.push(a):l=this._handlers[n]=[a],s&&s.tag&&this._tag.set(a,s.tag)}intercept(n,a,s){this.on(n,a,{...s,intercept:!0})}detach(n){for(const a in this._handlers){const s=this._handlers[a];for(let l=s.length-1;l>=0;l--)this._tag.get(s[l])===n&&s.splice(l,1)}}async exec(n,a){const s=this._handlers[n];if(s)for(let l=0;l<s.length;l++){const c=s[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};function lM(n){return a=>a[n]}function oM(n){return(a,s)=>a[n]=s}function Ol(n,a){return(a.getter||lM(a.id))(n)}function _h(n,a,s){return(a.setter||oM(a.id))(n,s)}function cM(n,a){const s=document.createElement("a");s.href=URL.createObjectURL(n),s.download=a,document.body.appendChild(s),s.click(),document.body.removeChild(s)}function zl(n,a){let s=Ol(n,a)??"";return a.template?s=a.template(s,n,a):a.optionsMap&&(Array.isArray(s)?s=s.map(l=>a.optionsMap.get(l)).join(", "):s=a.optionsMap.get(s)),typeof s>"u"?"":s+""}function uM(n,a){const s=/\n|"|;|,/;let l="";const c=a.rows||`
|
|
13
13
|
`,u=a.cols||" ",m=n._columns,h=n.flatData;a.header!==!1&&m[0].header&&(l=yb("header",m,l,u,c));for(let g=0;g<h.length;g++){const y=[];for(let x=0;x<m.length;x++){let b=zl(h[g],m[x]);s.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}l+=(l?c:"")+y.join(u)}return a.footer!==!1&&m[0].footer&&(l=yb("footer",m,l,u,c)),l}function yb(n,a,s,l,c){const u=/\n|"|;|,/;for(let m=0;m<a[0][n].length;m++){const h=[];for(let g=0;g<a.length;g++){let y=(a[g][n][m].text||"")+"";u.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}s+=(s?c:"")+h.join(l)}return s}const dM="portrait",fM=100,mM="a4",hM={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function pM(n,a){const s=[];let l=[],c=0;const u=n.filter(h=>!h.hidden),m=gM(a);return u.forEach((h,g)=>{c+h.width<=m?(c+=h.width,l.push(h)):(l.length&&s.push(l),l=[h],c=h.width),g===u.length-1&&l.length&&s.push(l)}),s}function bb(n,a,s){const l=[];return n.forEach((c,u)=>{const m=c[a];for(let h=0;h<s.length;h++){l[h]||(l[h]=[]);const g={...m[h]};if(l[h][u]!==null){if(!u&&!g.rowspan&&!g.colspan){let y=1,x=n[u+y][a][h],b=g.width;for(;!x.rowspan&&!x.colspan;)y++,x=n[u+y][a][h],b+=x.width;g.colspan=y,g.width=b,g.height=s[h]}if(l[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+u>n.length){const x=g.colspan-(g.colspan+u-n.length);g.colspan=x,g.width=n.slice(u,u+y+1).reduce((b,w)=>b+w.width,0),x>1&&(y=x-1)}for(let x=0;x<y;x++)l[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let x=1;x<y;x++)l[h+x]||(l[h+x]=[]),l[h+x].push(null)}}}if(c.collapsed)for(let h=0;h<l.length;h++){const g=l[h],y=g[u];if(y&&y.collapsed){if(g[u]=null,!h)break}else{const x=y||g.findLast(b=>b?.colspan>=1);x&&(x.colspan=x.colspan-1,x.width=x.width-c.width)}}}),l.map(c=>c.filter(u=>u&&u.colspan!==0))}function gM(n){const{mode:a,ppi:s,paper:l}=n,{width:c,height:u}=hM[l];return vM(a==="portrait"?c:u,s)}function vM(n,a){return n*a}function yM(n={}){const{mode:a,ppi:s,paper:l}=n;return{mode:a||dM,ppi:s||fM,paper:l||mM}}function Mw(n,a){return n.flexgrow?`min-width:${a}px;width:auto`:`width:${n.width}px; max-width:${n.width}px; height:${n.height}px`}function bM(n,a,s){let l=n[s.id];if(s.filter.type==="richselect"&&l){const c=s.filter.config?.options||a.find(({id:u})=>u==s.id).options;c&&(l=c.find(({id:u})=>u==l).label)}return l??""}const xb=["resize-column","hide-column","update-cell"],xM=["delete-row","update-row","update-cell"],wM=["move-item"],SM=["resize-column","move-item"];class CM{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(a,s,l){this.in=a,this.getState=s,this.setState=l,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:a=>({action:"delete-row",data:{id:a.id},source:{action:"add-row",data:a}})},"delete-row":{handler:a=>{const{id:s}=a,{data:l}=this.getPrev(),c=l.findIndex(u=>u.id===s);return{action:"add-row",data:{id:s,row:l[c],before:c<l.length-1?l[c+1].id:void 0},source:{action:"delete-row",data:a}}}},"update-cell":{handler:a=>{const{id:s,column:l}=a,c=this.getRow(s),u=this.getColumn(l),m=Ol(c,u);return Zf(m,a.value)?null:{action:"update-cell",data:{id:s,column:l,value:m},source:{action:"update-cell",data:a}}}},"update-row":{handler:a=>{const{id:s,row:l}=a,c=this.getRow(s);for(const u in l)Object.keys(c).includes(u)||(c[u]=void 0);return{action:"update-row",data:{id:s,row:c},source:{action:"update-row",data:a}}}},"copy-row":{handler:a=>{const{id:s}=a,{data:l}=this.getState(),c=l.findIndex(m=>m.id===s),u=l[c];return{action:"delete-row",data:{id:s},source:{action:"add-row",data:{id:s,row:u,before:c<l.length-1?l[c+1].id:void 0}}}}},"resize-column":{handler:a=>{const{id:s,width:l}=a,c=this.getColumn(s),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:s,width:c.width??u.columnWidth},source:{action:"resize-column",data:{id:s,width:l}}}}},"hide-column":{handler:a=>{const{id:s}=a,l=this.getColumn(s);return{action:"hide-column",data:{id:s,mode:l.hidden},source:{action:"hide-column",data:a}}}},"collapse-column":{handler:a=>{const{id:s,row:l,mode:c}=a;return{action:"collapse-column",data:{id:s,row:l,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:a}}}},"move-item":{handler:a=>{const{id:s,target:l,mode:c}=a,{flatData:u}=this.getPrev(),m=u.findIndex(h=>h.id===s);return{action:"move-item",data:{id:s,target:u[m+(m?-1:1)].id,mode:m?"after":"before"},source:{action:"move-item",data:{id:s,target:l,mode:c}}}}},"open-row":{handler:a=>{const{id:s,nested:l}=a;return{action:"close-row",data:{id:s,nested:l},source:{action:"open-row",data:a}}}},"close-row":{handler:a=>{const{id:s,nested:l}=a;return{action:"open-row",data:{id:s,nested:l},source:{action:"close-row",data:a}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const a=this.getHandlers();for(const s in a)this.in.intercept(s,l=>{if(!(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo)){if(SM.includes(s)){(l.inProgress&&!this.progress[s]||typeof l.inProgress!="boolean")&&(wM.includes(s)&&this.setPrev("flatData"),xb.includes(s)&&this.setPrev("columns")),this.progress[s]=l.inProgress;return}xM.includes(s)&&this.setPrev("data"),xb.includes(s)&&this.setPrev("columns")}}),this.in.on(s,l=>{if(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo||l.inProgress)return;const c=a[s].handler(l);c&&this.addToHistory(c)})}setPrev(a){this._previousValues[a]=yp(this.getState()[a])}addToHistory(a){this.undo.push(a),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const a=this.undo.pop();this.redo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const a=this.redo.pop();this.undo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(a){const{data:s}=this.getPrev();return this.getState().tree?this.getTreeRow(s,a):s.find(l=>l.id===a)}getTreeRow(a,s){for(let l=0;l<a.length;l++){if(a[l].id===s)return a[l];if(a[l].data){const c=this.getTreeRow(a[l].data,s);if(c)return c}}return null}getColumn(a){const{columns:s}=this.getPrev();return s.find(l=>l.id===a)}}function Aw(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function kM(n,a){return-Aw(n,a)}function jM(n,a){if(typeof a.sort=="function")return function(l,c){const u=a.sort(l,c);return n==="asc"?u:-u};const s=n==="asc"?Aw:kM;return function(l,c){return s(Ol(l,a),Ol(c,a))}}function MM(n,a){if(!n||!n.length)return;const s=n.map(l=>{const c=a.find(u=>u.id==l.key);return jM(l.order,c)});return n.length===1?s[0]:function(l,c){for(let u=0;u<s.length;u++){const m=s[u](l,c);if(m!==0)return m}return 0}}const gf=28,AM=20;function NM(){if(typeof document>"u")return"willow";const n=document.querySelector('[class^="wx"][class$="theme"]');return n?n.className.substring(3,n.className.length-6):"willow"}function Ff(n,a,s,l,c){const u=document.createElement("div"),m=document.createElement("div"),h=document.body;c=c?`${c}px`:"auto";let g,y;m.className=a,u.classList.add(`wx-${s}-theme`),u.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${c};white-space:nowrap;`,u.appendChild(m),h.appendChild(u),typeof n!="object"&&(n=[n]);for(let x=0;x<n.length;x++){m.innerText=n[x]+"";const b=u.getBoundingClientRect(),w=Math.ceil(b.width)+(l&&l.length?l[x]:0),j=Math.ceil(b.height);g=Math.max(g||0,w),y=Math.max(y||0,j)}return u.remove(),{width:g,height:y}}function wb(n,a,s,l,c){const u=[];for(let m=0;m<n.length;m++){const h=n[m][a],g=h.length;for(let y=0;y<g;y++){const{text:x,vertical:b,collapsed:w,rowspan:j,css:M}=h[y];if(!x){u[y]=Math.max(u[y]||0,l);continue}let k=0;if(b&&!w){let N=`wx-measure-cell-${a}`;if(N+=M?` ${M}`:"",k=Ff(x,N,c).width,(j>1||!h[y+1])&&s>y+1){const A=j||s-y,T=u.slice(y,y+A).reduce((L,O)=>L+O,0);if(T<k){const L=Math.ceil((k-T)/A);for(let O=y;O<y+A;O++)u[O]=(u[O]||l)+L}continue}}u[y]=Math.max(u[y]||l,k)}}return u}function TM(n,a,s){const l=[],c=[];let u="wx-measure-cell-body";u+=n.css?` ${n.css}`:"";for(let m=0;m<a.length;m++){const h=a[m],g=zl(h,n);g&&(l.push(g),n.treetoggle?c.push(a[m].$level*gf+(a[m].$count?gf:0)+(n.draggable?gf:0)):n.draggable&&c.push(gf))}return Ff(l,u,s,c).width}function RM(n,a){const s="wx-measure-cell-header",l=n.sort?AM:0;let c=n.header;if(typeof c=="string")return Ff(c,s,a).width+l;let u;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const h=c[m],g=typeof h=="string"?h:h.text,y=s+(typeof h=="string"?"":` ${h.css}`);let x=Ff(g,y,a).width;m===c.length-1&&(x+=l),u=Math.max(u||0,x)}return u}const EM={text:(n,a)=>n?n.toString().toLowerCase().indexOf(a.toLowerCase())!==-1:!a,richselect:(n,a)=>typeof a!="number"&&!a?!0:n==a,datepicker:(n,a)=>a?n&&LM(n,a):!0,multiselect:(n,a)=>!a||a?.length===0?!0:Array.isArray(n)?n?.some(s=>a.includes(s)):n&&a.includes(n)};function Nw(n){return EM[n]}function DM(n,a){const s=[];for(const l in n){const c=a.find(g=>g.id==l),{config:u,type:m}=c.header.find(g=>g.filter).filter,h=n[l];s.push(g=>{const y=Ol(g,c);return u?.handler?u.handler(y,h):Nw(m)(y,h)})}return l=>{for(let c=0;c<s.length;c++)if(!s[c](l))return!1;return!0}}function LM(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let _M=class extends rM{in;_router;_branches;_xlsxWorker;_historyManager;constructor(a){super({writable:a,async:!1});const s={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new sM(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:u,sizes:m,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((w,j)=>Math.max(j.header.length,w),0),x=g.reduce((w,j)=>Math.max(j.footer.length,w),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,m,y,x,h);for(let w=0;w<g.length;w++)this.normalizeColumns(g,w,"header",y,b),this.normalizeColumns(g,w,"footer",x,b);this.setState({_columns:g,_sizes:b},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{const{data:u,tree:m,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),x=m?this.flattenRows(u,[],g):y?u.filter(w=>y.has(w.id)):u,b=!h&&x.some(w=>w.rowHeight);this.setState({flatData:x,_rowHeightFromData:b},c)}}],{sizes:c=>({...s,...c})});const l=this.in=new iM;l.on("close-editor",({ignore:c})=>{const{editor:u}=this.getState();u&&(c||l.exec("update-cell",u),this.setState({editor:null}))}),l.on("open-editor",({id:c,column:u})=>{let m=this.getState().editor;m&&l.exec("close-editor",{});const h=this.getRow(c),g=u?this.getColumn(u):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;m={column:g.id,id:c,value:Ol(h,g)??"",renderedValue:zl(h,g),type:y.type||y},typeof y=="object"&&y.config&&(m.config=y.config,y.config.options&&(m.options=y.config.options)),g.options&&!m.options&&(m.options=g.options),this.setState({editor:m})}}),l.on("editor",({value:c})=>{let u=this.getState().editor;if(u){u={...u},u.value=c;const m=this.getColumn(u.column),h={...this.getRow(u.id)};_h(h,m,c),u.renderedValue=zl(h,m),this.setState({editor:u})}}),l.on("add-row",c=>{const u=this.getState();let{data:m}=u;const{select:h,_filterIds:g}=u,{row:y,before:x,after:b,select:w}=c;if(c.id=y.id=c.id||y.id||vf(),x||b){const M=x||b,k=m.findIndex(N=>N.id===M);m=[...m],m.splice(k+(b?1:0),0,c.row)}else m=[...m,c.row];const j={data:m};g&&(j._filterIds=[...g,c.id]),this.setState(j),!(typeof w=="boolean"&&!w)&&(w||h)&&l.exec("select-row",{id:y.id,show:!0})}),l.on("delete-row",c=>{const{data:u,selectedRows:m,focusCell:h,editor:g}=this.getState(),{id:y}=c,x={data:u.filter(b=>b.id!==y)};this.isSelected(y)&&(x.selectedRows=m.filter(b=>b!==y)),g?.id===y&&(x.editor=null),this.setState(x),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const u=this.getState();let{data:m}=u;m=[...m];const{tree:h}=u,{id:g,column:y,value:x}=c,b=this.getColumn(y);if(h){const w={...this._branches[g]};_h(w,b,x);const j=this.updateTreeRow(w);w.$parent===0&&(m=j)}else{const w=m.findIndex(M=>M.id===g),j={...m[w]};_h(j,b,x),m[w]=j}this.setState({data:m})}),l.on("update-row",c=>{let{data:u}=this.getState();const{id:m,row:h}=c,g=u.findIndex(y=>y.id===m);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),l.on("select-row",({id:c,toggle:u,range:m,mode:h,show:g,column:y})=>{const x=this.getState(),{focusCell:b}=x;let{selectedRows:w}=x;if(w.length||(m=u=!1),m){const{data:j}=this.getState();let M=j.findIndex(N=>N.id===w[w.length-1]),k=j.findIndex(N=>N.id===c);M>k&&([M,k]=[k,M]),j.slice(M,k+1).forEach(N=>{this.isSelected(N.id)||w.push(N.id)})}else if(u&&this.isSelected(c)){if(h===!0)return;w=w.filter(j=>j!==c)}else if(u){if(h===!1)return;w.push(c)}else w=[c];this.setState({selectedRows:[...w]}),b?.row!==c&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:c,column:y})}),this.in.on("focus-cell",c=>{const{row:u,column:m,eventSource:h}=c,{_columns:g,split:y}=this.getState();u&&m?(this.setState({focusCell:{row:u,column:m}}),h!=="click"&&((!y.left||g.findIndex(x=>x.id===c.column)>=y.left)&&(!y.right||g.findIndex(x=>x.id===c.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:m}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:u,auto:m,maxRows:h,inProgress:g}=c;if(g===!1)return;let y=c.width||0;const x=[...this.getState().columns],b=this.getColumn(u);if(m){if(m==="data"||m===!0){const{flatData:w,_skin:j}=this.getState();let M=w.length;h&&(M=Math.min(h,M));const k=w.slice(0,M);y=TM(b,k,j)}if(m==="header"||m===!0){const{_skin:w}=this.getState();y=Math.max(RM(b,w),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:x})}),l.on("hide-column",c=>{const{id:u,mode:m}=c,h=[...this.getState().columns],g=this.getColumn(u),y=h.reduce((x,b)=>x+(b.hidden?0:1),0);!m||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:u,add:m,sort:h}=c,g=this.getState(),{columns:y,data:x,tree:b}=g;if(h){const T=[...x];T.sort(h),this.setState({data:T});return}const{order:w="asc"}=c;let j=g.sortMarks;const M=Object.keys(j),k=M.length;!m||!k||k===1&&j[u]?j={[u]:{order:w}}:(k===1&&(j[M[0]]={...j[M[0]],index:0}),j={...j,[u]:{order:w,index:typeof m=="number"?m:j[u]?.index??k}});const N=Object.keys(j).sort((T,L)=>j[T].index-j[L].index).map(T=>({key:T,order:j[T].order}));this.setState({sortMarks:j});const A=MM(N,y);if(A){const T=[...x];b?this.sortTree(T,A):T.sort(A),this.setState({data:T})}}),l.on("filter-rows",c=>{const{value:u,key:m,filter:h}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:x,_columns:b}=g;let w=g.filterValues;const j={};m&&(w={...w,[m]:u},j.filterValues=w);const M=h??DM(w,b);let k=[];x?k=this.filterTree(y,M,k):y.forEach(N=>{M(N)&&k.push(N.id)}),j._filterIds=k,this.setState(j)}),l.on("collapse-column",c=>{const{id:u,row:m,mode:h}=c,g=[...this.getState().columns],y=this.getColumn(u).header,x=Array.isArray(y)?y[m]:y;typeof x=="object"&&(x.collapsed=h??!x.collapsed,this.setState({columns:g}))}),l.on("move-item",c=>{const{id:u,inProgress:m}=c;let{target:h,mode:g="after"}=c;const{data:y,flatData:x,tree:b}=this.getState(),w=x.findIndex(k=>k.id===u);let j;if(g==="up"||g==="down"){if(g==="up"){if(w===0)return;j=w-1,g="before"}else if(g==="down"){if(w===x.length-1)return;j=w+1,g="after"}h=x[j]&&x[j].id}else j=x.findIndex(k=>k.id===h);if(w===-1||j===-1||m===!1)return;let M;b||(M=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(M):M})}),l.on("copy-row",c=>{const{id:u,target:m,mode:h="after"}=c,g=this.getState(),{flatData:y,_filterIds:x}=g;let{data:b}=g;const w=this.getRow(u);if(!w)return;const j={...w,id:vf()};c.id=j.id;const M=y.findIndex(N=>N.id===m);if(M===-1)return;b.splice(M+(h==="after"?1:0),0,j),b=[...b];const k={data:b};x&&(k._filterIds=[...x,j.id]),this.setState(k)}),l.on("open-row",c=>{const{id:u,nested:m}=c;this.toggleBranch(u,!0,m)}),l.on("close-row",c=>{const{id:u,nested:m}=c;this.toggleBranch(u,!1,m)}),l.on("export-data",c=>new Promise((u,m)=>{const h=c.format||"csv",g=`${c.fileName||"data"}.${h}`;if(h==="csv"){const y=uM(this.getState(),c.csv||{});c.download!==!1?cM(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):c.result=y,u(!0)}else m()})),l.on("hotkey",({key:c,event:u,isInput:m})=>{switch(c){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(m)return;if(u.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(m)return;if(u.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const x=h.column;let b=h.id,w=this.getNextEditor(this.getRow(b),this.getColumn(x));if(!w){const j=this.getNextRow(b);j&&(b=j.id,w=this.getNextEditor(j))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const x=h.column;let b=h.id,w=this.getPrevEditor(this.getRow(b),this.getColumn(x));if(!w){const j=this.getPrevRow(b);j&&(b=j.id,w=this.getPrevEditor(j))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!m&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:x}=this.getState();if(!h&&g){u.preventDefault();const b=y[0]?.id,w=this._getFirstVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getLastVisibleColumn()?.id,x=g.row;this.in.exec("focus-cell",{row:x,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:x}=this.getState();if(!h&&g){u.preventDefault();const b=y.at(-1).id,w=this._getLastVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),l.on("scroll",c=>{const{_columns:u,split:m,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:x}=this.getState();let b=-1,w=-1,j=0,M=0;if(c.column){b=0;const k=u.findIndex(N=>N.id===c.column);j=u[k].width;for(let N=m.left??0;N<k;N++){const A=u[N];A.hidden||(b+=A.width)}}if(c.row&&!y){const k=g.findIndex(N=>N.id===c.row);k>=0&&(x?(w=g.slice(0,k).reduce((N,A)=>N+(A.rowHeight||h.rowHeight),0),M=g[k].rowHeight):w=h.rowHeight*k)}this.setState({scroll:{top:w,left:b,width:j,height:M||h.rowHeight}})}),l.on("scroll-to",c=>{const u={};c.top!==void 0&&(u.scrollTop=c.top),c.left!==void 0&&(u.scrollLeft=c.left),Object.keys(u).length&&this.setState(u)}),l.on("print",c=>{const u=yM(c);this.setState({_print:u}),this.setStateAsync({_print:null})}),l.on("undo",()=>{this._historyManager?.handleUndo()}),l.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(a){if(!this._xlsxWorker){const s=window.URL.createObjectURL(new Blob([`importScripts('${a}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(l=>{const c=new Worker(s);c.addEventListener("message",u=>{u.data.type==="init"&&l(c)})})}return this._xlsxWorker}initOnce(){const a={sortMarks:{},_filterIds:null,data:[],filterValues:{},scroll:null,scrollLeft:0,scrollTop:0,editor:null,focusCell:null,_print:null,history:{undo:0,redo:0},search:null};this._router.init(a)}init(a){a.hasOwnProperty("_skin")&&!a._skin&&(a._skin=NM()),a.columns&&a.columns.forEach(s=>{s.options&&(s.optionsMap=new Map(s.options.map(l=>[l.id,l.label])))}),Zf(this.getState().data,a.data)||(a.tree?a.data=this.normalizeTreeRows(a.data):a.data=this.normalizeRows(a.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),a.tree&&(a.undo=!1,a.reorder=!1),a.split?.right&&(a.split.right=0),a.undo&&!this._historyManager&&(this._historyManager=new CM(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...a})}setState(a,s){return this._router.setState(a,s)}setStateAsync(a){this._router.setStateAsync(a)}getRow(a){const{tree:s}=this.getState();return s?this._branches[a]:this.getState().data.find(l=>l.id===a)}getRowIndex(a,s){return s||(s=this.getState().flatData),s.findIndex(l=>l.id===a)}getNextRow(a){const s=this.getState().flatData,l=this.getRowIndex(a,s);return s[l+1]}getPrevRow(a){const s=this.getState().flatData,l=this.getRowIndex(a,s);return s[l-1]}getColumn(a){return this.getState().columns.find(s=>s.id===a)}getNextColumn(a,s){const l=this.getState()._columns,c=l.findIndex(u=>u.id===a);return s?this._getFirstVisibleColumn(c+1):l[c+1]}getPrevColumn(a,s){const l=this.getState()._columns,c=l.findIndex(u=>u.id===a);return s?this._getLastVisibleColumn(c-1):l[c-1]}_getFirstVisibleColumn(a){const s=this.getState()._columns;let l=a??0;for(;l<s.length&&(s[l]?.hidden||s[l]?.collapsed);)l++;return s[l]}_getLastVisibleColumn(a){const s=this.getState()._columns;let l=a??s.length-1;for(;l<s.length&&(s[l]?.hidden||s[l]?.collapsed);)l--;return s[l]}isCellEditable(a,s){const{editor:l,hidden:c}=s;return!l||c?!1:typeof l=="function"?l(a,s):!0}getNextEditor(a,s){let l=this.getState().columns;if(s){const c=l.findIndex(u=>u.id===s.id);l=l.slice(c+1)}return l.find(c=>this.isCellEditable(a,c))}getPrevEditor(a,s){let l=this.getState().columns;if(s){const c=l.findLastIndex(u=>u.id===s.id);l=l.slice(0,c)}return l.findLast(c=>this.isCellEditable(a,c))}toggleBranch(a,s,l){let c=this._branches[a],{data:u}=this.getState();if(u=[...u],a!==0){c={...c,open:s};const m=this.updateTreeRow(c);c.$parent===0&&(u=m)}l&&c.data?.length&&c.data.forEach(m=>{const h=this.toggleKids(m,s,l);a===0&&(u=h)}),this.setState({data:u})}toggleKids(a,s,l){a={...a,open:s};const c=this.updateTreeRow(a);return l&&a.data?.length&&a.data.forEach(u=>{this.toggleKids(u,s,l)}),c}updateTreeRow(a){const s=a.id;this._branches[s]=a;const l=this._branches[a.$parent],c=l.data.findIndex(u=>u.id===s);return l.data=[...l.data],l.data[c]=a,l.data}isSelected(a){return this.getState().selectedRows.indexOf(a)!==-1}findAndRemove(a,s){for(let l=0;l<a.length;l++){if(a[l].id===s)return a.splice(l,1)[0];if(a[l].data){const c=[...a[l].data],u=this.findAndRemove(c,s);if(u)return a[l]={...a[l],data:c},u}}return null}insertItem(a,s,l,c){for(let u=0;u<a.length;u++){if(a[u].id===s){const m=a[u],h=c==="before"?u:u+1;if(m.data){if(c==="before"){const g=u>0?a[u-1]:null;return g?.data&&g.open?a[u-1]={...g,data:[...g.data,l]}:a.splice(h,0,l),!0}else if(m.open)return a[u]={...m,data:[l,...m.data]},!0}return a.splice(h,0,l),!0}if(a[u].data&&(a[u]={...a[u],data:[...a[u].data]},this.insertItem(a[u].data,s,l,c)))return!0}return!1}moveItem(a,s,l,c){const u=[...l],m=this.findAndRemove(u,a);return this.insertItem(u,s,m,c),u}copyColumns(a){const s=[];for(let l=0;l<a.length;l++){const c={...a[l]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),s[l]=c}return s}copyHeaderFooter(a,s){let l=a[s];l=Array.isArray(l)?[...l]:[l],l.forEach((c,u)=>{l[u]=typeof c=="string"?{text:c}:{...c}}),a[s]=l}setCollapsibleColumns(a,s,l){let c=a.header;for(let u=0;u<c.length;u++){const m=c[u];if(m.collapsible&&m.collapsed){if(m.collapsible!=="first"){a.collapsed=!0,a.width=36,m.vertical=!0;const g=c.length-u;c=c.slice(0,u+1),c[u].rowspan=g}const h=m.colspan;if(h){const g=c[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let x=y;x<h;x++){const b=l[s+x];b&&(b.hidden=!0)}}}}}normalizeColumns(a,s,l,c,u){const m=a[s];m.width||(m.width=m.flexgrow?17:u.columnWidth),m._colindex=s+1;const h=m[l],g=u[`${l}RowHeights`];for(let y=0;y<c;y++){const x=h[y];x.id=m.id,y===h.length-1&&(x.rowspan=x.rowspan?Math.min(x.rowspan,c-y):c-y);for(let b=1;b<x.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let w=1;w<x.colspan;w++)a[s+w][l].splice(y+b,0,{})}if(x.rowspan){const b=(x.rowspan===c?g:g.slice(y,x.rowspan+y)).reduce((w,j)=>w+j,0);x.height=b,y+x.rowspan!=c&&x.height--}if(x.colspan){let b=m.width,w=m.flexgrow||0;const j=x.colspan;for(let M=1;M<j;M++){const k=a[s+M];k&&(k.hidden?x.colspan-=1:k.flexgrow?w+=k.flexgrow:b+=k.width||u.columnWidth),w?x.flexgrow=w:x.width=b}}else x.width=m.width,x.flexgrow=m.flexgrow;l==="header"&&x.filter&&typeof x.filter=="string"&&(x.filter={type:x.filter})}h.length>c&&(h.length=c),m[l]=h}normalizeRows(a){for(let s=0;s<a.length;s++)a[s].id||(a[s].id=vf());return a}normalizeTreeRows(a,s,l){return!s&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=vf()),c.$level=s||0,c.$parent=l||0,this._branches[c.id]=c,c.data&&(c.data.length?(c.$count=c.data.length,this.normalizeTreeRows(c.data,c.$level+1,c.id)):(delete c.data,delete c.$count,delete c.open))}),a}sortTree(a,s){a.sort(s),a.forEach(l=>{l.data&&this.sortTree(l.data,s)})}filterTree(a,s,l){return a.forEach(c=>{s(c)&&l.push(c.id),c.data&&this.filterTree(c.data,s,l)}),l}flattenRows(a,s,l){const c=s;return a.forEach(u=>{(!l||l.includes(u.id))&&c.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,c,l)}),c}createFilter(a){const{_columns:s}=this.getState(),l=[];for(const c in a){const u=s.find(y=>y.id==c),{config:m,type:h}=u.header.find(y=>y.filter).filter,g=a[c];l.push(y=>{const x=Ol(y,u);return m?.handler?m.handler(x,g):Nw(h)(x,g)})}return c=>{for(let u=0;u<l.length;u++)if(!l[u](c))return!1;return!0}}searchRows(a,s){a=a.trim().toLowerCase();const l={};if(!a)return l;const{flatData:c,columns:u}=this.getState(),m=s?u.filter(h=>s[h.id]):u;return c.forEach(h=>{const g={};m.forEach(y=>{const x=zl(h,y);String(x).toLowerCase().includes(a)&&(g[y.id]=!0)}),Object.keys(g).length&&(l[h.id]=g)}),l}normalizeSizes(a,s,l,c,u){const m=wb(a,"header",l,s.headerHeight,u),h=wb(a,"footer",c,s.footerHeight,u),g=m.reduce((x,b)=>x+b,0),y=h.reduce((x,b)=>x+b,0);return{...s,headerRowHeights:m,footerRowHeights:h,headerHeight:g,footerHeight:y}}},IM=new Date().valueOf();function vf(){return"temp://"+IM++}function zM(n,a="data-id"){let s=n;for(!s.tagName&&n.target&&(s=n.target);s;){if(s.getAttribute&&s.getAttribute(a))return s;s=s.parentNode}return null}new Date().valueOf();var OM=class{constructor(){this.store=new Map}configure(n,a){this.node=a;for(const s in n)if(n[s]){const l=s.toLowerCase().replace(/[ ]/g,""),c=n[s];this.store.set(l,c)}}},jc=[],HM={subscribe:n=>{PM();const a=new OM;return jc.push(a),n(a),()=>{const s=jc.findIndex(l=>l===a);s>=0&&jc.splice(s,1)}}},Sb=!1;function PM(){Sb||(Sb=!0,document.addEventListener("keydown",n=>{if(jc.length&&(n.ctrlKey||n.altKey||n.metaKey||n.shiftKey||n.key.length>1||n.key===" ")){const a=[];n.ctrlKey&&a.push("ctrl"),n.altKey&&a.push("alt"),n.metaKey&&a.push("meta"),n.shiftKey&&a.push("shift");let s=n.code.replace("Key","").toLocaleLowerCase();n.key===" "&&(s="space"),a.push(s);const l=a.join("+");for(let c=jc.length-1;c>=0;c--){const u=jc[c],m=u.store.get(l)||u.store.get(s);m&&u.node.contains(n.target)&&m(n,{key:l,evKey:s})}}}))}const FM={tab:!0,"shift+tab":!0,arrowup:!0,arrowdown:!0,arrowright:!0,arrowleft:!0,enter:!0,escape:!0,f2:!0,home:!0,end:!0,"ctrl+home":!0,"ctrl+end":!0,"ctrl+z":!0,"ctrl+y":!0};function $M(n,{keys:a,exec:s}){if(!a)return;function l(m){const h=m.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||zM(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const h=a[m];typeof h<"u"&&(typeof h=="function"?c[m]=h:h&&(c[m]=g=>{const y=l(g);s({key:m,event:g,isInput:y})}))}const u=HM.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{u()}}}function BM(n,a){let s=null;a.scroll.subscribe(l=>{if(!l||l===s)return;s=l;const{left:c,top:u,height:m,width:h}=l,g=a.getHeight(),y=a.getWidth(),x=a.getScrollMargin();if(u>=0){const b=n.scrollTop;u<b?n.scrollTop=u:u+m>b+g&&(n.scrollTop=u-g+m)}if(c>=0){const b=n.scrollLeft;c<b?n.scrollLeft=c:c+h>b+y-x&&(n.scrollLeft=c-y+h+x)}}),a.scrollLeft?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollLeft-l)>1&&(n.scrollLeft=l)})}),a.scrollTop?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollTop-l)>1&&(n.scrollTop=l)})})}const xr=d.createContext(null);function UM(n,a){const s=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return s.observe(n.parentNode),{destroy(){s.disconnect()}}}const Cb=5,qM=700;function Tf(n){const a=n.getBoundingClientRect(),s=document.body,l=a.top+s.scrollTop-s.clientTop||0,c=a.left+s.scrollLeft-s.clientLeft||0;return{y:Math.round(l),x:Math.round(c),width:n.offsetWidth,height:n.offsetHeight}}function bp(n,a){const s=Tf(a);return{x:n.clientX-s.x,y:n.clientY-s.y}}function GM(n,a){const s=a.current;let l=null,c,u,m=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(c),c=null}function x(_){const G=Rc(_);G&&(l={container:g,sourceNode:_.target,from:Kf(G),pos:bp(_,n)},u=l.pos,b(_))}function b(_){if(!l)return;const G=l.pos=bp(_,n);if(!m){if(!h&&!_?.target?.getAttribute("draggable-data")&&Math.abs(u.x-G.x)<Cb&&Math.abs(u.y-G.y)<Cb)return;if(I(_)===!1)return B()}if(h){const te=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,W=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(_.pageX-te,_.pageY-W)}else l.targetNode=_.target;s.move&&s.move(_,l),g.style.left=-(l.offset?l.offset.x:0)+"px",g.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function w(_){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",m&&s.end&&s.end(_,l),l=u=null,B()}function j(_){s.getReorder&&!s.getReorder()||_.button===0&&(O(_),window.addEventListener("mousemove",M),window.addEventListener("mouseup",k),x(_))}function M(_){b(_)}function k(_){w(_)}function N(_){if(s.getReorder&&!s.getReorder())return;c=setTimeout(()=>{h=!0,x(_.touches[0])},qM),O(_);function G(){c&&y(),_.target.removeEventListener("touchmove",A),_.target.removeEventListener("touchend",G),w(_)}_.target.addEventListener("touchmove",A),_.target.addEventListener("touchend",G),n.addEventListener("contextmenu",T)}function A(_){m?(_.preventDefault(),b(_.touches[0])):c&&y()}function T(_){if(m||c)return _.preventDefault(),!1}function L(_){_.preventDefault()}function O(_){if(!s.getDraggableInfo)return;const{hasDraggable:G}=s.getDraggableInfo();(!G||_.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function I(_){if(m=!0,s.start){if(s.start(_,l)===!1)return!1;n.appendChild(g),document.body.style.cursor="move"}}function B(_){m=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",M),window.removeEventListener("mouseup",k),_&&(n.removeEventListener("mousedown",j),n.removeEventListener("touchstart",N),n.removeEventListener("dragstart",L))}return n.addEventListener("mousedown",j),n.addEventListener("touchstart",N),n.addEventListener("dragstart",L),{destroy(){B(!0)}}}const VM=.004;function WM(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function YM(n,a,s,l){const{node:c,left:u,top:m,bottom:h,sense:g,xScroll:y,yScroll:x}=l,b=bp(n,c);s.scrollState||(s.scrollState=WM());let w=0,j=0;b.x<u+g?w=-1:b.x>a.width-g&&(w=1),b.y<m+Math.round(g/2)?j=-1:b.y>a.height-h-Math.round(g/2)&&(j=1),(s.scrollState.dirX!==w||s.scrollState.dirY!==j)&&(Tw(s),s.scrollState.dirX=w,s.scrollState.dirY=j),(y&&s.scrollState.dirX!==0||x&&s.scrollState.dirY!==0)&&KM(s,l,{x:s.scrollState.dirX,y:s.scrollState.dirY})}function KM(n,a,s){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(QM,15,n,a,s)},250))}function Tw(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function QM(n,a,s){const{x:l,y:c}=s;n.scrollSpeedFactor+=VM,l!==0&&ZM(n,a,l),c!==0&&XM(n,a,c)}function XM(n,a,s){const l=a.node.scrollTop;Rw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*s,"scrollTop",a)}function ZM(n,a,s){const l=a.node.scrollLeft;Rw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*s,"scrollLeft",a)}function Rw(n,a,s){s.node[a]=n}function Jf(n,a,s,l,c,u){const m={};return n&&(m.width=`${n}px`,m.minWidth=`${n}px`),a&&(m.flexGrow=a),u&&(m.height=`${u}px`),s&&(m.position="sticky",s.left&&(m.left=`${l}px`),s.right&&(m.right=`${c}px`)),m}function Ew(n,a,s){let l="";if(n.fixed)for(const c in n.fixed){let u=n.fixed[c]===-1;!u&&n.fixed.leftSize&&a.colspan&&(u=a.colspan+n._colindex-1===n.fixed.leftSize),l+=u?"wx-shadow ":"wx-fixed "}return l+=a.rowspan>1?"wx-rowspan ":"",l+=a.colspan>1?"wx-colspan ":"",l+=a.vertical?"wx-vertical ":"",l+=s?s(n)+" ":"",l}function JM(n){const{row:a,column:s,cellStyle:l=null,columnStyle:c=null,children:u,focusable:m}=n,h=d.useContext(xr),g=ht(h,"focusCell"),y=ht(h,"search"),x=ht(h,"reorder"),b=d.useMemo(()=>y?.rows[a.id]&&y.rows[a.id][s.id],[y,a.id,s.id]),w=d.useMemo(()=>Jf(s.width,s.flexgrow,s.fixed,s.left,s.right),[s.width,s.flexgrow,s.fixed,s.left,s.right]);function j(I,B){let _="wx-cell";return _+=s.fixed?" "+(s.fixed===-1?"wx-shadow":"wx-fixed"):"",_+=I?" "+I(s):"",_+=B?" "+B(a,s):"",_+=s.treetoggle?" wx-tree-cell":"",_}const M=d.useMemo(()=>j(c,l),[c,l,s,a]),k=d.useMemo(()=>typeof s.draggable=="function"?s.draggable(a,s)!==!1:s.draggable,[s,a]),N=d.useRef(null);d.useEffect(()=>{N.current&&m&&g?.row===a.id&&g?.column===s.id&&N.current.focus()},[g,m,a.id,s.id]);const A=d.useCallback(()=>{m&&!g&&h.exec("focus-cell",{row:a.id,column:s.id,eventSource:"focus"})},[h,m,g,a.id,s.id]);function T(I){const B=new RegExp(`(${y.value.trim()})`,"gi");return String(I).split(B).map(_=>({text:_,highlight:B.test(_)}))}const L=d.useMemo(()=>{const I=s.fixed&&s.fixed.left===-1||s.fixed.right===-1,B=s.fixed&&s.fixed.right;return[M,I?"wx-shadow":"",B?"wx-fixed-right":""].filter(Boolean).join(" ")},[M,s]),O=s.cell;return i.jsxs("div",{className:"wx-TSCaXsGV "+L,ref:N,onFocus:A,style:w,"data-row-id":na(a.id),"data-col-id":na(s.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":s._colindex,"aria-readonly":s.editor?void 0:!0,children:[x&&s.draggable?k?i.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):i.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,s.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:`${a.$level*28}px`}}),a.$count?i.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${a.open!==!1?"down":"right"}`}):null]}):null,O?i.jsx(O,{api:h,row:a,column:s,onAction:({action:I,data:B})=>h.exec(I,B)}):u?u():b?i.jsx("span",{children:T(zl(a,s)).map(({highlight:I,text:B},_)=>I?i.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:B},_):i.jsx("span",{children:B},_))}):zl(a,s)]})}function kb(n,a){let s,l;function c(h){s=h.clientX,n.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",u),window.addEventListener("mouseup",m),a&&a.down&&a.down(n)}function u(h){l=h.clientX-s,a&&a.move&&a.move(l)}function m(){n.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",a&&a.up&&a.up(l),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",m)}return n.addEventListener("mousedown",c),{destroy(){n.removeEventListener("mousedown",c)}}}function eA({filter:n,column:a,action:s,filterValue:l}){function c({value:u}){s({value:u,key:a.id})}return i.jsx(Fp,{...n.config??{},value:l,onChange:c})}function tA({filter:n,column:a,action:s,filterValue:l}){const c=d.useContext(xr),u=ht(c,"flatData"),m=d.useMemo(()=>n?.config?.options||a?.options||g(),[n,a,u]),h=d.useMemo(()=>n?.config?.template,[n]);function g(){const b=[];return u.forEach(w=>{const j=Ol(w,a);b.includes(j)||b.push(j)}),b.map(w=>({id:w,label:w}))}function y({value:b}){s({value:b,key:a.id})}function x(b){b.key!=="Tab"&&b.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:x,children:i.jsx(pj,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:y,children:b=>h?h(b):b.label})})}function nA({filter:n,column:a,action:s,filterValue:l}){function c({value:u}){s({value:u,key:a.id})}return i.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:i.jsx(hj,{placeholder:"",clear:!0,...n?.config??{},value:l,onChange:c})})}function Dw(n){const{value:a,options:s=[],placeholder:l="",clear:c=!1,text:u=null,template:m=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:x,onAction:b}=n,[w,j]=gw(a||[]),M=d.useMemo(()=>(w||[]).map(W=>s.find(Y=>Y.id===W)).filter(Boolean),[w,s]),k=d.useRef(null),N=d.useRef(null),[A,T]=d.useState(null),L=()=>{const W=w||[];if(!W.length)return 0;const Y=s.find(F=>W.includes(F.id));return Y?s.indexOf(Y):0};function O(W){N.current=W.navigate,T(()=>W.keydown),y&&W.navigate(L())}d.useEffect(()=>{y&&(k.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function I({id:W}){j(W),x&&x({value:W})}function B(W){W.stopPropagation(),j([]),x&&x({value:[]})}function _(){N.current?.(L())}function G(){N.current?.(null)}function te(W){A?.(W,L())}return i.jsxs("div",{ref:k,className:"wx-multiselect wx-aadNNOwy",onClick:_,onKeyDown:te,tabIndex:0,children:[i.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(M):h?i.jsx(h,{data:M,onAction:b}):u?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):M.length?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:M.map(W=>W.label).join(", ")}):l?i.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:l}):" "}),c&&w?.length?i.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:B}):i.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),i.jsx(Xf,{items:s,onReady:O,onSelect:I,multiselect:!0,checkboxes:!0,value:w||[],onCancel:G,...g,children:({option:W})=>i.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(W):h?i.jsx(h,{data:W,onAction:b}):W.label})})]})}function aA({filter:n,column:a,action:s,filterValue:l}){const c=d.useContext(ra.i18n)?.getGroup("grid")||Ju(Up).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...n?.config||{}}),[n]),m=d.useMemo(()=>u.options||a.options,[u,a]),h=d.useMemo(()=>{const x=l?.length;return x?x<3?l.map(b=>a.optionsMap.get(b)).join(", "):x+" "+c("selected"):""},[l,a,c]);function g({value:x}){s({value:x,key:a.id})}function y(x){x.key!=="Tab"&&x.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:y,children:i.jsx(Dw,{placeholder:"",...u,options:m,value:l||[],text:h,onChange:g})})}const rA={text:eA,richselect:tA,datepicker:nA,multiselect:aA};function sA({filter:n,column:a}){const s=d.useContext(xr),l=ht(s,"filterValues");function c(m){s.exec("filter-rows",m)}const u=d.useMemo(()=>rA[n.type],[n.type]);return i.jsx(u,{filter:n,column:a,action:c,filterValue:l[a.id]})}function iA(n){const{cell:a,column:s,row:l,lastRow:c,sortRow:u,columnStyle:m,bodyHeight:h,hasSplit:g}=n,y=d.useContext(xr),x=ht(y,"sortMarks"),b=d.useMemo(()=>x?x[s.id]:void 0,[x,s.id]),w=d.useRef(),j=d.useCallback(fe=>{w.current=a.flexgrow?fe.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),M=d.useCallback((fe,Q)=>{y.exec("resize-column",{id:a.id,width:Math.max(1,(w.current||0)+fe),inProgress:Q})},[y,a.id]),k=d.useCallback(fe=>M(fe,!0),[M]),N=d.useCallback(fe=>M(fe,!1),[M]),A=d.useCallback(fe=>{if(!s.sort||a.filter)return;let Q=b?.order;Q&&(Q=Q==="asc"?"desc":"asc"),y.exec("sort-rows",{key:a.id,add:fe.ctrlKey||fe.metaKey,order:Q})},[y,a.id,a.filter,s.sort,b?.order]),T=d.useCallback(fe=>{fe&&fe.stopPropagation(),y.exec("collapse-column",{id:a.id,row:l})},[y,a.id,l]),L=d.useCallback(fe=>{fe.key==="Enter"&&T()},[T]),O=d.useCallback(fe=>{fe.key==="Enter"&&!a.filter&&A(fe)},[A,a.filter]),I=d.useMemo(()=>a.collapsed&&s.collapsed,[a.collapsed,s.collapsed]),B=d.useMemo(()=>I&&!g&&a.collapsible!=="header",[I,g,a.collapsible]),_=d.useMemo(()=>B?{top:-h/2,position:"absolute"}:{},[B,h]),G=d.useMemo(()=>Jf(a.width,a.flexgrow,s.fixed,s.left,a.right??s.right,a.height+(I&&B?h:0)),[a.width,a.flexgrow,s.fixed,s.left,a.right,s.right,a.height,I,B,h]),te=d.useMemo(()=>Ew(s,a,m),[s,a,m]),W=d.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([fe])=>fe!=="cell")),[a]),Y=`wx-cell ${te} ${a.css||""} wx-collapsed`,F=["wx-cell",te,a.css||"",a.filter?"wx-filter":"",s.fixed&&s.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),ve=d.useRef(null);return d.useEffect(()=>{const fe=ve.current;if(!fe)return;const Q=kb(fe,{down:j,move:k,up:N});return()=>{typeof Q=="function"&&Q()}},[j,k,N,kb]),I?i.jsx("div",{className:"wx-RsQD74qC "+Y,style:G,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:L,onClick:T,"data-header-id":na(s.id),children:i.jsx("div",{className:"wx-RsQD74qC wx-text",style:_,children:a.text||""})}):i.jsxs("div",{className:"wx-RsQD74qC "+F,style:G,onClick:A,"data-header-id":na(s.id),tabIndex:!a._hidden&&s.sort&&!a.filter?0:void 0,role:"columnheader","aria-colindex":s._colindex,"aria-colspan":a.colspan>1?a.colspan:void 0,"aria-rowspan":a.rowspan>1?a.rowspan:void 0,"aria-sort":!b?.order||a.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:O,children:[a.collapsible?i.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":a.collapsed?"Expand column":"Collapse column","aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:L,onClick:T,children:i.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const fe=a.cell;return i.jsx(fe,{api:y,cell:W(),column:s,row:l,onAction:({action:Q,data:z})=>y.exec(Q,z)})})():a.filter?i.jsx(sA,{filter:a.filter,column:s}):i.jsx("div",{className:"wx-RsQD74qC wx-text",children:a.text||""}),s.resize&&c&&!a._hidden?i.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:ve,onClick:fe=>fe.stopPropagation(),children:i.jsx("div",{})}):null,u?i.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?i.jsxs(i.Fragment,{children:[typeof b.index<"u"?i.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,i.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function lA({cell:n,column:a,row:s,columnStyle:l}){const c=d.useContext(xr),u=d.useMemo(()=>Jf(n?.width,n?.flexgrow,a?.fixed,a?.left,n?.right??a?.right,n?.height),[n?.width,n?.flexgrow,a?.fixed,a?.left,n?.right,a?.right,n?.height]),m=d.useMemo(()=>Ew(a,n,l),[a,n,l]),h=d.useCallback(()=>Object.fromEntries(Object.entries(n||{}).filter(([y])=>y!=="cell")),[n]),g=`wx-6Sdi3Dfd wx-cell ${m||""} ${n?.css||""}`+(a?.fixed&&a?.fixed.right?" wx-fixed-right":"");return i.jsx("div",{className:g,style:u,children:!a?.collapsed&&!n?.collapsed?n?.cell?Mp.createElement(n.cell,{api:c,cell:h(),column:a,row:s,onAction:({action:y,data:x})=>c.exec(y,x)}):i.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:n?.text||""}):null})}function jb({deltaLeft:n,contentWidth:a,columns:s,type:l="header",columnStyle:c,bodyHeight:u}){const m=d.useContext(xr),h=ht(m,"_sizes"),g=ht(m,"split"),y=d.useMemo(()=>h?.[`${l}RowHeights`],[h,l]),x=d.useMemo(()=>{let k=[];if(s&&s.length){const N=s[0][l].length;for(let A=0;A<N;A++){let T=0;k.push([]),s.forEach((L,O)=>{const I={...L[l][A]};T||k[A].push(I),I.colspan>1?T=I.colspan-1:T&&T--})}}return k},[s,l]),b=d.useMemo(()=>g?.left||g?.right,[g]);function w(k){return s.find(N=>N.id===k)}function j(k,N){let A=N;return k.rowspan&&(A+=k.rowspan-1),A===x.length-1}function M(k,N,A){if(!A.sort)return!1;for(let T=x.length-1;T>=0;T--){const L=A.header[T];if(!L.filter&&!L._hidden)return N===T}return j(k,N)}return i.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:x.map((k,N)=>i.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[N]}px`,display:"flex"},role:"row",children:k.map(A=>{const T=w(A.id);return l==="header"?i.jsx(iA,{cell:A,columnStyle:c,column:T,row:N,lastRow:j(A,N),bodyHeight:u,sortRow:M(A,N,T),hasSplit:b},A.id):i.jsx(lA,{cell:A,columnStyle:c,column:w(A.id),row:N},A.id)})},N))})}function oA({overlay:n}){const a=d.useContext(xr);function s(c){return typeof c=="function"}const l=n;return i.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:s(n)?i.jsx(l,{onAction:({action:c,data:u})=>a.exec(c,u)}):n})}function cA(n){const{editor:a,onSave:s,onApply:l}=n,[c,u]=d.useState(a?.value||""),{type:m="text"}=d.useMemo(()=>a?.config||{},[a]),h=d.useRef(null);d.useEffect(()=>{h.current&&h.current.focus()},[]),d.useEffect(()=>{if(!h.current)return;const x=Fs(h.current,()=>s(!0));return()=>x.destroy()},[s]);function g(){h.current&&(u(h.current.value),l(h.current.value))}function y({key:x}){x==="Enter"&&s()}return i.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:m,value:c})}function uA({editor:n,onAction:a,onSave:s,onApply:l,onCancel:c}){const[u,m]=d.useState(n?.value),[h,g]=d.useState(n?.renderedValue),[y,x]=d.useState(n?.options||[]),b=d.useMemo(()=>n?.config?.template,[n]),w=d.useMemo(()=>n?.config?.cell,[n]),j=d.useMemo(()=>n?.config?.dropdown||{},[n]),M=d.useMemo(()=>({trackScroll:!0,...j}),[j]),k=d.useMemo(()=>(y||[]).findIndex(_=>_.id===u),[y,u]),N=d.useRef(null),A=d.useRef(null),T=d.useCallback(_=>{N.current=_.navigate,A.current=_.keydown,N.current(k)},[k,N]),L=d.useCallback(_=>{const G=_?.target?.value??"";g(G);const te=G?(n?.options||[]).filter(W=>(W.label||"").toLowerCase().includes(G.toLowerCase())):n?.options||[];x(te),te.length?N.current(-1/0):N.current(null)},[n]),O=d.useRef(null);d.useEffect(()=>{O.current&&O.current.focus()},[]);const I=d.useRef(s);d.useEffect(()=>{I.current=s},[s]),d.useEffect(()=>{if(!O.current)return;const _=Fs(O.current,()=>I.current(!0));return()=>_.destroy()},[]),d.useEffect(()=>{m(n?.value),g(n?.renderedValue),x(n?.options||[])},[n]);const B=d.useCallback(({id:_})=>{l(_),s()},[l,s]);return i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:O,value:h??"",onChange:L,onKeyDown:_=>A.current?A.current(_,k):void 0}),i.jsx(Xf,{items:y,onReady:T,onSelect:B,...M,onCancel:c,children:({option:_})=>b?b(_):w?i.jsx(w,{data:_,onAction:a}):_.label})]})}function dA({editor:n,onAction:a,onSave:s,onApply:l,onCancel:c}){const[u]=d.useState(()=>n.value||new Date),{template:m,cell:h,dropdown:g={}}=n?.config||{},y=d.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function x({value:M}){l(M),s()}const b=d.useRef(null),[w,j]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!w)return;const M=Fs(w,()=>s(!0));return()=>M.destroy()},[w,s]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:c,onKeyDown:M=>M.preventDefault(),children:m?m(u):h?i.jsx(h,{data:n.value,onAction:a}):i.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:n.renderedValue})}),i.jsx(Pp,{...y,onCancel:c,children:i.jsx("div",{ref:j,className:"wx-lNWNYUb6",children:i.jsx(dw,{value:u,onChange:x,buttons:n.config?.buttons})})})]})}function fA(n){const{editor:a}=n,s=n.onAction??n.onaction,l=n.onSave??n.onsave,c=n.onApply??n.onapply,u=n.onCancel??n.oncancel,m=a.config||{},{dropdown:h={}}=m,g=d.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=d.useState(a.options.find(L=>L.id===a.value)),[x]=d.useState(a.value),[b]=d.useState(a.options),w=d.useMemo(()=>b.findIndex(L=>L.id===x),[b,x]);function j({id:L}){c(L),l()}let M;const[k,N]=d.useState();function A(L){M=L.navigate,N(()=>L.keydown),M(w)}const T=d.useRef(null);return d.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!T.current)return;const L=Fs(T.current,()=>l(!0));return()=>L.destroy()},[l]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:L=>{k(L,w),L.preventDefault()},children:m.template?m.template(y):m.cell?(()=>{const L=m.cell;return i.jsx(L,{data:y,onAction:s})})():i.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),i.jsx(Xf,{items:b,onReady:A,onSelect:j,...g,onCancel:u,children:({option:L})=>m.template?m.template(L):m.cell?(()=>{const O=m.cell;return i.jsx(O,{data:L,onAction:s})})():L.label})]})}function mA(n){const{editor:a,onAction:s,onSave:l,onApply:c}=n,u=a?.config||{},m=a?.options??[],h=a?.value||[],g=a?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function x({value:w}){c(w)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const w=Fs(b.current,()=>l(!0));return()=>w.destroy()},[l]),i.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:i.jsx(Dw,{value:h,options:m,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:x,onAction:s})})}const hA={text:cA,combo:uA,datepicker:dA,richselect:fA,multiselect:mA};function pA({column:n,row:a}){const s=d.useContext(xr),l=ht(s,"editor"),c=d.useCallback((M,k)=>{s.exec("close-editor",{ignore:M}),k&&s.exec("focus-cell",{...k,eventSource:"click"})},[s]),u=d.useCallback(M=>{const k=M?null:{row:l?.id,column:l?.column};c(!1,k)},[l,c]),m=d.useCallback(()=>{c(!0,{row:l?.id,column:l?.column})},[l,c]),h=d.useCallback(M=>{s.exec("editor",{value:M})},[s]),g=d.useCallback(M=>{M.key==="Enter"&&l&&(n.editor.type==="multiselect"?h(l.value):m())},[l,n.editor,m,h]),y=d.useMemo(()=>Jf(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]),x=d.useMemo(()=>{let M=n.editor;if(typeof M=="function"&&(M=M(a,n)),!M)return null;let k=typeof M=="string"?M:M.type;return hA[k]},[n,a]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const w=typeof a.$parent<"u"?"gridcell":"cell",j=typeof a.$parent<"u"?!n.editor:void 0;return i.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:w,"aria-readonly":j,tabIndex:-1,onClick:M=>M.stopPropagation(),onDoubleClick:M=>M.stopPropagation(),onKeyDown:g,children:x?i.jsx(x,{editor:l,onSave:u,onApply:h,onCancel:m,onAction:({action:M,data:k})=>s.exec(M,k)}):null})}function Mb(n){const{columns:a,type:s,columnStyle:l}=n,c=d.useContext(xr),{filterValues:u,_columns:m,_sizes:h}=c.getState();function g(y){return l?" "+l(y):""}return i.jsx(i.Fragment,{children:a.map((y,x)=>i.jsx("tr",{children:y.map(b=>{const w=m.find(k=>k.id===b.id),j=`wx-print-cell-${s}${g(w)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,M=b.cell;return i.jsx("th",{style:vw(Mw(b,h.columnWidth)),className:"wx-Gy81xq2u "+j,rowSpan:b.rowspan,colSpan:b.colspan,children:M?i.jsx(M,{api:c,cell:Object.fromEntries(Object.entries(b).filter(([k])=>k!=="cell")),column:w,row:x}):b.filter?i.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:bM(u,m,b)}):i.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},x))})}function gA(n){const{columns:a,rowStyle:s,columnStyle:l,cellStyle:c,header:u,footer:m,reorder:h}=n,g=d.useContext(xr),{flatData:y,_sizes:x}=g.getState(),b=u&&bb(a,"header",x.headerRowHeights),w=m&&bb(a,"footer",x.footerRowHeights);function j(k,N){let A="";return A+=l?" "+l(N):"",A+=c?" "+c(k,N):"",A}function M(k,N){return typeof N.draggable=="function"?N.draggable(k,N)!==!1:N.draggable}return i.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(k=>k.flexgrow)?"wx-flex-columns":""}`,children:[u?i.jsx("thead",{children:i.jsx(Mb,{columns:b,type:"header",columnStyle:l})}):null,i.jsx("tbody",{children:y.map((k,N)=>i.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(s?" "+s(k):""),style:{height:`${k.rowHeight||x.rowHeight}px`},children:a.map(A=>A.collapsed?null:i.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${j(k,A)}`,style:vw(Mw(A,x.columnWidth)),children:[h&&A.draggable?i.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:M(k,A)?i.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,A.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:k.$level*28+"px"}}),k.$count?i.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${k.open!==!1?"down":"right"}`}):null]}):null,A.cell?(()=>{const T=A.cell;return i.jsx(T,{api:g,row:k,column:A})})():i.jsx("span",{children:zl(k,A)})]},A.id))},N))}),m?i.jsx("tfoot",{children:i.jsx(Mb,{columns:w,type:"footer",columnStyle:l})}):null]})}function vA(n){const{config:a,...s}=n,l=d.useContext(xr),{_skin:c,_columns:u}=l.getState(),m=d.useMemo(()=>pM(u,a),[]),h=d.useRef(null);return d.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const x=y.cloneNode(!0);g.appendChild(x);const b=`@media print { @page { size: ${a.paper} ${a.mode}; }`,w=document.createElement("style");w.setAttribute("type","text/css"),w.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(w),w.appendChild(document.createTextNode(b)),window.print(),w.remove(),g.classList.remove("wx-print"),x.remove()},[]),i.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:h,children:m.map((g,y)=>i.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:i.jsx(gA,{columns:g,...s})},y))})}function yA(n){const{header:a,footer:s,overlay:l,multiselect:c,onreorder:u,rowStyle:m,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:x,clientWidth:b,clientHeight:w,responsiveLevel:j,hotkeys:M}=n,k=d.useContext(xr),N=ht(k,"dynamic"),A=ht(k,"_columns"),T=ht(k,"flatData"),L=ht(k,"split"),O=ht(k,"_sizes"),[I,B]=Pr(k,"selectedRows"),_=ht(k,"select"),G=ht(k,"editor"),te=ht(k,"scrollLeft"),W=ht(k,"scrollTop"),Y=ht(k,"tree"),F=ht(k,"focusCell"),ve=ht(k,"_print"),fe=ht(k,"undo"),Q=ht(k,"reorder"),z=ht(k,"_rowHeightFromData"),[re,V]=d.useState(0);d.useEffect(()=>{V(an())},[]);const[H,le]=d.useState(0),oe=d.useMemo(()=>(A||[]).some(se=>!se.hidden&&se.flexgrow),[A]),X=d.useMemo(()=>O?.rowHeight||0,[O]),be=d.useRef(null),[me,he]=d.useState(null),[J,Ce]=d.useState(null),Te=d.useMemo(()=>{let se=[],Ee=0;return L&&L.left&&(se=(A||[]).slice(0,L.left).filter(Ge=>!Ge.hidden).map(Ge=>({...Ge})),se.forEach(Ge=>{Ge.fixed={left:1,leftSize:L.left},Ge.left=Ee,Ee+=Ge.width}),se.length&&(se[se.length-1].fixed.left=-1)),{columns:se,width:Ee}},[L,A]),He=d.useMemo(()=>{let se=[],Ee=0;if(L&&L.right){se=(A||[]).slice(L.right*-1).filter(Ge=>!Ge.hidden).map(Ge=>({...Ge}));for(let Ge=se.length-1;Ge>=0;Ge--){const pt=se[Ge];pt.fixed={right:1},pt.right=Ee,Ee+=pt.width}se.length&&(se[0].fixed={right:-1})}return{columns:se,width:Ee}},[L,A]),ee=d.useMemo(()=>{const se=(A||[]).slice(L?.left||0,(A||[]).length-(L?.right??0)).filter(Ee=>!Ee.hidden);return se.forEach(Ee=>{Ee.fixed=0}),se},[A,L]),Ue=d.useMemo(()=>(A||[]).reduce((se,Ee)=>(Ee.hidden||(se+=Ee.width),se),0),[A]),ft=1;function ne(se,Ee,Ge){let pt=Ee,Ut=se;if(ee.length){let Wt=ee.length;for(let nt=se;nt>=0;nt--)ee[nt][Ge].forEach(Nt=>{Nt.colspan>1&&nt>se-Nt.colspan&&nt<Wt&&(Wt=nt)});if(Wt!==ee.length&&Wt<se){for(let nt=Wt;nt<se;nt++)pt-=ee[nt].width;Ut=Wt}}return{index:Ut,delta:pt}}const xe=d.useMemo(()=>{let se,Ee,Ge;const pt=te||0,Ut=(te||0)+(b||0);let Wt=0,nt=0,Nt=0,sa=0;ee.forEach((kn,En)=>{pt>Nt&&(Wt=En,sa=Nt),Nt=Nt+kn.width,Ut>Nt&&(nt=En+ft)});const $n={header:0,footer:0};for(let kn=nt;kn>=Wt;kn--)["header","footer"].forEach(En=>{ee[kn]&&ee[kn][En].forEach($s=>{const Bs=$s.colspan;if(Bs&&Bs>1){const Rt=Bs-(nt-kn+1);Rt>0&&($n[En]=Math.max($n[En],Rt))}})});const bn=ne(Wt,sa,"header"),tn=ne(Wt,sa,"footer"),Ve=bn.delta,kt=bn.index,Br=tn.delta,Ht=tn.index;return oe&&Ue>(b||0)?se=Ee=Ge=[...Te.columns,...ee,...He.columns]:(se=[...Te.columns,...ee.slice(Wt,nt+1),...He.columns],Ee=[...Te.columns,...ee.slice(kt,nt+$n.header+1),...He.columns],Ge=[...Te.columns,...ee.slice(Ht,nt+$n.footer+1),...He.columns]),{data:se||[],header:Ee||[],footer:Ge||[],d:sa,df:Br,dh:Ve}},[ee,Te,He,te,b,oe,Ue]),Oe=d.useMemo(()=>a&&O?.headerHeight||0,[a,O]),$e=d.useMemo(()=>s&&O?.footerHeight||0,[s,O]),ze=d.useMemo(()=>b&&w?Ue>=b:!1,[b,w,Ue]),[Qe,qe]=d.useState(!1),We=d.useMemo(()=>(w||0)-Oe-$e-(ze?re:0),[w,Oe,$e,ze,re]),lt=d.useMemo(()=>Math.ceil((We||0)/(X||1))+1,[We,X]),U=d.useRef([]),[ye,je]=d.useState(0),[Fe,ut]=d.useState(void 0),tt=d.useMemo(()=>{let se=0,Ee=0;const Ge=2,pt=W||0;if(y){let nt=pt;for(;nt>0;)nt-=U.current[se]||X,se++;Ee=pt-nt;for(let Nt=Math.max(0,se-Ge-1);Nt<se;Nt++)Ee-=U.current[se-Nt]||X;se=Math.max(0,se-Ge)}else{if(z){let nt=0,Nt=0;for(let tn=0;tn<(T||[]).length;tn++){const Ve=T[tn].rowHeight||X;if(Nt+Ve>pt){nt=tn;break}Nt+=Ve}se=Math.max(0,nt-Ge);for(let tn=0;tn<se;tn++)Ee+=T[tn].rowHeight||X;let sa=0,$n=0;for(let tn=nt+1;tn<(T||[]).length;tn++){const Ve=T[tn].rowHeight||X;if(sa++,$n+Ve>We)break;$n+=Ve}const bn=Math.min(N?N.rowCount:(T||[]).length,nt+sa+Ge);return{d:Ee,start:se,end:bn}}se=Math.floor(pt/(X||1)),se=Math.max(0,se-Ge),Ee=se*(X||0)}const Ut=N?N.rowCount:(T||[]).length,Wt=Math.min(Ut,se+(lt||0)+Ge);return{d:Ee,start:se,end:Wt}},[y,z,W,X,N,T,lt,We]),vt=d.useMemo(()=>{const se=N?N.rowCount:(T||[]).length;if(y)return ye+tt.d+(se-(Fe||0))*(X||0);if(!z)return se*(X||0);let Ee=0;for(let Ge=0;Ge<se;Ge++)Ee+=T[Ge]?.rowHeight||X;return Ee},[N,T,X,y,z,ye,tt.d,Fe]),st=d.useRef({});st.current={clientWidth:b,clientHeight:w,fullHeight:vt,headerHeight:Oe,footerHeight:$e,fullWidth:Ue,SCROLLSIZE:re};const xt=d.useCallback(()=>{const se=st.current;qe(se.clientWidth&&se.clientHeight?se.fullHeight+se.headerHeight+se.footerHeight>=se.clientHeight-(se.fullWidth>=se.clientWidth?se.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const se=requestAnimationFrame(xt);return()=>window.cancelAnimationFrame(se)},[H,xt]),d.useEffect(()=>{xt()},[w,xt]);const pe=d.useMemo(()=>oe&&Ue<=(b||0)?(b||0)-0-(Qe?re:0):Ue,[oe,Ue,b,Qe,re,ze]),Le=d.useMemo(()=>oe&&Ue<=(b||0)?b||0:pe<(b||0)?Ue+(Qe?re:0):-1,[oe,Ue,b,pe,Qe,re]),Pe=d.useRef({});d.useEffect(()=>{if(N&&(Pe.current.start!==tt.start||Pe.current.end!==tt.end)){const{start:se,end:Ee}=tt;Pe.current={start:se,end:Ee},k&&k.exec&&k.exec("request-data",{row:{start:se,end:Ee}})}},[N,tt,k]);const Re=d.useMemo(()=>N?T||[]:(T||[]).slice(tt.start,tt.end),[N,T,tt]),ot=d.useMemo(()=>(I||[]).filter(se=>(Re||[]).some(Ee=>Ee.id===se)),[B,Re]),wt=d.useMemo(()=>tt.start,[tt.start]),De=d.useRef({top:W,left:te});De.current={top:W,left:te};const Hn=d.useCallback(se=>{const Ee=se.target.scrollTop,Ge=se.target.scrollLeft,pt=De.current;(Ee!==pt.top||Ge!==pt.left)&&k.exec("scroll-to",{top:Ee,left:Ge})},[k]),_t=d.useCallback(se=>{se.shiftKey&&se.preventDefault(),be.current&&be.current.focus&&be.current.focus()},[]),Ot=d.useCallback(()=>!!(A||[]).find(se=>!!se.draggable),[A]),$t=d.useRef(null),Pn=d.useRef(null),Fn=d.useRef({dblclick:(se,Ee)=>{const Ge={id:se,column:Xu(Ee,"data-col-id")};k.exec("open-editor",Ge)},click:(se,Ee)=>{if(Ee.target.closest("input")||$t.current)return;const Ge=Xu(Ee,"data-col-id");if(F?.id!==se&&k.exec("focus-cell",{row:se,column:Ge,eventSource:"click"}),_===!1)return;const pt=c&&(Ee.ctrlKey||Ee.metaKey),Ut=c&&Ee.shiftKey;(pt||I.length>1||!I.includes(se))&&k.exec("select-row",{id:se,toggle:pt,range:Ut})},"toggle-row":se=>{const Ee=k.getRow(se);k.exec(Ee.open!==!1?"close-row":"open-row",{id:se})},"ignore-click":()=>!1}),_e=d.useMemo(()=>({top:Oe,bottom:$e,left:Te.width,xScroll:ze,yScroll:Qe,sense:y&&J?J.offsetHeight:Math.max(O?.rowHeight||0,40),node:be.current&&be.current.firstElementChild}),[Oe,$e,Te.width,ze,Qe,y,J,O]);function nn(se,Ee){const{container:Ge,sourceNode:pt,from:Ut}=Ee;if(Ot()&&!pt.getAttribute("draggable-data"))return!1;he(Ut),Y&&k.getRow(Ut).open&&k.exec("close-row",{id:Ut,nested:!0});const Wt=Rc(pt),nt=Wt.cloneNode(!0);nt.classList.remove("wx-selected"),nt.querySelectorAll("[tabindex]").forEach(bn=>bn.setAttribute("tabindex","-1")),Ge.appendChild(nt),Ce(nt);const Nt=(te||0)-xe.d,sa=Qe?re:0;Ge.style.width=Math.min((b||0)-sa,oe&&Ue<=(b||0)?pe:pe-sa)+Nt+"px";const $n=Tf(Wt);Ee.offset={x:Nt,y:-Math.round($n.height/2)},Pn.current||(Pn.current=se.clientY)}function cn(se,Ee){const{from:Ge}=Ee,pt=Ee.pos,Ut=Tf(be.current);pt.x=Ut.x;const Wt=_e.top;if(pt.y<Wt)pt.y=Wt;else{const nt=Ut.height-(ze&&re>0?re:Math.round(_e.sense/2))-_e.bottom;pt.y>nt&&(pt.y=nt)}if(be.current.contains(Ee.targetNode)){const nt=Rc(Ee.targetNode),Nt=nt&&Kf(nt);if(Nt&&Nt!==Ge){Ee.to=Nt;const sa=y?J?.offsetHeight:O?.rowHeight;if(J&&((W||0)===0||pt.y>Wt+sa-1)){const $n=nt.getBoundingClientRect(),bn=Tf(J).y,tn=$n.y,Ve=bn>tn?-1:1,kt=Ve===1?"after":"before",Br=k.getState().flatData,Ht=Math.abs(Br.findIndex(En=>En.id===Ge)-Br.findIndex(En=>En.id===Nt)),kn=Ht!==1?kt==="before"?"after":"before":kt;if(Ht===1&&(Ve===-1&&se.clientY>Pn.current||Ve===1&&se.clientY<Pn.current))return;Pn.current=se.clientY,k.exec("move-item",{id:Ge,target:Nt,mode:kn,inProgress:!0})}}u&&u({event:se,context:Ee})}YM(se,Ut,Ee,_e)}function Da(se,Ee){const{from:Ge,to:pt}=Ee;k.exec("move-item",{id:Ge,target:pt,inProgress:!1}),$t.current=setTimeout(()=>{$t.current=0},1),he(null),Ce(null),Pn.current=null,Tw(Ee)}function an(){const se=document.createElement("div");se.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(se);const Ee=se.offsetWidth-se.clientWidth;return document.body.removeChild(se),Ee}const Fr=d.useMemo(()=>Le>0?{width:`${Le}px`}:void 0,[Le]),Kn=d.useRef(null);function $r(){Promise.resolve().then(()=>{let se=0,Ee=wt;const Ge=Kn.current;Ge&&(Array.from(Ge.children).forEach((pt,Ut)=>{U.current[wt+Ut]=pt.offsetHeight,se+=pt.offsetHeight,Ee++}),je(se),ut(Ee))})}d.useEffect(()=>{Re&&y&&$r()},[Re,y,wt]);let[$,Xe]=d.useState();d.useEffect(()=>{if(F&&(!_||!ot.length||ot.includes(F.row)))Xe({...F});else if(Re.length&&xe.data.length){if(!$||ot.length&&!ot.includes($.row)||Re.findIndex(se=>se.id===$.row)===-1||xe.data.findIndex(se=>se.id===$.column&&!se.collapsed)===-1){const se=ot[0]||Re[0].id,Ee=xe.data.findIndex(Ge=>!Ge.collapsed);Xe(Ee!==-1?{row:se,column:xe.data[Ee].id}:null)}}else Xe(null)},[F]);const dt=d.useRef(null);d.useEffect(()=>{const se=be.current;if(!se)return;const Ee=UM(se,x);return()=>{typeof Ee=="function"&&Ee()}},[x]);const hn=d.useRef({});Object.assign(hn.current,{start:nn,move:cn,end:Da,getReorder:()=>Q,getDraggableInfo:()=>({hasDraggable:Ot()})}),d.useEffect(()=>{const se=be.current;return se?GM(se,hn).destroy:void 0},[Q,be.current]),d.useEffect(()=>{const se=be.current;return se?$M(se,{keys:M!==!1&&{...FM,"ctrl+z":fe,"ctrl+y":fe,...M},exec:Ee=>k.exec("hotkey",Ee)}).destroy:void 0},[k,fe,M]);const Ba=d.useRef({scroll:k.getReactiveState().scroll,scrollLeft:k.getReactiveState().scrollLeft,scrollTop:k.getReactiveState().scrollTop});Ba.current.getWidth=()=>(b||0)-(Qe?re:0),Ba.current.getHeight=()=>We,Ba.current.getScrollMargin=()=>Te.width+He.width,d.useEffect(()=>{BM(dt.current,Ba.current)},[]);const Ii=d.useRef(null);d.useEffect(()=>{const se=Ii.current;if(!se)return;const Ee=[];Ee.push(Fs(se,()=>F&&k.exec("focus-cell",{eventSource:"click"})).destroy),Ee.push(Gj(se,Fn.current)),le(se.clientHeight);const Ge=new ResizeObserver(()=>{le(se.clientHeight)});return Ge.observe(se),Ee.push(()=>Ge.disconnect()),()=>Ee.forEach(pt=>pt())},[]);const wr=`wx-grid ${j?`wx-responsive-${j}`:""}`;return d.useEffect(()=>{F&&(Re.some(se=>se.id===F.row)&&xe.data.some(se=>se.id===F.column&&!se.collapsed)||k.exec("focus-cell",{eventSource:"destroy"}))},[F,Re,xe.data,k]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-4VuBwK2D "+wr,style:{"--header-height":`${Oe}px`,"--footer-height":`${$e}px`,"--split-left-width":`${Te.width}px`,"--split-right-width":`${He.width}px`},children:i.jsx("div",{ref:be,className:"wx-4VuBwK2D wx-table-box",style:Fr,role:Y?"treegrid":"grid","aria-colcount":xe.data.length,"aria-rowcount":Re.length,"aria-multiselectable":Y&&c?!0:void 0,tabIndex:-1,children:i.jsxs("div",{ref:dt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:ze?"scroll":"hidden",overflowY:Qe?"scroll":"hidden"},onScroll:Hn,children:[a?i.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:i.jsx(jb,{contentWidth:pe,deltaLeft:xe.dh,columns:xe.header,columnStyle:h,bodyHeight:We-+s})}):null,i.jsxs("div",{ref:Ii,className:"wx-4VuBwK2D wx-body",style:{width:`${pe}px`,height:`${vt}px`},onMouseDown:se=>_t(se),children:[l?i.jsx(oA,{overlay:l}):null,i.jsx("div",{ref:Kn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${tt.d}px`,paddingLeft:`${xe.d}px`},children:Re.map((se,Ee)=>{const Ge=I.indexOf(se.id)!==-1,pt=me===se.id,Ut="wx-row"+(y?" wx-autoheight":"")+(m?" "+m(se):"")+(Ge?" wx-selected":"")+(pt?" wx-inactive":""),Wt=y?{minHeight:`${se.rowHeight||X}px`}:{height:`${se.rowHeight||X}px`};return i.jsx("div",{className:"wx-4VuBwK2D "+Ut,"data-id":na(se.id),"data-context-id":na(se.id),style:Wt,role:"row","aria-rowindex":Ee,"aria-expanded":se.open,"aria-level":Y?se.$level+1:void 0,"aria-selected":Y?Ge:void 0,tabIndex:-1,children:xe.data.map(nt=>nt.collapsed?i.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},nt.id):G?.id===se.id&&G.column===nt.id?i.jsx(pA,{row:se,column:nt},nt.id):i.jsx(JM,{row:se,column:nt,columnStyle:h,cellStyle:g,reorder:Q,focusable:$?.row===se.id&&$?.column===nt.id},nt.id))},se.id)})})]}),s&&(T||[]).length?i.jsx(jb,{type:"footer",contentWidth:pe,deltaLeft:xe.df,columns:xe.footer,columnStyle:h}):null]})})}),ve?i.jsx(vA,{config:ve,rowStyle:m,columnStyle:h,cellStyle:g,header:a,footer:s,reorder:Q}):null]})}const bA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),xA=d.forwardRef(function({data:n=[],columns:a=[],rowStyle:s=null,columnStyle:l=null,cellStyle:c=null,selectedRows:u,select:m=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:x=null,overlay:b=null,reorder:w=!1,onReorder:j=null,autoRowHeight:M=!1,sizes:k,split:N,tree:A=!1,autoConfig:T=!1,init:L=null,responsive:O=null,sortMarks:I,undo:B=!1,hotkeys:_=null,filterValues:G,...te},W){const Y=d.useRef();Y.current=te;const F=d.useMemo(()=>new _M(yw),[]),ve=d.useMemo(()=>F.in,[F]),fe=d.useRef(null);fe.current===null&&(fe.current=new fw((He,ee)=>{const Ue="on"+bA(He);Y.current&&Y.current[Ue]&&Y.current[Ue](ee)}),ve.setNext(fe.current));const Q=d.useMemo(()=>({getState:F.getState.bind(F),getReactiveState:F.getReactive.bind(F),getStores:()=>({data:F}),exec:ve.exec,setNext:He=>(fe.current=fe.current.setNext(He),fe.current),intercept:ve.intercept.bind(ve),on:ve.on.bind(ve),detach:ve.detach.bind(ve),getRow:F.getRow.bind(F),getColumn:F.getColumn.bind(F)}),[F,ve]),[z,re]=d.useState(0),[V,H]=d.useState(0),[le,oe]=d.useState(null),[X,be]=d.useState(null),me=d.useMemo(()=>{if(T&&!a.length&&n.length){const He=n[0],ee=[];for(let Ue in He)if(Ue!=="id"&&Ue[0]!=="$"){let ft={id:Ue,header:Ue[0].toUpperCase()+Ue.slice(1)};typeof T=="object"&&(ft={...ft,...T}),ee.push(ft)}return ee}return(X&&X.columns)??a},[T,a,n,X]),he=d.useMemo(()=>(X&&X.sizes)??k,[X,k]),J=d.useCallback(He=>{if(re(He.width),H(He.height),O){const ee=Object.keys(O).map(Number).sort((Ue,ft)=>Ue-ft).find(Ue=>He.width<=Ue)??null;ee!==le&&(be(O[ee]),oe(ee))}},[O,le]),Ce=d.useContext(ra.theme),Te=d.useRef(0);return d.useEffect(()=>{if(!Te.current)L&&L(Q);else{const He=F.getState();F.init({data:n,columns:me,split:N||He.split,sizes:he||He.sizes,selectedRows:u||He.selectedRows,dynamic:x,tree:A,sortMarks:I||He.sortMarks,filterValues:G||He.filterValues,undo:B,reorder:w,_skin:Ce,_select:m})}Te.current++},[F,n,me,N,he,u,x,A,I,G,B,w,Ce,m,L,Q]),Te.current===0&&F.init({data:n,columns:me,split:N||{left:0},sizes:he||{},selectedRows:u||[],dynamic:x,tree:A,sortMarks:I||{},filterValues:G||{},undo:B,reorder:w,_skin:Ce,select:m}),d.useImperativeHandle(W,()=>({...Q}),[Q]),i.jsx(xr.Provider,{value:Q,children:i.jsx(Bp,{words:Up,optional:!0,children:i.jsx(yA,{header:g,footer:y,overlay:b,rowStyle:s,columnStyle:l,cellStyle:c,onReorder:j,multiselect:h,autoRowHeight:M,clientWidth:z,clientHeight:V,responsiveLevel:le,resize:J,hotkeys:_})})})});Ip(ir);const aa=d.createContext(null),Vp=d.createContext(null),Wp=d.createContext(null);function wA({children:n}){const a=d.useContext(ra.i18n),s=d.useMemo(()=>a.getGroup("filemanager"),[a]),l=d.useContext(aa),[c]=Pr(l,"panels"),u=ht(l,"activePanel"),m=c[u].path,[h,g]=d.useState(null),[y,x]=d.useState(null),[b,w]=d.useState(""),[j,M]=d.useState(""),[k,N]=d.useState(!1);function A(){const I=b.trim();if(!I){N(!0);return}h.add?l.exec("create-file",{file:{...h.item,name:I},parent:m}):j!==I&&l.exec("rename-file",{id:h.item.id,name:I}),T()}function T(){g(null),N(null),M(""),w("")}function L(){l.exec("delete-files",{ids:y.selected}),x(null)}const O=d.useMemo(()=>({showPrompt(I){const B=I.item.name||(I.item.type==="folder"?s("New folder"):`${s("New file")}.txt`);M(B),w(B),g({...I})},showConfirm(I){x({...I})}}),[s]);return i.jsxs(Vp.Provider,{value:O,children:[i.jsx(wj,{children:n}),h?i.jsx(vp,{title:s(`Enter ${h.item.type} name`),onConfirm:A,onCancel:T,children:i.jsx(Fp,{error:k,select:!0,focus:!0,value:b,onChange:({value:I})=>w(I)})}):null,y?i.jsx(vp,{title:s("Are you sure you want to delete these items:"),onConfirm:L,onCancel:()=>x(null),children:y.selected?i.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((I,B)=>i.jsx("li",{children:I},B))}):null}):null]})}let Ab={"7z":!0,rar:!0,zip:!0,css:!0,html:!0,js:!0,php:!0,md:!0,xml:!0,sql:!0,aif:!0,mid:!0,mp3:!0,waw:!0,wma:!0,doc:!0,docx:!0,txt:!0,avi:!0,mov:!0,mp4:!0,mpeg:!0,mpg:!0,pdf:!0,xls:!0,xlsx:!0,gif:!0,jpg:!0,jpeg:!0,png:!0,psd:!0,tiff:!0,svg:!0,folder:!0,file:!0,multiple:!0,search:!0,none:!0};function SA(n){const a=n.lastIndexOf("."),s=a>0&&a<n.length-1?Math.min(10,n.length-a):Math.min(5,n.length),l=n.slice(0,-s),c=n.slice(-s);return[l,c]}function CA({item:n}){const a=d.useContext(aa),s=d.useContext(ra.i18n).getGroup("filemanager"),l=d.useContext(aa).templates,[c]=Pr(a,"panels"),u=ht(a,"activePanel"),m=ht(a,"mode"),h=c[u].selected,g=d.useMemo(()=>l.preview(n,214,163),[l,n]),y=d.useMemo(()=>l.icon(n,"big"),[l,n]),[x,b]=d.useMemo(()=>SA(n.name),[n.name]);return i.jsx(i.Fragment,{children:n.id==="/wx-filemanager-parent-link"?m!=="search"?i.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:i.jsxs("div",{className:`wx-GAOa4kDV wx-back ${n.navigation?"wx-selected":""}`,"data-id":na("/wx-filemanager-parent-link"),children:[i.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),i.jsx("span",{children:s("Back to parent folder")})]})}):null:i.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(n.id)>=0?"wx-selected":""}`,"data-id":na(n.id),children:[g?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:s("A miniature file preview"),src:g})}):y?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):i.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:i.jsx("i",{className:`wx-GAOa4kDV wxi-${n.type}`})}),n.type==="folder"?i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[i.jsx("span",{className:"wx-GAOa4kDV wx-type",children:s("Folder")}),i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:x}),i.jsx("span",{children:b})]})]}),i.jsx("div",{"data-action-id":na(n.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:x}),i.jsx("span",{children:b})]})}),i.jsx("div",{"data-action-id":na(n.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function Lw(){const n=d.useContext(aa),a=d.useContext(ra.i18n),s=d.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=Pr(n,"panels"),c=ht(n,"activePanel"),u=ht(n,"mode"),m=l[c]._files,h=l[c].selected,g=l[c].path,y=l[c]._crumbs,x=l[c]._selectNavigation,b=d.useCallback((T,L)=>{const O=L&&(L.ctrlKey||L.metaKey),I=L&&L.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(O||I))return;n.exec("select-file",{type:"navigation"});return}let B=T==="body"&&L?null:T;const _=L.target.className.indexOf("wx-more")!==-1||L.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:B,toggle:O&&!_,range:I&&!_,panel:c})},1)},[n,h,c]),w=d.useCallback(()=>{y.length>1&&n.exec("set-path",{id:y[y.length-2].id,panel:c,selected:[y[y.length-1].id]})},[n,y,c]),j=d.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return w();u==="search"&&n.exec("filter-files",{text:""});const L=m.find(O=>O.id===T);L&&(L.type=="folder"?n.exec("set-path",{id:L.id,panel:c}):n.exec("open-file",{id:L.id}))},[n,w,u,m,c]),M=d.useCallback((T,L)=>{(!h?.length||!h.filter(O=>O?.id===T).length>0)&&b(T,L)},[h,b]),k=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:s("Back to parent folder"),navigation:x},...m]:m,[g,s,x,m]),N=d.useRef(null),A=d.useRef();return d.useEffect(()=>{N.current&&(A.current?(A.current.click=b,A.current._dblclick=j,A.current.context=M):(A.current={click:b,dblclick:T=>A.current._dblclick(T),_dblclick:j,context:M},Ec(N.current,A.current)))},[b,j,M]),u=="search"&&!k.length?i.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:i.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:s("Looks like nothing is here")})}):i.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":na("body"),ref:N,children:k.map(T=>i.jsx(CA,{item:T},T.id))})}function Mo({name:n="",spin:a=!1,onClick:s}){return i.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${n} ${a?"wx-spin":""} ${s?"wx-clickable":""}`,onClick:()=>{s&&s()}})}function kA(){const n=d.useContext(ra.i18n).getGroup("filemanager"),a=d.useContext(aa),s=ht(a,"activePanel"),[l]=Pr(a,"panels"),c=d.useMemo(()=>l[s]._crumbs,[l,s]);function u(){a.exec("filter-files",{text:""})}return i.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[i.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[i.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:i.jsx(Mo,{name:"angle-left",onClick:u})}),i.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[n("Search results in")," ",Array.isArray(c)&&c.map((m,h)=>i.jsxs(d.Fragment,{children:[h?"/":null,m.id=="/"?n(m.name):m.name]},h))]})]}),i.jsx(Lw,{})]})}function Ih({narrowMode:n,extraInfo:a}){const s=d.useContext(aa),{preview:l,icon:c}=s.templates,u=d.useContext(ra.i18n),m=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>kc("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=Pr(s,"panels"),x=ht(s,"activePanel"),b=ht(s,"preview"),w=ht(s,"search"),j=d.useMemo(()=>{const _=g&&x!=null&&g[x]?._selected?.length||0;return w&&!_},[w,y,x]),M=d.useMemo(()=>{const _=g&&x!=null?g[x]:null;return _?j?_._files:_._selected:[]},[j,y,x]),k=d.useCallback((_,G)=>(_?`${_} ${m(_>1?"folders":"folder")} `:"")+(G?`${G} ${m(G>1?"files":"file")}`:""),[m]),N=d.useCallback(()=>{s.exec("show-preview",{mode:!b})},[s,b]),A=d.useCallback(_=>_.type==="folder"?m("Folder"):_.ext||m("Unknown file"),[m]),T=d.useMemo(()=>{let _,G,te,W,Y,F,ve,fe;if(M.length===1&&!j){G=M[0],_=G.name;const Q=l(G,400,500);Q?(te=Q,W=""):(W=c(G,"big"),te=""),Y=G.type!=="folder"}else{if(G=Y=null,_="",M.length){let Q=0,z=0,re=0,V=[],H;M.forEach(oe=>{typeof oe.size>"u"&&(H=!0,Q=void 0),H||(Q+=oe.size),V.push(A(oe)),oe.type==="folder"?z++:re++});const le=new Set(V);F=le.size>1?m("multiple"):[...le][0],ve=k(z,re),fe=Q,j||(_=m("Multiple files"))}W=c({type:j?"search":M.length?"multiple":"none"},"big"),te=""}return{name:_,item:G,previewSrc:te,iconSrc:W,showDownloadIcon:Y,type:F,totalCount:ve,totalSize:fe}},[M,j,l,c,m,A,k]),L=d.useCallback(()=>{s.exec("download-file",{id:M[0].id})},[s,M]),O=d.useCallback(async _=>{if(!a||!_)return null;try{return await a(_)}catch(G){return console.log(G),null}},[a]),[I,B]=d.useState(null);return d.useEffect(()=>{let _=!1;return B(null),Promise.resolve(O(T.item)).then(G=>{_||B(G)}).catch(()=>{_||B(null)}),()=>{_=!0}},[O,T.item]),i.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:M&&M.length?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?i.jsx(Mo,{name:"download",onClick:L}):null,n?i.jsx(Mo,{name:"close",onClick:N}):null]})]}),T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${j?"search":"file-multiple-outline"}`})})]}),i.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(j?"Found":"Information")}),i.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:A(T.item)}),typeof T.item.size<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Zu(T.item.size)})]}):null,i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),i.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Count")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Zu(T.totalSize)})]}):null]}),I?Object.entries(I).map(([_,G])=>i.jsxs(Mp.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:_}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:G})]},_)):null]})]})]}):i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:n?i.jsx(Mo,{name:"close",onClick:N}):null})]}),i.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${j?"search":"message-question-outline"}`})}),i.jsx("span",{className:"wx-O0BTtRrH wx-text",children:j?"":m("Select file or folder to view details")})]})})]})})}function _w({panel:n}){const a=d.useContext(aa),s=d.useContext(ra.i18n),l=d.useMemo(()=>s.getGroup("filemanager"),[s]),[c,u]=Pr(a,"panels"),m=d.useMemo(()=>c[n]._files,[u,n]),h=d.useMemo(()=>c[n]._crumbs||[],[u,n]);function g(M){const k=qp(M,h);a.exec("set-path",{id:M,panel:n,...k&&{selected:[k]}})}const[y,x]=d.useState(null);d.useEffect(()=>{m&&x(null)},[m]);function b(){x(!0),a.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{x(null)},5e3)}const w=d.useRef(null),j=d.useRef();return d.useEffect(()=>{j.current?j.current.click=g:(j.current={click:g},Ec(w.current,j.current))},[g]),i.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:w,children:[i.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:i.jsx(Mo,{name:"refresh",spin:!!y,onClick:b})}),h.map((M,k)=>i.jsxs(Mp.Fragment,{children:[k?i.jsx(Mo,{name:"angle-right"}):null,i.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":na(M.id),"data-menu-ignore":"true",children:M.id=="/"?l(M.name):M.name})]},k))]})}function jA({row:n}){const a=d.useContext(ra.i18n),[s]=d.useState(()=>a.getGroup("filemanager")),l=d.useContext(aa).templates,[c]=d.useState(()=>l.icon(n,"small"));return i.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:n.id==="/wx-filemanager-parent-link"?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",s("Back to parent folder")]})]}):i.jsxs(i.Fragment,{children:[c?i.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):i.jsx("i",{className:`wx-qgAqG6sL wxi-${n.type}`}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n.name," "]})]})})}function Iw({children:n}){const a=d.useContext(aa),s=ht(a,"activePanel"),l=d.useContext(Wp),c=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const m=c.current,h=Nk(m,"data-panel");h&&h!=s&&a.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},u.current.dragLeave=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},d.useEffect(()=>{const m=c.current;return l.droparea(m,u.current)},[]),i.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:n})}function xp({panel:n,active:a=!1,onClick:s,onContextMenu:l}){const c=d.useContext(aa),u=d.useContext(ra.i18n),m=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>kc("%d %M %Y",u.getRaw().calendar),[u]),[g]=Pr(c,"panels"),y=g[n].selected,x=g[n].path,b=g[n]._crumbs,w=g[n]._sorts,j=g[n]._selectNavigation,M=g[n]._files,k=d.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:jA},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:F=>typeof F=="number"?Zu(F):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:F=>F?h(F):""}],[m,h]),N=d.useRef(null),A=d.useRef(null),T=d.useMemo(()=>j?["/wx-filemanager-parent-link"]:[...y],[j,y]);function L(F,ve){if(ve&&ve.target&&ve.target.className&&ve.target.className.indexOf("wx-grip")!==-1)return;const fe=ve&&(ve.ctrlKey||ve.metaKey),Q=ve&&ve.shiftKey;if(F==="/wx-filemanager-parent-link"){if(y.length&&(fe||Q))return;c.exec("select-file",{type:"navigation"});return}let z=F==="body"&&ve?null:F;!N.current&&!A.current?c.exec("select-file",{id:z,toggle:fe,range:Q,panel:n}):(N.current=null,A.current=null)}function O(){b.length>1&&c.exec("set-path",{id:b[b.length-2].id,panel:n,selected:[b[b.length-1].id]})}function I(F){if(F==="/wx-filemanager-parent-link")return O();const ve=M.find(fe=>fe.id===F);ve&&(ve.type==="folder"?c.exec("set-path",{id:ve.id,panel:n}):c.exec("open-file",{id:ve.id}))}function B(F){const ve=F.key,fe=w[x];let Q=fe?"asc":"desc";fe&&fe.key===ve&&(Q=fe.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:ve,order:Q,panel:n,path:x})}function _(F){F.intercept("sort-rows",ve=>(N.current=!0,B(ve),!1)),F.intercept("select-row",()=>!1),F.on("resize-column",()=>A.current=!0),F.intercept("hotkey",()=>!1)}const G=d.useMemo(()=>x!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...M]:M,[x,M,m]),te=d.useMemo(()=>{if(G&&w&&w[x]){const{key:F,order:ve}=w[x];return{[F]:{order:ve}}}},[G,w,x]),W=d.useRef(null),Y=d.useRef();return d.useEffect(()=>{Y.current?(Y.current.click=L,Y.current._dblclick=I):(Y.current={click:L,dblclick:F=>Y.current._dblclick(F),_dblclick:I},Ec(W.current,Y.current))},[L,I]),i.jsxs("div",{onClick:s,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[i.jsx(_w,{panel:n}),i.jsx("div",{"data-id":na("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:W,children:i.jsx(Iw,{children:i.jsx(xA,{init:_,data:G,columns:k,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:te})})})]})}function MA(){const n=d.useContext(aa),a=ht(n,"activePanel");function s(l){n.exec("set-active-panel",{panel:l})}return i.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":na("body"),children:[i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:i.jsx(xp,{panel:0,active:a==0,onClick:()=>s(0),onContextMenu:()=>s(0)})}),i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:i.jsx(xp,{panel:1,active:a==1,onClick:()=>s(1),onContextMenu:()=>s(1)})})]})}function zw({folderIcon:n=!1,folder:a={}}){const s=d.useContext(aa),[l,c]=Pr(s,"panels"),u=ht(s,"activePanel"),m=d.useMemo(()=>l[u].path,[c,u]),h=d.useContext(ra.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!a.data?.find(j=>j.type==="folder"),[a]),x=d.useMemo(()=>a.id=="/"?g(a.name):a.name,[a,g]),b=d.useMemo(()=>a.$level>1?(a.$level-1)*20:0,[a]),w=a.open;return i.jsxs(i.Fragment,{children:[i.jsxs("li",{"data-id":na(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?i.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${w?"angle-down":"angle-right"}`,"data-action":"toggle"}):i.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),i.jsx("i",{className:"wx-NYfhvGIt "+(n||"wxi-folder")}),i.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",x," "]})]}),w&&a.data&&a.data.length&&y?i.jsx(i.Fragment,{children:a.data.map(j=>j.type==="folder"?i.jsx(zw,{folder:j},j.id):null)}):null]})}function AA(){const n=d.useContext(aa),[a,s]=Pr(n,"data"),[l,c]=Pr(n,"panels"),u=ht(n,"activePanel"),m=d.useMemo(()=>l[u]._crumbs,[c,u]),h=d.useCallback(j=>{n.exec("open-tree-folder",{id:j,mode:!a.byId(j).open})},[n,s]),g=d.useCallback(j=>{const M=qp(j,m);n.exec("set-path",{id:j,panel:u,...M&&{selected:[M]}})},[n,m,u]),[y,x]=d.useState([]);d.useEffect(()=>{x(a.byId(0).data)},[s]);const b=d.useRef(null),w=d.useRef();return d.useEffect(()=>{w.current?(w.current.click=g,w.current.toggle=h):(w.current={click:g,toggle:h},Ec(b.current,w.current))},[g,h]),i.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(j=>j.type==="folder"?i.jsx(zw,{folder:j},j.id):null)})}function NA(){const n=d.useContext(aa),a=d.useContext(ra.i18n),s=d.useMemo(()=>a.getGroup("filemanager"),[a]),l=ht(n,"drive"),c=l?l.used:"",u=l?l.total:"";return c&&u?i.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[i.jsx("progress",{value:c,max:u,className:"wx-DetSyKGG wx-progress"}),i.jsxs("p",{children:[Zu(c)," ",s("of")," ",Zu(u)," ",s("used")]})]}):null}function TA({option:n}){const a=d.useContext(ra.i18n).getGroup("filemanager"),s=d.useContext(Wp),l=d.useCallback(()=>{s.open({})},[s]);return i.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:l,children:i.jsx("span",{children:a(n.text)})})}function RA({readonly:n,menuOptions:a}){const s=d.useContext(ra.i18n).getGroup("filemanager"),{showPrompt:l}=d.useContext(Vp);d.useEffect(()=>{Yj("upload",TA)},[]);function c({action:m}){m&&(m.id==="add-file"?l({item:{type:"file",size:0,date:new Date},add:!0}):m.id==="add-folder"&&l({item:{type:"folder",date:new Date},add:!0}))}const u=d.useMemo(()=>a("add").map(m=>(m.text=s(m.text),m)),[a,s]);return i.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!n&&i.jsx("div",{className:"wx-FlucfALM wx-button",children:i.jsx(Qj,{options:u,at:"bottom-fit",onClick:c,children:i.jsx(Gu,{type:"primary block",children:s("Add New")})})}),i.jsx("div",{className:"wx-FlucfALM wx-tree",children:i.jsx(AA,{})}),i.jsx(NA,{})]})}function EA({value:n="",onSearch:a}){const[s,l]=gw(n),c=d.useContext(ra.i18n).getGroup("filemanager"),u=d.useRef(null),m=d.useMemo(()=>s!==""?"wxi-close":"wxi-search",[s]);function h(y){const x=y.target.value;l(x),a&&a({value:x})}function g(){l(""),u.current&&u.current.focus(),a&&a({value:""})}return i.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[i.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${m}`,onClick:g}),i.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:s,onInput:h,placeholder:c("Search")})]})}function DA({narrowMode:n=!1,onShowTree:a}){const s=d.useContext(aa),l=d.useContext(ra.i18n).getGroup("filemanager"),c=ht(s,"mode"),u=ht(s,"preview"),m=ht(s,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){s.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),s.exec("show-preview",{mode:!u})}function x(b){s.exec("filter-files",{text:b.value})}return i.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[i.jsxs("div",{className:"wx-5PZQQztG wx-left "+(n?"wx-left-narrow":""),children:[n?c==="panels"||c==="search"?null:i.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":na("toggle-tree"),children:i.jsx(Mo,{onClick:()=>a&&a(),name:"subtask"})}):i.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),i.jsx(EA,{onSearch:x,value:m})]}),i.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[n?null:i.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:i.jsx(Sj,{onClick:y,value:u,children:i.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),i.jsx("div",{className:"wx-5PZQQztG wx-modes",children:i.jsx(gj,{value:c,options:h,onChange:g})})]})]})}function LA(){const n=d.useContext(aa),a=ht(n,"activePanel");return i.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[i.jsx(_w,{panel:a}),i.jsx(Iw,{children:i.jsx(Lw,{})})]})}function _A({readonly:n=!1,menuOptions:a,extraInfo:s}){const l=d.useRef(null),c=d.useRef(null),[u,m]=d.useState(void 0),[h,g]=d.useState(void 0),[y,x]=d.useState(!1),b=Cw(),w=d.useContext(aa),{showPrompt:j,showConfirm:M}=d.useContext(Vp),k=d.useContext(ra.i18n),N=d.useMemo(()=>k.getGroup("filemanager"),[k]),A=ht(w,"mode"),T=ht(w,"preview"),L=ht(w,"activePanel"),[O,I]=Pr(w,"panels"),B=d.useMemo(()=>(O&&L!=null?O[L]:null)?.selected??[],[I,L]),_=d.useMemo(()=>(O&&L!=null?O[L]:null)?.path,[I,L]),[G,te]=d.useState([]);d.useEffect(()=>{const le=l.current;if(!le)return;const oe=new ResizeObserver(X=>{const be=X[0]?.borderBoxSize?.[0]?.inlineSize;typeof be=="number"&&g(be<768)});return oe.observe(le),()=>{oe.disconnect()}},[]);const W=d.useCallback(()=>{x(le=>!le)},[]),Y=d.useCallback(le=>{h&&Xu(le)!=="toggle-tree"&&x(!1)},[h]);d.useEffect(()=>{const le=c.current;if(le)return Fs(le,Y).destroy},[Y]),d.useEffect(()=>{const le=c.current;if(!le)return;const oe=new ResizeObserver(()=>{le&&m(le.clientWidth)});return oe.observe(le),le&&m(le.clientWidth),()=>{oe.disconnect()}},[]);const F=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ve=d.useCallback(le=>{let oe=h?[F]:[];return le==="file"&&(oe=[...oe,...a().filter(X=>X.id==="download")]),oe},[h,F,a]),fe=d.useRef(null),Q=d.useCallback((le,oe,X)=>{const be=X?[oe.id]:B;switch(le){case"download":w.exec("download-file",{id:oe.id});break;case"copy":case"move":fe.current={action:le,ids:be};break;case"paste":fe.current&&w.exec(fe.current.action==="copy"?"copy-files":"move-files",{ids:fe.current.ids,target:oe?.type==="folder"?oe.id:_});break;case"rename":j({item:oe});break;case"delete":M({selected:be});break;case"preview":w.exec("show-preview",{mode:!T});break}},[w,B,_,j,M,T]),z=d.useCallback(()=>O?.[L],[O,L]);d.useEffect(()=>{const le=l.current;if(!le)return;const oe=Oj(le,{api:w,menuOptions:n?ve:a,performAction:Q,getPanel:z});return()=>{typeof oe=="function"?oe():oe&&typeof oe.destroy=="function"&&oe.destroy()}},[w,n,ve,a,Q,z]);const re=d.useCallback((le,oe)=>{const X=le?w.getFile(le):null,be=oe.target.closest(".tree-item.folder");let me;if(n)me=ve(X?.type);else{switch(le){case"body":me=a(le);break;default:if(X)if(!be&&B.length>1)me=h?[F,...a("multiselect")]:a("multiselect");else if(le==="/")me=a("folder",X).filter(he=>he.id==="paste");else{const he=a(X.type,X);he&&(me=h?[F,...he]:he)}}A==="search"&&(me=me?.filter(he=>he.id!=="paste"))}if(X?.id&&(!B.length||!B.some(he=>he===X.id))&&!be&&w.exec("select-file",{id:X.id}),me?.length)return me.forEach(he=>{be&&(he.hotkey=""),he.text&&(he.text=N(he.text)),he.hotkey&&(he.subtext=he.hotkey)}),te(me),X||{}},[w,n,ve,a,B,h,F,A,N]),V=d.useCallback(le=>{const{action:oe,context:X}=le;oe&&Q(oe.id,X,!oe.hotkey)},[Q]);async function H(le){await Promise.resolve();const{name:oe,size:X}=le.file;w.exec("create-file",{file:{name:oe,size:X,date:new Date,file:le.file},parent:_})}return i.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:h&&T?i.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:i.jsx(Ih,{narrowMode:h,extraInfo:s})}):i.jsxs(i.Fragment,{children:[i.jsx(DA,{narrowMode:h,onShowTree:W}),i.jsx(Xj,{dataKey:"id",at:"point",options:G,resolver:re,onClick:V,children:i.jsxs(Sw,{dataKey:"actionId",options:G,resolver:re,onClick:V,children:[i.jsx(nM,{data:b,apiOnly:!0,uploadURL:H}),i.jsx(Wp.Provider,{value:b,children:i.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:A!=="panels"&&A!=="search"?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:i.jsx(RA,{readonly:n,menuOptions:a})}),i.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":na("body"),children:A==="table"?i.jsx(xp,{panel:L}):i.jsx(LA,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(Ih,{extraInfo:s})}):null]})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:A==="panels"?i.jsx(MA,{}):i.jsx(kA,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(Ih,{extraInfo:s})}):null]})})})]})})]})})}const IA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function zA(n,a){const{type:s,ext:l}=n;if(s==="folder")return!1;let c;return s&&s!=="file"&&Ab[s]?c=s:l?c=Ab[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const OA=d.forwardRef(function(n,a){const{data:s=[],mode:l="cards",drive:c=null,preview:u=!1,panels:m=null,activePanel:h=0,readonly:g=!1,menuOptions:y=_j,extraInfo:x=null,init:b=null,icons:w=zA,previews:j=null,...M}=n,k=d.useRef();k.current=M;const N=d.useMemo(()=>new Lj(yw),[]),A=d.useMemo(()=>N.in,[N]),T=d.useRef(null);T.current===null&&(T.current=new fw((I,B)=>{const _="on"+IA(I);k.current&&k.current[_]&&k.current[_](B)}),A.setNext(T.current));const L=d.useMemo(()=>({getState:N.getState.bind(N),getReactiveState:N.getReactive.bind(N),getStores:()=>({data:N}),exec:A.exec,setNext:I=>(T.current=T.current.setNext(I),T.current),intercept:A.intercept.bind(A),on:A.on.bind(A),detach:A.detach.bind(A),getFile:N.getFile.bind(N),serialize:N.serialize.bind(N),templates:{preview:j||(()=>null),icon:w==="simple"?(()=>null):w}}),[N,A]),O=d.useRef(0);return d.useEffect(()=>{if(!O.current)b&&b(L);else{const I=N.getState();N.init({data:s,mode:l,drive:c,preview:u,panels:m||I.panels||[],activePanel:h})}O.current++},[N,s,l,c,u,m,h,b,L]),O.current===0&&N.init({data:s,mode:l,drive:c,preview:u,panels:m||[],activePanel:h}),d.useImperativeHandle(a,()=>({...L}),[L]),i.jsx(aa.Provider,{value:L,children:i.jsx(Bp,{words:Up,optional:!0,children:i.jsx(wA,{children:i.jsx(_A,{readonly:g,menuOptions:y,extraInfo:x})})})})});function HA({fonts:n=!0,children:a}){return a?i.jsx(fb,{fonts:n,children:a}):i.jsx(fb,{fonts:n})}Ip(ir);function Yp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function ed(n,a,s){const l=Yp(n,s);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${s} response: ${a} must be an array.`);return l[a]}function PA(n,a,s){const l=Yp(n,s);if(!l[a]||typeof l[a]!="object"||Array.isArray(l[a]))throw new Error(`Invalid Hub ${s} response: ${a} must be an object.`);return l[a]}async function FA(n,a=!1){return ed(await Ye(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function zh(n,a){const s=await Ye(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:PA(s,"folder","filesystem entries"),entries:ed(s,"entries","filesystem entries")}}async function $A(n,a){return Ye("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function BA(n,a,s,l){return Ye("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:s})},l)}async function UA(n,a=!1){const s=await Ye(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:ed(s,"jobs","file transfer jobs")}}async function qA(n,a){return Ye(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function GA(n,a){return Ye(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function Nb(n){return ed(await Ye("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function VA(n,a){return Ye("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function WA(n,a,s){return Ye(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},s)}async function YA(n,a){return Ye(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function KA(n,a,s,l){const c=await Ye(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:s})},l),u=Yp(c,"shared folder sync");return{ok:u.ok===!0,jobs:ed(c,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function QA(n){return{id:String(n.id),parentId:n.parent,name:n.name,type:n.type==="file"?"file":"folder",size:Number(n.size||0),modifiedAt:n.date?.toISOString()||null,displayPath:String(n.displayPath||n.name),hasChildren:n.lazy===!0||!!n.data?.length,locked:n.locked===!0}}function Tb(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let s=n,l=0;for(;s>=1024&&l<a.length-1;)s/=1024,l+=1;return`${s.toFixed(l===0||s>=100?0:1)} ${a[l]}`}function Rf(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function XA(n){const a=n.filter(s=>Rf(s)==="local");return a.find(s=>/\bC:/i.test(`${s.name} ${s.displayPath||""}`))||a[0]||n[0]||null}function ZA({hubUrl:n,roots:a,loading:s,error:l,onRefreshRoots:c,onImportFiles:u,onImportFolder:m,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:x}){const b=d.useRef(null),w=d.useRef("/"),j=d.useRef(0),M=d.useRef([]),k=d.useRef(new Map),[N,A]=d.useState(null),[T,L]=d.useState([]),[O,I]=d.useState([]),[B,_]=d.useState(0),[G,te]=d.useState(null),[W,Y]=d.useState(!1),[F,ve]=d.useState(""),[fe,Q]=d.useState(new Set),z=a.find(ne=>ne.id===N)||null,re=T[T.length-1]||null,V=z?re?.svarPath||`/${z.name}`:null,H=V;d.useEffect(()=>{M.current=T,w.current=H||"/"},[H,T]);const le=d.useMemo(()=>(k.current.clear(),!z||!H||T.length===0?[]:(T.forEach(ne=>k.current.set(ne.svarPath,ne.hubId)),[...T.map((ne,xe)=>({id:ne.svarPath,parent:xe===0?"/":T[xe-1].svarPath,type:"folder",name:ne.name,date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:!1})),...O.map(ne=>{const xe=`${H}/${ne.name}`;return k.current.set(xe,ne.id),{id:xe,parent:H,name:ne.name,type:ne.type==="file"?"file":"folder",...ne.type==="file"?{size:ne.size}:{},date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:ne.type!=="file"&&ne.hasChildren===!0,displayPath:ne.displayPath,locked:ne.locked,driveType:ne.driveType,totalBytes:ne.totalBytes,freeBytes:ne.freeBytes}})])),[z,O,H,T]),oe=ne=>k.current.get(String(ne))||String(ne),X=ne=>QA({...ne,id:oe(String(ne.id)),parent:oe(String(ne.parent))}),be=async(ne,xe)=>{const Oe=ne[ne.length-1];if(!Oe)return;const $e=++j.current;Y(!0),ve("");try{const ze=await zh(Oe.hubId,n);if($e!==j.current)return;if(!Array.isArray(ze.entries))throw new Error("Invalid Hub filesystem entries response.");const Qe={...Oe,displayPath:ze.folder.displayPath||Oe.displayPath,modifiedAt:ze.folder.modifiedAt||Oe.modifiedAt},qe=[...ne.slice(0,-1),Qe];M.current=qe,L(qe),I(ze.entries),_(We=>We+1)}catch(ze){if($e!==j.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Oe.hubId,error:ze}),ve(ze instanceof Error?`${xe}: ${ze.message}`:`${xe}: Unable to read this folder.`)}finally{$e===j.current&&Y(!1)}},me=async ne=>{const xe={svarPath:`/${ne.name}`,hubId:ne.id,name:ne.name,displayPath:ne.displayPath,modifiedAt:ne.modifiedAt},Oe=++j.current;A(ne.id),M.current=[xe],L([xe]),w.current=xe.svarPath,I([]),ve(""),Y(!0),te(ne.id),Q($e=>{const ze=new Set($e);return ze.delete(ne.id),ze});try{const $e=await zh(ne.id,n);if(Oe!==j.current)return;if(!Array.isArray($e.entries))throw new Error("Invalid Hub filesystem entries response.");const ze={...xe,displayPath:$e.folder.displayPath||xe.displayPath,modifiedAt:$e.folder.modifiedAt||xe.modifiedAt};M.current=[ze],L([ze]),I($e.entries),_(Qe=>Qe+1)}catch($e){if(Oe!==j.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ne.id,error:$e}),Q(ze=>new Set(ze).add(ne.id)),ve($e instanceof Error?`${ne.name}: ${$e.message}`:`${ne.name}: Unable to read this drive.`),x($e instanceof Error?`${ne.name}: ${$e.message}`:`${ne.name}: Unable to read this drive.`)}finally{Oe===j.current&&(te(null),Y(!1))}},he=ne=>{const xe=M.current;ne<0||ne>=xe.length||ne===xe.length-1||be(xe.slice(0,ne+1),xe[ne].name)},J=(ne,xe)=>{if(ne.type!=="folder")return;const Oe=M.current,$e=Oe.findIndex(Qe=>Qe.svarPath===xe);if($e<0)return;const ze={svarPath:`${xe}/${ne.name}`,hubId:ne.id,name:ne.name,displayPath:ne.displayPath,modifiedAt:ne.modifiedAt};be([...Oe.slice(0,$e+1),ze],ne.name)},Ce=()=>he(M.current.length-2),Te=ne=>{if(ne.key!=="Enter"&&ne.code!=="Enter"&&ne.code!=="NumpadEnter"||ne.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Oe=b.current;if(!Oe)return;const $e=Oe.getState().panels?.flatMap(Qe=>Qe.selected||[])||[];if($e.length!==1)return;const ze=Oe.getFile(String($e[0]));ze?.type==="folder"&&(ne.preventDefault(),ne.stopPropagation(),J(X(ze),String(ze.parent||w.current)))};d.useEffect(()=>{const ne=a.find(xe=>xe.id===N)||XA(a);if(Q(xe=>new Set([...xe].filter(Oe=>a.some($e=>$e.id===Oe)))),!ne){A(null),M.current=[],L([]),I([]);return}me(ne)},[a]);const He=ne=>{b.current=ne,ne.on("request-data",async({id:xe})=>{const Oe=String(xe),$e=oe(Oe);try{const ze=await zh($e,n);if(!Array.isArray(ze.entries))throw new Error("Invalid Hub filesystem entries response.");const Qe=ze.entries.map(qe=>{const We=`${Oe}/${qe.name}`;return k.current.set(We,qe.id),{id:We,parent:Oe,name:qe.name,type:qe.type==="file"?"file":"folder",...qe.type==="file"?{size:qe.size}:{},date:qe.modifiedAt?new Date(qe.modifiedAt):void 0,lazy:qe.type!=="file"&&qe.hasChildren===!0,displayPath:qe.displayPath,locked:qe.locked,driveType:qe.driveType,totalBytes:qe.totalBytes,freeBytes:qe.freeBytes}});await ne.exec("provide-data",{id:Oe,data:Qe})}catch(ze){console.error("[LiveDesk FS] nested getEntries failed",{id:$e,error:ze}),x(ze instanceof Error?ze.message:"Unable to read this folder.")}}),ne.intercept("set-path",({id:xe})=>{const Oe=String(xe),$e=M.current.findIndex(Qe=>Qe.svarPath===Oe);if($e>=0)return he($e),!1;const ze=ne.getFile(Oe);if(ze?.type==="folder")return J(X(ze),String(ze.parent||w.current)),!1}),ne.intercept("open-file",()=>!1),ne.on("select-file",()=>{window.setTimeout(()=>{const $e=(ne.getState().panels?.flatMap(ze=>ze.selected||[])||[]).map(ze=>ne.getFile(ze)).filter(Boolean).map(ze=>X(ze));h($e.map(ze=>ze.id),$e)},0)})},ee=(ne,xe)=>{const Oe=xe?X(xe):null,$e=()=>{const ze=Oe?.type==="file"?String(xe?.parent||w.current):String(xe?.id||w.current);b.current?.exec("request-data",{id:ze})};return ne==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:$e},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x("Select a file or folder to view its properties.")}]:ne==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Qe=>Qe.selected||[])||[]).forEach(Qe=>{const qe=b.current?.getFile(Qe);qe&&g(X(qe))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:$e}]:Oe?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Oe)},...Oe.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(Oe)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{jf(Oe.displayPath||Oe.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:$e},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x(`${Oe.name}
|
|
14
14
|
${Oe.displayPath||""}`)}]:[]},Ue=async()=>{try{await c()}catch(ne){x(ne instanceof Error?ne.message:"Unable to refresh Hub drives.")}},ft=[{id:"local",label:"Local drives",icon:wo,roots:a.filter(ne=>Rf(ne)==="local")},{id:"removable",label:"Removable drives",icon:T0,roots:a.filter(ne=>Rf(ne)==="removable")},{id:"network",label:"Network drives",icon:Ap,roots:a.filter(ne=>Rf(ne)==="network")}];return i.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[i.jsxs("div",{className:"hub-file-explorer-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub file explorer"}),i.jsxs("strong",{children:[i.jsx(wo,{size:16})," Browse files on this Hub"]})]}),i.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[i.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:i.jsx(vx,{size:16})}),i.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:i.jsx(R0,{size:16})}),i.jsx("button",{className:"icon-button",onClick:()=>{Ue()},title:"Refresh drives",type:"button",children:i.jsx(Ac,{size:16})})]})]}),s?i.jsxs("div",{className:"hub-file-explorer-state",children:[i.jsx(wo,{size:24}),i.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?i.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[i.jsx(Di,{size:24}),i.jsx("strong",{children:l})]}):i.jsxs("div",{className:"hub-file-explorer-content",children:[i.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[i.jsxs("div",{className:"hub-drive-sidebar-title",children:[i.jsx(wo,{size:15}),i.jsx("strong",{children:"This PC"})]}),ft.map(ne=>ne.roots.length>0&&i.jsxs("section",{className:"hub-drive-group",children:[i.jsxs("h3",{children:[i.jsx(ne.icon,{size:13}),ne.label]}),i.jsx("div",{className:"hub-drive-list",children:ne.roots.map(xe=>{const Oe=ne.icon,$e=fe.has(xe.id)||xe.locked===!0;return i.jsxs("button",{className:`hub-drive-item ${N===xe.id?"active":""} ${$e?"unavailable":""}`,onClick:()=>{me(xe)},"aria-pressed":N===xe.id,type:"button",children:[i.jsx("span",{className:"hub-drive-item-icon",children:i.jsx(Oe,{size:16})}),i.jsxs("span",{className:"hub-drive-item-copy",children:[i.jsx("strong",{children:xe.name}),i.jsx("small",{children:xe.displayPath||xe.name}),i.jsxs("em",{children:[Tb(xe.freeBytes||0)," free / ",Tb(xe.totalBytes||0)]})]}),G===xe.id?i.jsx(zs,{className:"hub-drive-item-status spin",size:15}):$e?i.jsx(py,{className:"hub-drive-item-status",size:15}):null]},xe.id)})})]},ne.id)),a.length===0&&i.jsxs("div",{className:"hub-drive-sidebar-empty",children:[i.jsx(Di,{size:17}),i.jsx("span",{children:"No drives available."})]})]}),i.jsxs("div",{className:"hub-file-explorer-browser",children:[i.jsxs("div",{className:"hub-file-explorer-navigation",children:[i.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((ne,xe)=>i.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[xe>0&&i.jsx(Np,{size:13,"aria-hidden":"true"}),i.jsx("button",{className:`hub-file-explorer-breadcrumb ${xe===T.length-1?"current":""}`,onClick:()=>he(xe),"aria-current":xe===T.length-1?"location":void 0,type:"button",children:ne.name})]},ne.svarPath))}),i.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[W&&i.jsx(zs,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),i.jsx("button",{className:"icon-button",onClick:Ce,disabled:T.length<=1||W,title:"Back to parent folder",type:"button",children:i.jsx(dx,{size:16})})]})]}),F&&i.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[i.jsx(py,{size:15}),i.jsx("span",{children:F})]}),i.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Te,children:i.jsx(HA,{fonts:!1,children:i.jsx(OA,{data:le,panels:V?[{path:V,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:He,icons:"simple",menuOptions:ee},`${z?.id||"no-root"}:${B}`)})})]})]})]})}class JA extends d.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,s){console.error("[LiveDesk] Share Files runtime error",a,s.componentStack)}render(){return this.state.error?i.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[i.jsx(Gf,{size:24}),i.jsx("strong",{children:"Share Files could not be opened."}),i.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),i.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[i.jsx(Ac,{size:15})," Retry"]})]}):this.props.children}}function eN(n){return n.deviceName||n.hostname||n.deviceId}function tN({devices:n,mode:a,selectedIds:s,onModeChange:l,onToggle:c}){const u=new Set(s);return i.jsxs("section",{className:"distribution-targets",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Target"}),i.jsx("strong",{children:a==="all"?`${n.length} connected`:`${s.length} selected`})]}),i.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[i.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[i.jsx(Wu,{size:14})," All connected"]}),i.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[i.jsx(Ea,{size:14})," Selected"]})]})]}),i.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:n.length===0?i.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):n.map(m=>{const h=a==="all"||u.has(m.deviceId);return i.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[i.jsx("input",{type:"checkbox",checked:h,disabled:a==="all",onChange:()=>c(m.deviceId)}),i.jsx(Ea,{size:20,"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:eN(m)}),i.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),i.jsx(ea,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function nN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let s=n,l=0;for(;s>=1024&&l<a.length-1;)s/=1024,l+=1;return`${s.toFixed(l===0||s>=100?0:1)} ${a[l]}`}function aN({folders:n,loading:a,busy:s,canSync:l,onSyncAll:c,onSync:u,onToggleAuto:m,onRemove:h,onAdd:g}){return i.jsxs("section",{className:"file-share-sync-panel",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub folders"}),i.jsx("strong",{children:"Continuous sync"})]}),i.jsxs("button",{className:"text-button compact",onClick:c,disabled:s||!l||n.length===0,type:"button",children:[i.jsx(kf,{size:15})," ",s?"Syncing":"Sync all"]})]}),a?i.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?i.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[i.jsx(kf,{size:28}),i.jsx("strong",{children:"Add a selected Hub folder"}),i.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):i.jsx("div",{className:"file-share-sync-list",children:n.map(y=>i.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[i.jsx("div",{className:"file-share-sync-icon",children:i.jsx(kf,{size:19})}),i.jsxs("div",{className:"file-share-sync-info",children:[i.jsx("strong",{children:y.name}),i.jsx("span",{children:y.displayPath}),i.jsxs("small",{children:[y.fileCount," files / ",nN(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${Nx(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),i.jsxs("label",{className:"file-share-auto-sync",children:[i.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>m(y)}),i.jsx("span",{children:"Auto"})]}),i.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:s||!l||y.status==="syncing",type:"button",children:[i.jsx(Ac,{size:14})," Sync now"]}),i.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:i.jsx(yx,{size:15})})]},y.id))})]})}function rN(n){const s=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return i.jsxs("aside",{className:"file-share-distribution-panel",children:[i.jsxs("div",{className:"file-share-distribution-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Distribution"}),i.jsx("strong",{children:"Hub → Clients"})]}),i.jsx(Vu,{size:18})]}),i.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[i.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),i.jsx("button",{className:n.tab==="sync"?"active":"",onClick:()=>n.onTabChange("sync"),role:"tab","aria-selected":n.tab==="sync",type:"button",children:"Sync"})]}),n.tab==="send"?i.jsxs(i.Fragment,{children:[i.jsx(tN,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),i.jsxs("label",{className:"file-share-destination",children:[i.jsx("span",{children:"Destination folder"}),i.jsxs("div",{children:[i.jsx(Sc,{size:15}),i.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),i.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),i.jsxs("div",{className:"file-share-selection-summary",children:[i.jsx("span",{children:"Selected"}),i.jsx("strong",{children:n.selectedSummary})]}),i.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[i.jsx(Vu,{size:17})," Share selected"]}),i.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[i.jsx(Sc,{size:16})," Add selected folder to Sync"]})]}):i.jsx(aN,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:s,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function sN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let s=n,l=0;for(;s>=1024&&l<a.length-1;)s/=1024,l+=1;return`${s.toFixed(l===0||s>=100?0:1)} ${a[l]}`}function Rb(n){if(n.state==="completed")return 100;const a=n.totalBytes>0?Math.round(n.sentBytes/n.totalBytes*100):n.totalFiles>0?Math.round(n.completedFiles/n.totalFiles*100):0;return Math.max(0,Math.min(wp(n.state)?100:99,a))}function Eb(n){return n.state==="scanning"?"Scanning selected Hub items":n.state==="queued"?"Preparing transfer":n.state==="sending"?`${n.completedFiles}/${n.totalFiles} · ${n.currentPath||"sending"}`:n.state==="completed"?`Sent ${n.totalFiles} file${n.totalFiles===1?"":"s"} to ${n.targetCount} Client${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} Client${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function wp(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function iN({hubUrl:n,devices:a,localFeatureAccess:s,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:u,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:x,folderPickerRef:b,onBrowserFileImport:w,onBrowserFolderImport:j,onNotice:M,onTransferChange:k}){const N=Array.isArray(a)?a:[],[A,T]=d.useState([]),[L,O]=d.useState(!0),[I,B]=d.useState(""),[_,G]=d.useState([]),[te,W]=d.useState([]),[Y,F]=d.useState(null),[ve,fe]=d.useState(!1),[Q,z]=d.useState([]),[re,V]=d.useState(!0),[H,le]=d.useState(!1),[oe,X]=d.useState("send"),[be,me]=d.useState([]),he=d.useRef(new Set),J=d.useRef(!1),Ce=d.useMemo(()=>m==="all"?N.map(U=>U.deviceId):h.filter(U=>N.some(ye=>ye.deviceId===U)),[N,h,m]),Te=be.find(U=>!wp(U.state)),He=te.length===1&&te[0].type==="folder"?te[0]:null,ee=te.length===0?"Select files or folders from the Hub explorer.":ve?"Calculating selection size...":Y?`${Y.files} files, ${Y.folders} folders · ${sN(Y.totalBytes)}`:`${te.length} item${te.length===1?"":"s"} selected`,Ue=U=>{k({id:U.jobId,state:U.state,progress:Rb(U),message:Eb(U)})},ft=d.useCallback(async()=>{const U=await FA(n,!0);return T(U),B(""),U},[n]),ne=async()=>{if(!J.current){J.current=!0;try{const ye=(await UA(n,!0)).jobs||[],je=await Promise.all([...he.current].map(async tt=>{try{return await qA(tt,n)}catch{return null}})),Fe=[...ye,...je.filter(Boolean)],ut=[...new Map(Fe.map(tt=>[tt.jobId,tt])).values()];me(ut),ut.forEach(Ue),ut.filter(tt=>wp(tt.state)).forEach(tt=>he.current.delete(tt.jobId))}catch{}finally{J.current=!1}}};d.useEffect(()=>{let U=!0;O(!0),B(""),Promise.all([ft(),Nb(n).then(je=>{U&&z(je)})]).catch(je=>{U&&(B(je instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),M(je instanceof Error?je.message:"Hub file system is unavailable."))}).finally(()=>{U&&(O(!1),V(!1))}),ne();const ye=window.setInterval(()=>{ne()},800);return()=>{U=!1,window.clearInterval(ye)}},[n,ft]),d.useEffect(()=>{if(_.length===0){F(null);return}let U=!1;return fe(!0),$A(_,n).then(ye=>{U||F(ye)}).catch(ye=>{U||M(ye instanceof Error?ye.message:"Unable to calculate selected size.")}).finally(()=>{U||fe(!1)}),()=>{U=!0}},[n,_.join("|")]);const xe=(U,ye)=>{G(U),W(ye)},Oe=U=>{U.forEach(ye=>he.current.add(ye.jobId)),me(ye=>[...new Map([...ye,...U].map(je=>[je.jobId,je])).values()]),U.forEach(Ue)},$e=async()=>{if(!s){M(l);return}if(_.length===0){M("Select files or folders from the Hub explorer.");return}if(Ce.length===0){M("Choose at least one connected Client.");return}if(Te){M("A Hub transfer is already running.");return}try{const U=await BA(_,Ce,c.trim(),n);he.current.add(U.jobId),M("Hub transfer queued."),await ne()}catch(U){M(U instanceof Error?U.message:"Unable to start Hub transfer.")}},ze=async U=>{const ye=U||He;if(!ye||ye.type!=="folder"){M("Select one folder to add it to Sync.");return}try{const je=await VA(ye.id,n);z(Fe=>[...Fe.filter(ut=>ut.id!==je.folder.id),je.folder]),X("sync"),M(`${ye.name} is ready for Hub sync.`)}catch(je){M(je instanceof Error?je.message:"Unable to add the Hub folder to Sync.")}},Qe=async U=>{if(Ce.length===0){M("Choose at least one connected Client.");return}le(!0),z(ye=>ye.map(je=>je.id===U.id?{...je,status:"syncing"}:je));try{const ye=await KA(U.id,Ce,c.trim(),n);Oe(ye.jobs||[]),M(ye.jobs?.length?"Hub sync queued.":"No changed files to sync.");const je=await Nb(n);z(je)}catch(ye){M(ye instanceof Error?ye.message:"Unable to sync the Hub folder."),z(je=>je.map(Fe=>Fe.id===U.id?{...Fe,status:"error",message:"Sync failed"}:Fe))}finally{le(!1)}},qe=async()=>{le(!0);try{for(const U of Q)await Qe(U)}finally{le(!1)}},We=async U=>{try{const ye=await WA(U.id,{autoSync:!U.autoSync},n);z(je=>je.map(Fe=>Fe.id===U.id?ye.folder:Fe))}catch(ye){M(ye instanceof Error?ye.message:"Unable to update auto sync.")}},lt=async U=>{try{await YA(U.id,n),z(ye=>ye.filter(je=>je.id!==U.id))}catch(ye){M(ye instanceof Error?ye.message:"Unable to remove the sync folder.")}};return i.jsxs("section",{className:"livedesk-file-explorer",children:[i.jsx("input",{ref:x,className:"hidden-file-input",type:"file",multiple:!0,onChange:U=>{U.currentTarget.files&&w(U.currentTarget.files),U.currentTarget.value=""}}),i.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:U=>{U.currentTarget.files&&j(U.currentTarget.files),U.currentTarget.value=""}}),i.jsx("div",{className:"file-share-workspace",children:i.jsxs(JA,{onRetry:()=>window.location.reload(),children:[i.jsx(ZA,{hubUrl:n,roots:A,loading:L,error:I,onRefreshRoots:ft,onImportFiles:()=>x.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:xe,onShareItem:U=>{G([U.id]),W([U]),X("send")},onAddSyncFolder:U=>{G([U.id]),W([U]),ze(U)},onNotice:M}),i.jsx(rN,{devices:N,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:c,onRemoteDirectoryChange:u,selectedEntries:te,selectedSummary:ee,canShare:s&&!Te&&_.length>0&&Ce.length>0&&!ve,onShare:()=>{$e()},canAddSync:!!He,onAddSync:()=>{ze()},tab:oe,onTabChange:X,folders:Q,foldersLoading:re,syncBusy:H,onSyncAll:()=>{qe()},onSync:U=>{Qe(U)},onToggleAuto:U=>{We(U)},onRemove:U=>{lt(U)},onAddFolder:()=>{ze()}})]})}),Te&&i.jsx("footer",{className:"file-share-workspace-footer",children:i.jsxs("span",{children:[Eb(Te)," · ",Rb(Te),"% ",i.jsx("button",{className:"icon-button",onClick:()=>{GA(Te.jobId,n).then(U=>{me(ye=>ye.map(je=>je.jobId===U.jobId?U:je)),Ue(U)})},title:"Cancel transfer",type:"button",children:i.jsx(Ra,{size:14})})]})})]})}const lN=d.forwardRef(function({value:a,onChange:s,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:u=!1,suggestedTaskCount:m,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},x){return i.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),l()},children:[i.jsx("button",{className:`agents-suggested-trigger ${u?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":u,onClick:c,disabled:h,children:i.jsx(E0,{size:17})}),i.jsx("textarea",{ref:x,value:a,onChange:b=>s(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),i.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!a.trim(),children:[h?i.jsx(zs,{className:"spin",size:16}):i.jsx(Vu,{size:16}),h?"Running":"Run"]})]})}),oN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function $f(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function Bf(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function cN(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function uN(n){switch(n){case"process.list":return"Process list";case"system.health":return"System health";case"gpu.status":return"GPU status";case"disk.status":return"Disk status";case"service.status":return"Service status";case"diagnostics.collect":return"Diagnostics";case"process.control":return"Process control";case"service.control":return"Service control";case"application.launch":return"Launch application";case"application.close":return"Close application";case"file.read":return"Read file";case"file.write":return"Write file";case"file.delete":return"Delete file";case"file.list":return"List directory";case"command.run":return"Run command";case"script.run":return"Run script";case"software.install":return"Install software";case"network.status":return"Network status";case"system.power":return"Power action";case"system.configure":return"System configuration";case"logs.collect":return"Collect logs"}}function dN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function yr(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function yf(n){const a=yr(n);return a===null?"":a<1024**2?`${Math.round(a/1024)}K`:a<1024**3?`${(a/1024**2).toFixed(0)}M`:`${(a/1024**3).toFixed(1)}G`}function fN(n){const a=yr(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function mN(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function Uf(n,a){if(a.error)return a.error;const s=dN(a.data),l=mN(a.result||"");if(!s)return l||a.stage||a.status;if(n==="system.health"){const c=typeof s.machine=="string"?s.machine:"",u=yf(s.freeMemoryBytes),m=yf(s.totalMemoryBytes),h=yr(s.totalMemoryBytes)&&yr(s.freeMemoryBytes)!==null?`${Math.round(yr(s.freeMemoryBytes)/yr(s.totalMemoryBytes)*100)}% RAM free`:"";return[c,u&&m?`RAM ${u}/${m}`:"",h,typeof s.platform=="string"?s.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof s.root=="string"?s.root:"",u=yf(s.freeBytes),m=yr(s.totalBytes)&&yr(s.freeBytes)!==null?`${Math.round(yr(s.freeBytes)/yr(s.totalBytes)*100)}% free`:"";return[c,u&&`${u} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof s.name=="string"&&s.name?s.name:"No GPU provider",u=fN(s.usageRatio),m=yr(s.temperatureC)!==null?`${Math.round(yr(s.temperatureC))}°C`:"",h=yf(s.freeMemoryBytes);return[c,u&&`GPU ${u}`,m,h&&`${h} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=yr(s.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(s.adapters)?s.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function Db(n,a){const s=Uf(n,a);return a.status==="failed"||a.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${a.result||""} ${s}`)}function hN({state:n,operation:a}){const s=n.status==="completed"?Os:n.status==="failed"||n.status==="cancelled"?Ra:n.status==="running"?zs:bx,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?Uf(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return i.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[i.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:i.jsx(s,{size:15})}),i.jsx("strong",{children:n.deviceName}),i.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),i.jsx("small",{children:l})]})}function pN({operation:n,states:a,status:s,onCancel:l,onRetry:c,busy:u=!1}){const m=["running","queued"].includes(s),[h,g]=d.useState(!1),[y,x]=d.useState("all"),b=d.useMemo(()=>({total:a.length,completed:a.filter(L=>L.status==="completed").length,failed:a.filter(L=>L.status==="failed").length,running:a.filter(L=>L.status==="running").length,queued:a.filter(L=>L.status==="queued").length,cancelled:a.filter(L=>L.status==="cancelled").length}),[a]),w=a.filter(L=>Db(n,L)),j=w.filter(L=>L.status==="completed").length,M=b.failed>0,k=w.length>0,N=a.filter(L=>y==="issues"?Db(n,L):y==="running"?L.status==="running"||L.status==="queued":y==="completed"?L.status==="completed":y==="failed"?L.status==="failed":!0),A=k&&!m||s==="completed-with-failures"?"Completed with issues":s[0]?.toUpperCase()+s.slice(1),T=a.filter(L=>L.status==="completed").map(L=>Uf(n,L)).filter(Boolean).filter((L,O,I)=>I.indexOf(L)===O).slice(0,2);return i.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[i.jsxs("div",{className:"agent-task-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"LiveDesk Agent"}),i.jsx("strong",{children:uN(n)})]}),i.jsx("span",{className:`agent-task-status status-${k?"completed-with-failures":s}`,children:A})]}),i.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[i.jsxs("strong",{children:[b.total," targets"]}),i.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&i.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&i.jsxs("span",{children:[b.queued," queued"]}),M&&i.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),j>0&&i.jsxs("span",{className:"summary-cancelled",children:[j," warning"]}),b.cancelled>0&&i.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&i.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[i.jsx("span",{children:"Result"}),T.join(" · ")]}),i.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((L,O)=>{const I=L.status==="completed"?"✓":L.status==="failed"?"×":L.status==="cancelled"?"!":L.status==="running"?"…":"·";return i.jsxs("span",{className:`agent-target-chip status-${L.status}`,title:`${L.deviceName}: ${Uf(n,L)}`,"aria-label":`${O+1}. ${L.deviceName}: ${L.status}`,children:[i.jsx("b",{children:String(O+1).padStart(2,"0")}),i.jsx("span",{children:I})]},L.deviceId)})}),a.length>0&&i.jsx("div",{className:"agent-task-details-toggle",children:i.jsxs("button",{type:"button",onClick:()=>g(L=>!L),"aria-expanded":h,children:[h?i.jsx(D0,{size:14}):i.jsx(xx,{size:14}),h?"Hide details":"Show details"]})}),h&&i.jsxs("div",{className:"agent-task-details",children:[i.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(L=>i.jsx("button",{className:y===L?"active":"",onClick:()=>x(L),role:"tab","aria-selected":y===L,type:"button",children:L==="all"?"All":L==="issues"?"Issues only":L[0].toUpperCase()+L.slice(1)},L))}),i.jsx("div",{className:"agent-task-rows",children:N.length>0?N.map(L=>i.jsx(hN,{operation:n,state:L},L.deviceId)):i.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||M)&&i.jsxs("div",{className:"agent-task-actions",children:[m&&l&&i.jsxs("button",{onClick:l,disabled:u,type:"button",children:[i.jsx(L0,{size:14})," Cancel"]}),!m&&M&&c&&i.jsxs("button",{onClick:c,disabled:u,type:"button",children:[i.jsx(wx,{size:14})," Retry failed"]})]})]})}function gN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function vN({approval:n,busy:a=!1,onApprove:s,onReject:l}){return i.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[i.jsxs("div",{className:"agent-approval-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Approval required"}),i.jsx("strong",{children:n.toolName})]}),i.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),i.jsx("p",{children:n.description}),i.jsx("pre",{children:gN(n.arguments)}),i.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),i.jsxs("div",{className:"agent-approval-actions",children:[i.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[i.jsx(Ra,{size:14})," Reject"]}),i.jsxs("button",{disabled:a,onClick:()=>s("once"),type:"button",children:[i.jsx(Os,{size:14})," Once"]}),i.jsx("button",{disabled:a,onClick:()=>s("same-action-this-run"),type:"button",children:"Allow same action"}),i.jsx("button",{disabled:a,onClick:()=>s("category-this-run"),type:"button",children:"Allow category"})]}),i.jsxs("div",{className:"agent-approval-scope",children:[i.jsx(Gf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function yN(n){return n==="queued"?"Request queued":n==="checking-codex"?"Checking Codex":n==="preparing-tools"?"Preparing tools":n==="thinking"?"Preparing answer":n==="tool-running"?"Working on computers":n==="recovering"?"Retrying safely":n==="waiting-approval"?"Waiting for approval":"Working"}function bN({items:n,onCancel:a,onRetry:s,busyBatchId:l,approvals:c,onApprove:u,onReject:m,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:x="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const b=d.useRef(null),w=d.useRef(!0),j=d.useRef(""),M=n[n.length-1];return d.useLayoutEffect(()=>{const k=b.current;k&&(M?.type==="user"&&M.id!==j.current&&(w.current=!0),j.current=M?.id||"",w.current&&(k.scrollTop=k.scrollHeight))},[c,n,M?.id,M?.type,g?.message,g?.stage]),i.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:k=>{const N=k.currentTarget;w.current=N.scrollHeight-N.scrollTop-N.clientHeight<72},children:[c.filter(k=>k.status==="pending").map(k=>i.jsx(vN,{approval:k,busy:h===k.approvalId,onApprove:N=>u(k,N),onReject:()=>m(k)},k.approvalId)),n.length===0&&i.jsxs("div",{className:"agents-empty-conversation",children:[i.jsx("strong",{children:y}),i.jsx("span",{children:x})]}),n.map(k=>{if(k.type==="task"){const N=k;return i.jsx(pN,{operation:N.operation,states:N.states,status:N.status,onCancel:()=>a(N.batchId,N.agentRunId),onRetry:()=>s(N.batchId),busy:l===N.batchId},N.id)}return i.jsxs("article",{className:`agents-message ${k.type}`,children:[i.jsx("span",{children:k.type==="user"?"You":"LiveDesk Agent"}),i.jsx("p",{children:k.text})]},k.id)}),g&&i.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[i.jsxs("span",{children:[i.jsx(zs,{"aria-hidden":"true",size:15}),yN(g.stage)]}),i.jsx("p",{children:g.message})]})]})}const Lb=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],Tn=["windows","macos","linux"],Ll={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Tn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Tn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Tn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Tn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Tn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Tn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:Tn},"service.control":{label:"service control",permissionCategory:"serviceControl",readOnly:!1,risk:"high",supportedPlatforms:["windows","linux"]},"application.launch":{label:"application launch",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Tn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Tn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Tn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:Tn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:Tn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Tn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:Tn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:Tn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:Tn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:Tn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:Tn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:Tn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Tn}};new Set(Object.keys(Ll));const xN={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"Files & configuration":["file","config","directory","파일","설정","폴더"],"Software & automation":["software","install","automation","프로그램","설치","자동화"],"Network & connectivity":["network","connection","adapter","네트워크","연결","어댑터"],"Power & maintenance":["power","maintenance","restart","전원","유지보수","재시작"],"Troubleshooting & recovery":["troubleshooting","recovery","incident","문제해결","복구","장애"]},_b=["low","medium","high","critical"];function wN(n){return n.reduce((a,s)=>{const l=Ll[s].risk;return _b.indexOf(l)>_b.indexOf(a)?l:a},"low")}function SN(n){return Tn.filter(a=>n.every(s=>Ll[s].supportedPlatforms.includes(a)))}function Je(n,a,s,l,c,u,m={}){const h=m.description||l,g=c.flatMap(x=>x.split(".")),y=[...new Set([...xN[a],...u,...g])];return{id:n,category:a,title:s,prompt:l,description:h,requiredOperations:c,risk:m.risk||wN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||SN(c),keywords:y,recommended:m.recommended??!1,enabled:!0}}const Ow=[Je("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Je("recommended-attention","Recommended","Find targets needing attention","Identify current targets with high resource use, low disk space, or service warnings.",["system.health","disk.status","service.status"],["attention","warning","monitor"],{recommended:!0}),Je("recommended-performance-compare","Recommended","Compare selected performance","Compare CPU, memory, disk, and GPU capacity across the current targets.",["system.health","disk.status","gpu.status"],["compare","benchmark"],{recommended:!0}),Je("recommended-gpu-vram","Recommended","Review GPU and VRAM availability","Show GPU temperature, utilization, and VRAM availability for the current targets.",["gpu.status"],["graphics","temperature","utilization"],{recommended:!0}),Je("recommended-low-disk","Recommended","Locate low disk capacity","Find current targets with low free disk capacity and report the affected volumes.",["disk.status"],["storage","free space","capacity"],{recommended:!0}),Je("recommended-process-services","Recommended","Review processes and services","Review running processes and service state for warnings on the current targets.",["process.list","service.status"],["process","service","warning"],{recommended:!0}),Je("recommended-recover-application","Recommended","Recover a stopped application","Check a named application or service, relaunch its registered entry when stopped, and verify the result.",["process.list","application.launch","service.status"],["recover","start","application"],{targetSupport:"single",recommended:!0}),Je("recommended-incident-diagnostics","Recommended","Collect an incident diagnostic bundle","Collect health, service, network, and recent log diagnostics for the current targets.",["diagnostics.collect","logs.collect","system.health","network.status"],["incident","report","evidence"],{recommended:!0}),Je("health-cpu-memory","Health & capacity","Check high CPU and memory use","Find current targets with unusually high CPU or memory usage.",["system.health"],["cpu","memory","load","높은 사용량"]),Je("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),Je("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Je("health-vram-usage","Health & capacity","Check VRAM usage","Report GPU memory usage and remaining VRAM on the current targets.",["gpu.status"],["vram","gpu memory","video memory"]),Je("health-low-disk","Health & capacity","Find low disk space","Find volumes below a safe free-space threshold on the current targets.",["disk.status"],["disk","storage","free space","디스크"]),Je("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Je("health-system-warnings","Health & capacity","Collect system warnings","Review health, disk, and network status for warnings that need attention.",["system.health","disk.status","network.status"],["warnings","alerts","경고"]),Je("health-capacity-report","Health & capacity","Build a capacity report","Create a concise capacity report covering CPU, memory, GPU, disk, and network status.",["system.health","gpu.status","disk.status","network.status"],["report","capacity","inventory"]),Je("process-find-name","Processes & services","Find a running process by name","Find process named [process name] on the current targets.",["process.list"],["find","running","name","실행 중"]),Je("process-resource-heavy","Processes & services","Find resource-heavy processes","List the processes using the most CPU or memory on the current targets.",["process.list","system.health"],["top","cpu","memory","resource"]),Je("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Je("process-restart-named","Processes & services","Restart a named process","Check process named [process name] and restart it with its registered launch details when available.",["process.list","process.control"],["restart","relaunch","재시작"],{targetSupport:"single"}),Je("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Je("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Je("service-status-name","Processes & services","Check a service status","Check service [service name] and report its state on the current targets.",["service.status"],["service","status","서비스 상태"]),Je("service-restart-name","Processes & services","Restart a service safely","Check service [service name], stop it, wait for it to stop, then start it and verify the result.",["service.status","service.control"],["restart","start","stop","서비스 재시작"],{targetSupport:"single"}),Je("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Je("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),Je("files-recent-logs","Files & configuration","Find recent log files","List recent log files under [path] and summarize the latest entries.",["file.list","file.read"],["logs","recent","tail"]),Je("files-update-config","Files & configuration","Update a configuration value","Read configuration file [path], update [change], and report the exact change made.",["file.read","file.write"],["edit","update","설정 변경"],{targetSupport:"single"}),Je("files-delete-temp","Files & configuration","Delete temporary files","Find temporary files under [path], delete only the requested matches, and report the freed space.",["file.list","file.delete","disk.status"],["cleanup","temp","delete","정리"],{targetSupport:"single"}),Je("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Je("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Je("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Je("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Je("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Je("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Je("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Je("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Je("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Je("software-verify-install","Software & automation","Verify an installed tool","Check whether [application] is installed, running, and available on the PATH of the current targets.",["process.list","system.health"],["verify","installed","path"]),Je("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Je("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Je("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Je("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Je("network-warnings","Network & connectivity","Review network warnings","Review network status and recent logs for connectivity warnings on the current targets.",["network.status","logs.collect"],["warning","latency","packet loss"]),Je("network-diagnostics","Network & connectivity","Collect network diagnostics","Collect network status, system diagnostics, and relevant logs for the current targets.",["network.status","diagnostics.collect","logs.collect"],["diagnostics","incident","connectivity"]),Je("network-service-failures","Network & connectivity","Find network service failures","Check network status and relevant service states on the current targets.",["network.status","service.status"],["service","failure","dns"]),Je("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Je("network-intermittent","Network & connectivity","Investigate intermittent connectivity","Investigate intermittent connectivity using network status, service state, and diagnostics evidence.",["network.status","service.status","diagnostics.collect"],["intermittent","unstable","recovery"]),Je("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Je("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Je("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Je("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Je("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Je("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Je("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Je("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Je("recovery-app-wont-start","Troubleshooting & recovery","Investigate an app that will not start","Inspect [application], review its logs, launch the registered application, and verify the process.",["process.list","application.launch","logs.collect"],["app failure","start","실행 오류"],{targetSupport:"single"}),Je("recovery-failed-service","Troubleshooting & recovery","Recover a failed service","Inspect service [service name], collect logs, restart it safely, and verify its running state.",["service.status","logs.collect","service.control"],["service failure","recover","서비스 복구"],{targetSupport:"single"}),Je("recovery-repeated-process","Troubleshooting & recovery","Investigate a repeatedly stopping process","Inspect process [process name], collect diagnostics, stop stale instances, and relaunch the registered process.",["process.list","diagnostics.collect","process.control","application.launch"],["crash loop","process","반복 종료"],{targetSupport:"single"}),Je("recovery-low-disk","Troubleshooting & recovery","Recover from low disk space","Inspect disk capacity, find temporary files, remove only the requested files, and verify free space.",["disk.status","file.list","file.delete"],["disk full","cleanup","저장공간 부족"],{targetSupport:"single"}),Je("recovery-gpu-overheating","Troubleshooting & recovery","Investigate GPU overheating","Inspect GPU temperature and processes, then close the specified workload if it is causing the thermal warning.",["gpu.status","process.list","application.close"],["overheating","thermal","GPU 발열"],{targetSupport:"single"}),Je("recovery-high-vram","Troubleshooting & recovery","Recover high VRAM usage","Inspect VRAM usage and GPU processes, then stop the specified stale workload if necessary.",["gpu.status","process.list","process.control"],["vram","memory pressure","VRAM 부족"],{targetSupport:"single"}),Je("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Je("recovery-incident-report","Troubleshooting & recovery","Create a full incident report","Create a full incident report from health, process, service, network, and log evidence for the current targets.",["system.health","process.list","service.status","network.status","logs.collect"],["incident","report","장애 보고서"])],Oh={read:"allow",processControl:"allow",serviceControl:"allow",applicationControl:"ask",fileRead:"allow",fileWrite:"allow",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"allow",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function CN(n,a){return n==="safe-auto"?Oh:n==="full-access"?{...Oh,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...Oh,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function kN(n,a,s){const l=CN(a,s),c=n.requiredOperations.map(u=>l[Ll[u].permissionCategory]);if(c.includes("deny")){const u=n.requiredOperations.find(m=>l[Ll[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Ll[u].label}, which is blocked by the current permission policy.`}}return c.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:n.requiredOperations.every(u=>Ll[u].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function jN(n){const a=String(n||"").trim().toLowerCase();return a==="windows"||a==="win32"||a==="win32nt"?"windows":a==="macos"||a==="macosx"||a==="darwin"||a==="osx"?"macos":a==="linux"?"linux":null}function MN(n,a,s){const l=new Set(s);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function AN(n,a){const s=jN(n.platform);if(!s||!a.supportedPlatforms.includes(s))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>Ll[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function Hw(n,a,s,l,c,u){const m=kN(n,c,u),h=MN(a,s,l),g=h.map(j=>j.deviceId),y={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(n.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(m.state==="blocked")return y;const x=h.filter(j=>AN(j,n)),b=x.map(j=>j.deviceId),w=g.filter(j=>!b.includes(j));return x.length===0?{...y,unsupportedDeviceIds:w,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:w}}function NN(n,a,s,l,c,u){return n.filter(m=>m.enabled&&Hw(m,a,s,l,c,u).available).length}const Hh="livedesk.agentPromptRecent",Ph="livedesk.agentPromptFavorites",TN={Recommended:Il,"Health & capacity":jo,"Processes & services":O0,"Files & configuration":z0,"Software & automation":gx,"Network & connectivity":Ap,"Power & maintenance":Yn,"Troubleshooting & recovery":I0};function Ib(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(s=>typeof s=="string"):[]}catch{return[]}}function bf(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function Fh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function RN(n){return n==="all"?"All":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto":n==="approval"?"Approval":n==="full-access"?"Full access":n==="available"?"Available":n==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[n]}function EN(n,a,s){if(!s.trim())return!0;const l=s.trim().toLowerCase();return[n.title,n.prompt,n.description,n.category,n.risk,a.label,...n.keywords,...n.requiredOperations,...n.supportedPlatforms].join(" ").toLowerCase().includes(l)}function DN(n){return`permission-${n}`}function LN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function _N(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function IN({devices:n,targetMode:a,selectedIds:s,permissionMode:l,customCategories:c,onSelectPrompt:u,onClose:m}){const[h,g]=d.useState(""),[y,x]=d.useState("all"),[b,w]=d.useState(()=>Ib(Hh)),[j,M]=d.useState(()=>Ib(Ph)),[k,N]=d.useState(0),[A,T]=d.useState(""),L=d.useRef(null),O=d.useRef(null),I=d.useMemo(()=>Ow.filter(Q=>Q.enabled),[]),B=d.useMemo(()=>new Map(I.map(Q=>[Q.id,Hw(Q,n,a,s,l,c)])),[c,n,l,s,a,I]),_=d.useMemo(()=>[...B.values()].filter(Q=>Q.available).length,[B]),G=d.useMemo(()=>n.filter(Q=>Q.connected&&(a==="all"||a==="auto"||s.includes(Q.deviceId))).length,[n,s,a]),te=d.useMemo(()=>{const Q=I.filter(z=>EN(z,B.get(z.id),h));return y==="recent"?b.map(z=>Q.find(re=>re.id===z)).filter(z=>!!z):y==="favorites"?j.map(z=>Q.find(re=>re.id===z)).filter(z=>!!z):y==="all"?Q:Q.filter(z=>{const re=B.get(z.id);return y==="read-only"?re.state==="read-only":y==="auto"?re.state==="auto":y==="approval"?re.state==="approval":y==="full-access"?re.state==="full-access":y==="available"?re.available:y==="unavailable"?!re.available:z.category===y})},[B,j,y,b,h,I]),W=d.useMemo(()=>y!=="all"?[{category:Fh(y),templates:te}]:Lb.map(Q=>({category:Q,templates:te.filter(z=>z.category===Q)})).filter(Q=>Q.templates.length>0),[y,te]);d.useEffect(()=>{N(Q=>Math.min(Q,Math.max(0,te.length-1)))},[te.length]),d.useEffect(()=>{bf(Hh,b)},[b]),d.useEffect(()=>{bf(Ph,j)},[j]),d.useEffect(()=>{O.current?.focus();const Q=re=>{re.target instanceof Node&&!L.current?.contains(re.target)&&m()},z=re=>{re.key==="Escape"&&(re.preventDefault(),m())};return document.addEventListener("pointerdown",Q),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",Q),document.removeEventListener("keydown",z)}},[m]);const Y=Q=>{const z=B.get(Q.id);if(!z.available){T(z.reason||"This task is not available for the current targets and permission policy.");return}const re=[Q.id,...b.filter(V=>V!==Q.id)].slice(0,10);w(re),bf(Hh,re),u(Q.prompt),m()},F=Q=>{M(z=>{const re=z.includes(Q)?z.filter(V=>V!==Q):[Q,...z];return bf(Ph,re),re})},ve=Q=>{Q.key==="ArrowDown"?(Q.preventDefault(),N(z=>Math.min(z+1,Math.max(0,te.length-1)))):Q.key==="ArrowUp"?(Q.preventDefault(),N(z=>Math.max(z-1,0))):Q.key==="Enter"&&te[k]&&(Q.preventDefault(),Y(te[k]))};let fe=-1;return i.jsxs("section",{className:"agents-suggested-tasks",ref:L,"aria-label":"Suggested tasks",children:[i.jsxs("header",{className:"agents-suggested-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"agents-suggested-title",children:[i.jsx(Il,{size:15})," Suggested tasks"]}),i.jsxs("small",{children:[_," available · ",I.length," total. Choose a task, edit it, then run it."]})]}),i.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:i.jsx(Ra,{size:16})})]}),i.jsxs("label",{className:"agents-suggested-search",children:[i.jsx(_0,{size:15,"aria-hidden":"true"}),i.jsx("input",{ref:O,value:h,onChange:Q=>g(Q.target.value),onKeyDown:ve,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),i.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...Lb].map(Q=>{const z=Q==="recent"?px:Q==="favorites"?Jh:Q==="all"?Il:Q==="available"?ea:Q==="unavailable"?Sx:Q==="read-only"||Q==="auto"||Q==="approval"||Q==="full-access"?Yn:TN[Q];return i.jsxs("button",{className:y===Q?"active":"",type:"button",title:Fh(Q),"aria-label":Fh(Q),"aria-pressed":y===Q,onClick:()=>{x(Q),N(0),T("")},children:[i.jsx(z,{size:12})," ",RN(Q)]},Q)})}),A&&i.jsx("div",{className:"agents-suggested-notice",role:"status",children:A}),i.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[W.map(Q=>i.jsxs("div",{className:"agents-suggested-group",children:[i.jsx("strong",{children:Q.category}),Q.templates.map(z=>{fe+=1;const re=fe===k,V=j.includes(z.id),H=B.get(z.id),le=H.availableDeviceIds.length+H.unsupportedDeviceIds.length||G,oe=H.available?`Available on ${H.availableDeviceIds.length} of ${le} target${le===1?"":"s"}`:`Unavailable: ${H.reason||"not supported by the current targets"}`;return i.jsxs("div",{className:`agents-suggested-item ${re?"active":""} ${H.available?"":"unavailable"}`,children:[i.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":re,"aria-disabled":!H.available,onClick:()=>Y(z),children:[i.jsx("span",{children:z.title}),i.jsx("small",{className:"agents-suggested-description",children:z.description}),i.jsxs("span",{className:"agents-suggested-meta",children:[i.jsx("em",{children:z.category}),i.jsx("em",{className:DN(H.state),children:H.label}),i.jsx("em",{className:`risk-${z.risk}`,children:LN(z.risk)}),i.jsx("em",{children:z.supportedPlatforms.map(_N).join(" · ")}),i.jsx("em",{className:H.available?"availability-ok":"availability-unavailable",children:oe}),H.available&&H.unsupportedDeviceIds.length>0&&i.jsxs("em",{className:"availability-warning",children:["Unsupported on ",H.unsupportedDeviceIds.length]})]})]}),i.jsx("button",{className:`agents-suggested-favorite ${V?"favorite":""}`,type:"button","aria-label":V?`Remove ${z.title} from favorites`:`Add ${z.title} to favorites`,"aria-pressed":V,onClick:()=>F(z.id),children:i.jsx(Jh,{size:14,fill:V?"currentColor":"none"})})]},z.id)})]},Q.category)),te.length===0&&i.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function zN({devices:n,mode:a,selectedIds:s,onModeChange:l,onToggle:c,permissionMode:u,onPermissionModeChange:m}){const h=n.filter(Bf),g=s.filter(y=>h.some(x=>x.deviceId===y)).length;return i.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[i.jsxs("div",{className:"agents-target-toolbar",children:[i.jsx("span",{className:"agents-section-label",children:"Targets"}),i.jsxs("div",{className:"agents-target-modes",children:[i.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[i.jsx(Wu,{size:14})," All connected ",i.jsx("small",{children:h.length})]}),i.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[i.jsx(Os,{size:14})," Selected ",g]}),i.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[i.jsx(Il,{size:14})," Auto"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(Wu,{size:14})," Group ",i.jsx("small",{children:"Soon"})]})]}),i.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[i.jsx(Gf,{size:14}),i.jsx("span",{children:"Permission"}),i.jsxs("select",{value:u,onChange:y=>m(y.target.value),"aria-label":"Agent permission mode",children:[i.jsx("option",{value:"ask",children:"Ask"}),i.jsx("option",{value:"safe-auto",children:"Safe Auto"}),i.jsx("option",{value:"full-access",children:"Full Access"}),i.jsx("option",{value:"custom",children:"Custom"})]}),i.jsx(xx,{size:13,"aria-hidden":"true"})]})]}),i.jsx("div",{className:"agents-target-list",children:n.length===0?i.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):n.map(y=>{const x=Bf(y),b=a==="all"||a==="auto"?x:s.includes(y.deviceId);return i.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${x?"":"offline"}`,children:[i.jsx("input",{type:"checkbox",checked:b,disabled:!x||a!=="selected",onChange:()=>c(y.deviceId)}),i.jsx("span",{className:"agents-target-icon",children:i.jsx(Ea,{size:15})}),i.jsxs("span",{children:[i.jsx("strong",{children:$f(y)}),i.jsx("small",{children:x?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&i.jsx(Os,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}async function ON(n,a){return Ye("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function HN(n,a){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function PN(n,a){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function FN(n){return Ye("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function $N(n,a,s,l){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(s)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function BN(n,a,s,l="User rejected this action."){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(s)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function UN(n,a,s){return Ye(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:s})},n)}async function qN(n,a){return Ye("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function GN(n,a){return Ye(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function VN(n,a){return Ye(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function WN(n,a){return Ye(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function bc(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function $h(n,a){const s=new Map(a.map(l=>[l.deviceId,$f(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||s.get(l.deviceId)||l.deviceId,status:cN(l.status),stage:l.stage||(l.status==="running"?"Checking processes":void 0),result:l.result,data:l.data,error:l.error,sequence:Number.isSafeInteger(l.sequence)?l.sequence:0}))}function YN(n,a){const s=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=s.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function KN(n,a){const s=a.filter(u=>u.status==="completed"),l=a.filter(u=>u.status==="failed");if(n.operation==="process.list"){const m=`${s.filter(h=>{const g=h.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
|
|
15
15
|
${l.map(h=>`${h.deviceName}는 ${h.error||"응답하지 않았습니다."}`).join(`
|