@codrihub/memora 2.1.7 → 2.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/app.js +115 -76
- package/assets/index.html +2 -2
- package/assets/mnemo-docs.json +1 -1
- package/assets/sw.js +2 -2
- package/package.json +4 -4
package/assets/app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){"use strict";const te={openNote:()=>{},renderTree:()=>{},loadCore:async()=>{},go:()=>{},refreshPage:()=>{},refreshTree:()=>{},refreshVault:()=>{},refreshLogs:()=>{},openMoveNote:()=>{},openMoveFolder:()=>{},openFolderColor:()=>{},confirmDeleteFolder:()=>{},openNewNote:()=>{},openNewFolder:()=>{},openTrash:()=>{},vaultChanged:()=>{},askMnemo:()=>{},mnemoButton:()=>!0,mnemoActivity:()=>{}},Jk=te.renderTree,O6=te.refreshTree,$6={add(){},remove(){},toggle(){},contains(){return!1}},Qk=new Proxy({},{get(t,e){if(e==="classList")return $6;if(e==="style")return new Proxy({},{get:()=>"",set:()=>!0});if(e==="dataset")return{};if(e==="querySelector"||e==="closest")return()=>Qk;if(e==="querySelectorAll")return()=>[];if(e==="children")return[];if(e==="offsetParent")return null;if(e==="value"||e==="textContent"||e==="innerHTML"||e==="title")return""},set:()=>!0});function H(t,e=document){return e.querySelector(t)??Qk}function Bn(t,e=document){return Array.from(e.querySelectorAll(t))}function re(t,e,n){const a=document.createElement(t);return e&&(a.className=e),n!=null&&(a.innerHTML=n),a}function x(t){return String(t??"").replace(/[&<>"']/g,e=>{switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function C(t){return x(t)}const F6={"&":"&","<":"<",">":">",""":'"',"'":"'"};function U6(t){return String(t??"").split(/(<\/?b>)/).map(e=>e==="<b>"||e==="</b>"?e:x(e.replace(/&(?:amp|lt|gt|quot|#39);/g,n=>F6[n]??n))).join("")}function Ue(t,e){if(document.getElementById(t))return;const n=document.createElement("style");n.id=t,n.textContent=e,document.head.appendChild(n)}function e2(t,e,n){const a=new Error(t);return a.status=e,a.data=n,a}let t2=!1;function B6(){if(t2||typeof location>"u"||location.pathname==="/login")return;t2=!0;const t=location.pathname+location.search+location.hash;window.setTimeout(()=>location.replace("/login?r="+encodeURIComponent(t)),50)}async function $n(t,e={}){const n={accept:"application/json"};let a;e.body!==void 0&&(n["content-type"]="application/json",a=JSON.stringify(e.body));let i;try{i=await fetch(t,{method:e.method??"GET",credentials:"same-origin",headers:n,body:a,cache:"no-store"})}catch{throw e2("cannot reach the server",0,null)}const o=await i.text();let s=null;try{s=o?JSON.parse(o):null}catch{s={raw:o}}if(i.status===401&&B6(),!i.ok){const r=s??{},l=typeof r.error=="string"?r.error:typeof r.message=="string"?r.message:`HTTP ${i.status}`;throw e2(l,i.status,s)}return s}function Oe(t){return $n(t)}function Ve(t,e={}){return $n(t,{method:"POST",body:e})}async function Iv(){const t=await Oe("/api/tools");return t&&t.tools||[]}function H6(t,e){return Ve("/api/tools",{name:t,enabled:e})}function n2(t){return Ve("/api/keys/update",t)}const q6='<svg class="caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M6 9l6 6 6-6"/></svg>',W6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M12 17v5M8.5 3h7l-1 6 3 3v2H6.5v-2l3-3z"/></svg>',G6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M12 17v5M8.5 3h7l-1 6 3 3v2H6.5v-2l3-3z"/><path d="M3 3l18 18"/></svg>',a2='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M14 13h-4M12 11l2 2-2 2"/></svg>',V6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><circle cx="12" cy="12" r="3"/><path d="M12 3v3M12 18v3M3 12h3M18 12h3"/></svg>',j6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/></svg>',Nv=["#5eead4","#7dd3fc","#a5b4fc","#fbbf24","#f87171","#4ade80","#f0abfc","#fb923c","#94a3b8"];function sa(t){return t?new Date(Number(t)*1e3).toLocaleString("en-US",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"-"}function kn(t){if(!t)return"-";const e=Date.now()/1e3-Number(t),n=(a,i)=>`${a} ${i}${a===1?"":"s"} ago`;return e<60?"just now":e<3600?n(Math.floor(e/60),"minute"):e<86400?n(Math.floor(e/3600),"hour"):e<2592e3?n(Math.floor(e/86400),"day"):new Date(Number(t)*1e3).toLocaleDateString("en-US",{day:"numeric",month:"short",year:"numeric"})}function Y6(t){return new Date(Number(t)*1e3).toLocaleDateString("en-US",{weekday:"short",day:"numeric",month:"short",year:"numeric"})}function X6(t,e){const n=String(t??"");return n.length>e?n.slice(0,e-1)+"...":n}function i2(t){const e=String(t||"").split("/");return e.length>1?e[0]:"Root"}function dn(t){return String(t||"").split("/").pop().replace(/\.md$/,"")}function or(t){return t.replace(/_/g," ").trim()||t}function jn(t){let e=0;const n=String(t||"");for(let a=0;a<n.length;a++)e=e*31+n.charCodeAt(a)>>>0;return Nv[e%Nv.length]}function zv(t,e){let n;return(...a)=>{clearTimeout(n),n=setTimeout(()=>t(...a),e)}}function o2(t){const e=new Set,n=t||"",a=/(?:^|\n)tags\s*:\s*(.*)/i.exec(n);return a&&a[1].replace(/[\[\]'"]/g," ").split(/[,\s]+/).map(i=>i.replace(/^#/,"").trim()).filter(Boolean).forEach(i=>e.add(i)),(n.match(/(^|\s)#([A-Za-z0-9_][\w/-]{1,48})/g)||[]).forEach(i=>e.add(i.trim().replace(/^#/,""))),Array.from(e)}function K6(t){const e=String(t||"").match(/\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g)||[];return Array.from(new Set(e.map(n=>n.replace(/^\[\[|\]\]$/g,"").split("|")[0].replace(/\\$/,"").trim()).filter(Boolean)))}const s2="memora.pins.v3",r2="memora.pinorder.v1",l2="memora.ui.v3",c2="memora.openfolders.v3",d2="memora.updateNotice",p2="memora.toasts.v1",Dv="memora.tagidx";function sr(t,e){try{const n=(t==="local"?localStorage:sessionStorage).getItem(e);return n?JSON.parse(n):void 0}catch{return}}function md(t,e,n){try{(t==="local"?localStorage:sessionStorage).setItem(e,JSON.stringify(n))}catch{}}function gd(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function vs(t,e){return t&&typeof t=="object"?t[e]:void 0}const h2=sr("local",l2),Ov=vs(h2,"width"),Eo={collapsed:vs(h2,"collapsed")===!0,...typeof Ov=="number"&&Number.isFinite(Ov)?{width:Ov}:{}},u2=sr("local",p2),Pa={off:vs(u2,"off")===!0,muted:gd(vs(u2,"muted"))};function f2(){md("local",p2,Pa)}function $v(t){return Pa.off?!1:!t||!Pa.muted.includes(t)&&!Fv.has(t)}const Fv=new Set;function Z6(t){return Fv.add(t),()=>Fv.delete(t)}function m2(){const t=sr("local",s2),e=new Map(gd(sr("local",r2)).map((a,i)=>[a,i])),n=a=>(a.kind==="note"?"n:":"f:")+a.path;return[...gd(vs(t,"folders")).map(a=>({kind:"folder",path:a})),...gd(vs(t,"notes")).map(a=>({kind:"note",path:a}))].sort((a,i)=>(e.get(n(a))??1e9)-(e.get(n(i))??1e9))}function g2(){try{localStorage.removeItem(s2),localStorage.removeItem(r2)}catch{}}function uu(){md("local",l2,Eo)}function J6(){return new Set(gd(sr("local",c2)))}function Uv(t){md("local",c2,Array.from(t))}function Q6(){const t=sr("local",d2);return typeof t=="string"?t:""}function eL(t){md("local",d2,t)}function v2(){const t=sr("session",Dv),e=vs(t,"sig"),n=vs(t,"tags");if(typeof e!="string"||!Array.isArray(n))return null;const a=n.filter(i=>Array.isArray(i)&&typeof i[0]=="string"&&Array.isArray(i[1]));return{sig:e,tags:a}}function tL(t,e){md("session",Dv,{sig:t,tags:e})}function Bv(){try{sessionStorage.removeItem(Dv)}catch{}}const N={page:"brain",tree:{},folders:[],folderMeta:{},stats:{notes:0,links:0,folders:0},health:{},config:{},me:null,open:J6(),filter:"",note:null,editing:!1,graph:{nodes:[],links:[],stop:null},tags:{index:null,built:!1,active:null,progress:0},peekPath:null,keysDeleted:[]};function en(){const t=[];for(const e of Object.keys(N.tree))for(const n of N.tree[e]||[])t.push({...n,folder:n.folder||e});return t}let x2=null;const Hv=new Map;function lt(t){const e=String(t||"");if(x2!==N.tree){x2=N.tree,Hv.clear();for(const n of Object.keys(N.tree))for(const a of N.tree[n]||[])a.title&&Hv.set(a.path,a.title)}return Hv.get(e)||or((e.split("/").pop()||e).replace(/\.md$/i,""))}function b2(){return Object.keys(N.tree).sort((t,e)=>t==="Root"?-1:e==="Root"?1:t.localeCompare(e))}function Yn(t){const e=N.folderMeta[t];return e&&e.color||jn(t)}const y2=[];let qv=N.note;Object.defineProperty(N,"note",{enumerable:!0,configurable:!0,get:()=>qv,set:t=>{if(t!==qv){qv=t;for(const e of y2)try{e(t)}catch(n){console.error("note listener failed",n)}}}});function nL(t){y2.push(t)}async function aL(t){if(window.matchMedia("(max-width: 760px)").matches){te.openNote(t);return}N.peekPath=t,H("#peek").classList.remove("hidden"),H("#peekFolder").textContent=i2(t)+" / "+dn(t),H("#peekBody").innerHTML='<div class="empty">Loading...</div>';try{const e=await Oe("/api/note?path="+encodeURIComponent(t));if(N.peekPath!==t)return;H("#peekBody").innerHTML=e.html||`<pre>${x(e.content||"")}</pre>`}catch(e){if(N.peekPath!==t)return;H("#peekBody").innerHTML=`<div class="empty">Could not load: ${x(e.message)}</div>`}}function Wv(){N.peekPath=null,H("#peek").classList.add("hidden")}const Ha={home:{label:"Overview",title:"Overview",hint:"Your notes and agents at a glance",icon:"overview",group:"system",path:"/overview"},brain:{label:"Brain",title:"Brain",hint:"Your memory as a living brain",icon:"brain",group:"content",path:"/brain"},vault:{label:"Notes",title:"Notes",hint:"Browse, read and write your notes",icon:"note",group:"content",path:"/nodes"},graph:{label:"Graph",title:"Graph",hint:"Map of every link between notes",icon:"graph",group:"content",path:"/brain?mode=graph"},canvas:{label:"Canvas",title:"Canvas",hint:"Arrange notes on an open board",icon:"canvas",group:"content",path:"/brain?mode=canvas"},tags:{label:"Tags",title:"Tags",hint:"Every tag and its notes",icon:"tags",group:"content",path:"/tags"},logs:{label:"Activity",title:"Activity",hint:"What your agents read and changed",icon:"activity",group:"system",path:"/activity"},keys:{label:"Agents",title:"Agents & API keys",hint:"Connect AI apps and choose what they may do",icon:"key",group:"system",path:"/agents"},tools:{label:"Tools",title:"MCP tools",hint:"Turn agent tools on or off",icon:"tools",group:"system",path:"/tools"},access:{label:"Access rules",title:"Access rules",hint:"Which addresses may reach Memora",icon:"shield",group:"system",path:"/access"},settings:{label:"Settings",title:"Settings",hint:"Account, appearance and preferences",icon:"settings",group:"system",path:"/settings"},docs:{label:"Documentation",title:"Documentation",hint:"Guides, agent instructions and reference",icon:"book",group:"system",path:"/docs"},assistant:{label:"Mnemo",title:"Mnemo",hint:"Your notes agent: ask, find, write and tidy",icon:"mnemo",group:"content",path:"/mnemo"},trash:{label:"Trash",title:"Trash",hint:"Deleted notes, ready to restore",icon:"trash",group:"system",path:"/trash"}},_o=Object.keys(Ha);function Gv(t){return typeof t=="string"&&Object.prototype.hasOwnProperty.call(Ha,t)}const w2=/[\u0000-\u001f\u007f]/;function iL(t){if(!t||t.length>1024||t.startsWith("/")||t.includes("\\")||w2.test(t)||/^[a-zA-Z]:/.test(t))return null;const e=t.split("/");for(const n of e)if(!n||n==="."||n===".."||w2.test(n))return null;return e.join("/")}function k2(t){return"/node/"+t.split("/").map(encodeURIComponent).join("/")}const xs=new Map(_o.map(t=>[Ha[t].path,t]));xs.set("/vault","vault"),xs.set("/home","home"),xs.set("/welcome","home"),xs.set("/logs","logs"),xs.set("/keys","keys"),xs.set("/graph","graph"),xs.set("/canvas","canvas");function oL(t){return t==="graph"||t==="canvas"?"brain":t}function sL(t){const e=new URLSearchParams(t.search).get("mode");return e==="graph"||e==="canvas"?e:"brain"}let wl=null;function rL(t){wl=t}let kl=!1;function fu(t){kl=t}function lL(){const t=wl;return wl=null,t}let vd=null,Vv=null;function xd(t){if(vd=t,N.page!=="assistant")return;const e=t?`/mnemo/${t}`:"/mnemo";if(location.pathname!==e)try{history.replaceState({page:"assistant"},"",e)}catch{}}function cL(){const t=Vv;return Vv=null,t}const jv=["overview","setup","activity","access","settings"];let rr=null;function lr(t){rr=t}const dL=new RegExp(`^/(?:new(?:/[a-z0-9-]{1,40})?|[A-Za-z0-9_-]{1,64}(?:/(?:${jv.join("|")}))?)$`),pL=/^#connect(?:=([\w-]{1,40}))?$/;function S2(t=location){const e=t.pathname.replace(/\/+$/,"")||"/",n=e==="/docs"||e.startsWith("/docs/"),a=t.hash.replace(/^#\/?/,"").split(/[/?]/)[0];if(a&&Gv(a)&&!n)return{page:a};if(n)return{page:"docs"};if(e==="/"||e==="/index.html"||e==="/brain")return{page:sL(t)};if(e.startsWith("/node/")){const l=e.slice(6).split("/"),c=[];for(const p of l)try{c.push(decodeURIComponent(p))}catch{return{page:"vault",badNode:!0}}if(c.some(p=>p.includes("/")))return{page:"vault",badNode:!0};const d=iL(c.join("/"));return d?{page:"vault",node:d}:{page:"vault",badNode:!0}}if(e==="/activity/timeline"||e==="/activity")return kl=e!=="/activity",{page:"logs"};const i=/^\/activity\/([A-Za-z0-9_-]{1,64})$/.exec(e);if(i)return wl=i[1],{page:"logs"};const o=/^\/(?:agents|keys)(\/.*)?$/.exec(e);if(o){const l=o[1]||"",c=l?null:pL.exec(t.hash);if(c)rr="/agents/new"+(c[1]?"/"+c[1].toLowerCase():"");else if(l&&dL.test(l))rr="/agents"+l;else{if(l)return{page:"brain",unknown:!0};rr=null}return{page:"keys"}}const s=/^\/mnemo\/(c[0-9a-f]{12})$/.exec(e);if(s)return Vv=s[1],vd=s[1],{page:"assistant"};e==="/mnemo"&&(vd=null);const r=xs.get(e);return r?{page:r}:{page:"brain",unknown:!0}}function hL(t){const e=en(),n=e.find(a=>a.path===t)||e.find(a=>a.path===t+".md")||e.find(a=>a.path.replace(/\.md$/i,"")===t);return n?n.path:null}function uL(t,e,n){if(t.unknown)return{kind:"missing",missing:{what:"page",label:e}};if(t.page==="vault"&&(t.badNode||t.node)){const a=t.node?n(t.node):null;if(a)return{kind:"node",path:a};let i=t.node||e.replace(/^\/node\/?/,"");if(!t.node)try{i=decodeURIComponent(i)}catch{}return{kind:"missing",missing:{what:"node",label:i||e}}}return{kind:"page",page:t.page}}let Yv=null;function fL(t){if(t==="docs"){const e=Yv;if(Yv=null,e)return e;const n=location.pathname;return n==="/docs"||n.startsWith("/docs/")?n+location.hash:"/docs"}if(t==="logs"&&wl)return"/activity/"+wl;if(t==="logs"&&kl)return"/activity/timeline";if(t==="assistant"&&vd)return`/mnemo/${vd}`;if(t==="keys"&&rr){const e=rr;return rr=null,e}return t==="vault"&&N.note?k2(N.note):Ha[t].path}let Xv=!1;function zi(){Xv=!0}function mu(){const t=fL(N.page),e=Xv;if(Xv=!1,location.pathname+location.search+location.hash!==t)try{e?history.replaceState({page:N.page},"",t):history.pushState({page:N.page},"",t)}catch{}}const Kv={},M2=[];function qa(t){M2.push(t)}function ba(t,e){Kv[t]=e}function Zv(){const t=N.page,e=H(".crumb"),n=t==="vault"&&N.note?lt(N.note):Ha[t].title;e.textContent=n,e.title=t==="vault"&&N.note?N.note:"",document.title=n+" · Memora"}let Jv=null;function mL(t){Jv=t}function ra(t,e=!1){if(Gv(t)||(t="brain"),!e&&N.editing&&Jv&&Jv(()=>ra(t,e),()=>{zi(),mu()}))return;e||(N.editing=!1);const n=N.page;N.page=t,Bn("[data-page].nav-item,[data-page].tab-item,[data-page].pm-item").forEach(a=>{const i=a.dataset.page===oL(t);a.classList.toggle("active",i),i?a.setAttribute("aria-current","page"):a.removeAttribute("aria-current")});for(const a of _o)H("#view-"+a).classList.toggle("hidden",a!==t);Zv(),H("#app").classList.remove("side-open"),t!=="graph"&&N.graph.stop&&(N.graph.stop(),N.graph.stop=null),Wv(),mu();for(const a of M2)try{a(t)}catch(i){console.error("navigate listener failed",i)}n!==t&&(H("#views").scrollTop=0),Kv[t]?.()}function bd(t="",e=""){Yv="/docs"+(t?"/"+encodeURIComponent(t):"")+(e?"#"+encodeURIComponent(e):""),ra("docs")}function A2(){Kv[N.page]?.()}nL(()=>{N.page==="vault"&&(mu(),Zv())});const T2={brain:'<path d="M9.5 4.5A2.5 2.5 0 0 0 7 7a2.6 2.6 0 0 0-2.5 3.2A3 3 0 0 0 5 15.6 2.8 2.8 0 0 0 9.5 19.5V4.5z"/><path d="M14.5 4.5A2.5 2.5 0 0 1 17 7a2.6 2.6 0 0 1 2.5 3.2 3 3 0 0 1-.5 5.4 2.8 2.8 0 0 1-4.5 3.9V4.5z"/><path d="M9.5 9H8M14.5 9H16M9.5 14H7.5M14.5 14h2"/>',overview:'<rect x="3.5" y="3.5" width="7" height="8" rx="2"/><rect x="13.5" y="3.5" width="7" height="5" rx="2"/><rect x="13.5" y="11.5" width="7" height="9" rx="2"/><rect x="3.5" y="14.5" width="7" height="6" rx="2"/>',vault:'<path d="M3.5 7.5a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/><path d="M3.5 10.5h17"/>',graph:'<circle cx="6" cy="17" r="2.4"/><circle cx="17.5" cy="6.5" r="2.4"/><circle cx="17.5" cy="17.5" r="2.2"/><path d="M7.9 15.3 15.4 8.4M8.8 17.4h6.3"/>',canvas:'<rect x="3.5" y="3.5" width="17" height="17" rx="3"/><rect x="6.5" y="7" width="5" height="4" rx="1"/><rect x="12.5" y="12.5" width="5" height="4.5" rx="1"/><path d="M11.5 9h3a1 1 0 0 1 1 1v2.5"/>',tags:'<path d="M4 12.5V6a2 2 0 0 1 2-2h6.5L20 11.5a2 2 0 0 1 0 2.8l-5.7 5.7a2 2 0 0 1-2.8 0z"/><circle cx="8.2" cy="8.2" r="1.3"/>',activity:'<path d="M3 12h3.5l2.5-6 3 12 2.5-6H21"/>',agents:'<rect x="4.5" y="7.5" width="15" height="11" rx="3"/><path d="M12 3.5v4M9 12.5h.01M15 12.5h.01M9.5 15.5h5"/><path d="M2.5 12v2.5M21.5 12v2.5"/>',key:'<circle cx="8" cy="12" r="3.2"/><path d="M11.2 12H21M18 12v3M15 12v2.2"/>',tools:'<rect x="3" y="4.5" width="18" height="6.5" rx="3.25"/><circle cx="15.6" cy="7.75" r="1.6"/><rect x="3" y="13" width="18" height="6.5" rx="3.25"/><circle cx="8.4" cy="16.25" r="1.6"/>',shield:'<path d="M12 3 19 6v6c0 4.2-2.9 7.6-7 9-4.1-1.4-7-4.8-7-9V6z"/><path d="m9.2 12 2 2 3.8-4"/>',settings:'<path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20.5 20.5-4.3-4.3"/>',more:'<circle cx="5" cy="12" r="1.3"/><circle cx="12" cy="12" r="1.3"/><circle cx="19" cy="12" r="1.3"/>',menu:'<path d="M4 7h16M4 12h16M4 17h10"/>',sidebar:'<rect x="3.5" y="4.5" width="17" height="15" rx="3"/><path d="M9.5 4.5v15"/>',"chev-left":'<path d="m14.5 6-6 6 6 6"/>',"chev-right":'<path d="m9.5 6 6 6-6 6"/>',"chev-down":'<path d="m6 9.5 6 6 6-6"/>',close:'<path d="M6 6l12 12M18 6 6 18"/>',plus:'<path d="M12 5v14M5 12h14"/>',note:'<path d="M7 3.5h7l4.5 4.5v11a1.5 1.5 0 0 1-1.5 1.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8h4.5M8.5 13h7M8.5 16.5h5"/>',folder:'<path d="M3.5 7.5a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/>',trash:'<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/>',"folder-plus":'<path d="M3.5 7.5a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/><path d="M12 11v5M9.5 13.5h5"/>',sun:'<circle cx="12" cy="12" r="4"/><path d="M12 2.5v2M12 19.5v2M4.6 4.6 6 6M18 18l1.4 1.4M2.5 12h2M19.5 12h2M4.6 19.4 6 18M18 6l1.4-1.4"/>',moon:'<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>',monitor:'<rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/>',image:'<rect x="3" y="4" width="18" height="16" rx="2.5"/><circle cx="9" cy="9.5" r="1.8"/><path d="m21 16-5-5L5 20"/>',book:'<path d="M4.5 5.5A2 2 0 0 1 6.5 3.5h12v14h-12a2 2 0 0 0-2 2z"/><path d="M4.5 19.5a2 2 0 0 0 2 2h12v-4"/><path d="M9 8h6M9 11.5h4"/>',help:'<circle cx="12" cy="12" r="9.2"/><path d="M9.6 9.3a2.4 2.4 0 1 1 3.3 2.2c-.8.4-1.1.9-1.1 1.7M12 16.6h.01"/>',download:'<path d="M12 3.5v12"/><path d="m7 10.5 5 5 5-5"/><path d="M4.5 19.5h15"/>',refresh:'<path d="M20 11a8 8 0 1 0-2.3 6.3"/><path d="M20 5v6h-6"/>',logout:'<path d="M15 4.5h3a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-3"/><path d="M10 16.5 5.5 12 10 7.5M5.5 12H15"/>',user:'<circle cx="12" cy="8.5" r="3.8"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/>',pin:'<path d="M12 17v4.5M8.5 3h7l-1 6 3 3v2h-11v-2l3-3z"/>',bell:'<path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z"/><path d="M10 20.5a2.2 2.2 0 0 0 4 0"/>',bolt:'<path d="M13 2.5 4.5 13.5H12l-1 8 8.5-11H12z"/>',wifi:'<path d="M2.5 9a14 14 0 0 1 19 0M5.5 12.5a9.5 9.5 0 0 1 13 0M8.6 16a5 5 0 0 1 6.8 0"/><circle cx="12" cy="19.3" r=".9"/>',"wifi-off":'<path d="M3 3l18 18M8.6 16a5 5 0 0 1 6.8 0M5.5 12.5a9.5 9.5 0 0 1 4-2.3M14.6 10.3a9.5 9.5 0 0 1 3.9 2.2M2.5 9a14 14 0 0 1 4-2.6M11 5.6A14 14 0 0 1 21.5 9"/><circle cx="12" cy="19.3" r=".9"/>',enter:'<path d="M19.5 5v6a3 3 0 0 1-3 3h-12"/><path d="m8.5 10-4 4 4 4"/>',arrow:'<path d="M5 12h14M13 6l6 6-6 6"/>',check:'<path d="m5 12.5 4.5 4.5L19 7.5"/>',alert:'<path d="M12 3.5 2.8 19.5h18.4z"/><path d="M12 10v4.5M12 17.2h.01"/>',info:'<circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.8h.01"/>',x_circle:'<circle cx="12" cy="12" r="9"/><path d="m9 9 6 6M15 9l-6 6"/>',mnemo:'<path d="M4 18v-8a2.6 2.6 0 0 1 5.2 0v4.2a2.8 2.8 0 0 0 5.6 0V10a2.6 2.6 0 0 1 5.2 0v8"/><path d="M12 2.8v2.6M10.7 4.1h2.6"/>',send:'<path d="M12 19V5M6 11l6-6 6 6"/>',stop:'<rect x="6.5" y="6.5" width="11" height="11" rx="2.5"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="2.5"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>',edit:'<path d="M4.5 19.5h4l10-10a2.1 2.1 0 0 0-4-4l-10 10z"/><path d="m13.5 6.5 4 4"/>',star:'<path d="m12 4 2.4 5 5.4.6-4 3.7 1.1 5.3L12 16l-4.9 2.6 1.1-5.3-4-3.7 5.4-.6z"/>',code:'<path d="m8.5 7.5-5 4.5 5 4.5M15.5 7.5l5 4.5-5 4.5M13.5 5l-3 14"/>',eye:'<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="2.8"/>',"eye-off":'<path d="M10 5.7A9.6 9.6 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a16 16 0 0 1-2.4 3.2M6.3 7.2C3.9 8.8 2.5 12 2.5 12S6 18.5 12 18.5a9 9 0 0 0 4.4-1.1M4 4l16 16"/><path d="M9.9 10a2.8 2.8 0 0 0 4 4"/>',chat:'<path d="M5 18.5V7a2.5 2.5 0 0 1 2.5-2.5h9A2.5 2.5 0 0 1 19 7v6.5a2.5 2.5 0 0 1-2.5 2.5H9z"/><path d="M9 9.5h6M9 12.5h3.5"/>',expand:'<path d="M14 4.5h5.5V10M10 19.5H4.5V14M19.5 4.5 13.5 10.5M4.5 19.5l6-6"/>',chev:'<path d="m9 6 6 6-6 6"/>',sparkle:'<path d="M12 3.5 13.8 9 19.5 10.8 13.8 12.6 12 18.5 10.2 12.6 4.5 10.8 10.2 9z"/><path d="M19 3.5v3M17.5 5h3"/>',command:'<path d="M9 6.5A2.5 2.5 0 1 0 6.5 9H9zM15 6.5A2.5 2.5 0 1 1 17.5 9H15zM9 17.5A2.5 2.5 0 1 1 6.5 15H9zM15 17.5a2.5 2.5 0 1 0 2.5-2.5H15zM9 9h6v6H9z"/>'};function gL(t){return T2[t]||T2.note}function V(t,e="i"){return`<svg class="${e}" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true" focusable="false">${gL(t)}</svg>`}const vL={ok:"check",warn:"alert",err:"alert",info:"info"},E2=3,xL=12,gn=[];let Qv=!1,Di=!1;const ex=()=>window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;function tx(){return H("#toasts")}function yd(t){if(!ex())for(const e of gn){const n=t.get(e.node);if(n==null)continue;const a=n-e.node.getBoundingClientRect().top;a&&(e.node.style.transition="none",e.node.style.transform=`translateY(${a}px)`,requestAnimationFrame(()=>{e.node.style.transition="",e.node.style.transform=""}))}}function gu(){return new Map(gn.map(t=>[t.node,t.node.getBoundingClientRect().top]))}function nx(t,e){window.clearTimeout(t.timer),!t.sticky&&(t.left=e,t.until=Date.now()+e,Qv||(t.timer=window.setTimeout(()=>wd(t.node),e)))}function Sl(){const t=tx();if(!t.classList)return;const e=Math.max(0,gn.length-E2);e||(Di=!1),gn.forEach((i,o)=>i.node.classList.toggle("stowed",!Di&&o>=E2));let n=t.querySelector(".t-more");e&&!n&&(n=re("button","t-more"),n.type="button",n.onclick=()=>{const i=gu();Di=!Di,Sl(),yd(i)},t.prepend(n)),n&&(e?(n.textContent=Di?"Show fewer":`+${e} more`,n.setAttribute("aria-expanded",String(Di)),n.setAttribute("aria-label",Di?"Show only the latest notifications":`Show ${e} more notification${e===1?"":"s"}`)):n.remove()),t.classList.toggle("expanded",Di);const a=gn.length?Math.ceil(t.getBoundingClientRect().height):0;document.documentElement.style.setProperty("--toasts-h",a?a+12+"px":"0px")}function wd(t,e=!1){const n=gn.findIndex(o=>o.node===t);if(n<0)return;const[a]=gn.splice(n,1);window.clearTimeout(a.timer);const i=gu();t.classList.add(e?"out-fast":"out"),t.style.pointerEvents="none",window.setTimeout(()=>{t.remove(),Sl(),yd(i)},ex()?0:e?160:260)}function bL(t){const e=gn.find(n=>n.group===t);e&&wd(e.node,!0)}function yL(t){return gn.some(e=>e.group===t)}function wL(t){let e=0,n=0,a=-1;t.addEventListener("pointerdown",o=>{o.target.closest("button")||(a=o.pointerId,e=o.clientX,n=0,t.setPointerCapture(a),t.style.transition="none")}),t.addEventListener("pointermove",o=>{o.pointerId===a&&(n=Math.max(0,o.clientX-e),t.style.transform=`translateX(${n}px)`,t.style.opacity=String(1-Math.min(.9,n/220)))});const i=o=>{o.pointerId===a&&(a=-1,t.style.transition="",n>70?(t.style.transform=`translateX(${n+120}px)`,t.style.opacity="0",wd(t,!0)):(t.style.transform="",t.style.opacity=""))};t.addEventListener("pointerup",i),t.addEventListener("pointercancel",i)}function _2(t,e,n,a,i){t.className="toast "+n+(i?.iconHtml?" has-av":""),t.innerHTML=`<span class="t-ico">${i?.iconHtml||V(vL[n]||"info")}</span><span class="t-msg">${x(e)}</span>${a?`<button type="button" class="t-act">${a.icon||""}${x(a.label)}</button>`:""}<button type="button" class="t-x" aria-label="Dismiss" title="Dismiss">${V("close")}</button>`,n==="err"?t.setAttribute("role","alert"):t.removeAttribute("role"),t.querySelector(".t-x").onclick=()=>wd(t,!0);const o=t.querySelector(".t-act");o&&a&&(o.onclick=async()=>{o.disabled=!0,wd(t,!0),await a.run()})}function Xn(t,e="ok",n=4200,a,i){const o=tx();if(!o.classList)return;const s=e==="err",r=gu(),l=i?.group?gn.find(p=>p.group===i.group):void 0;if(l){gn.splice(gn.indexOf(l),1),gn.unshift(l),l.sticky=s,_2(l.node,t,e,a,i),o.appendChild(l.node),ex()||(l.node.classList.remove("bump"),l.node.offsetWidth,l.node.classList.add("bump")),Sl(),yd(r),nx(l,n);return}const c=re("div","toast");_2(c,t,e,a,i),o.appendChild(c);const d={node:c,until:0,timer:0,left:n,sticky:s,group:i?.group};for(gn.unshift(d),wL(c);gn.length>xL;){const p=[...gn].reverse().find(h=>!h.sticky)||gn[gn.length-1];gn.splice(gn.indexOf(p),1),window.clearTimeout(p.timer),p.node.remove()}Sl(),yd(r),nx(d,n)}function ye(t,e="ok",n=4200){Xn(t,e,n)}let C2=!1;function kL(){if(C2)return;const t=tx();t.classList&&(C2=!0,t.addEventListener("pointerenter",()=>{Qv=!0;for(const e of gn)window.clearTimeout(e.timer),!e.sticky&&(e.left=Math.max(600,e.until-Date.now()))}),t.addEventListener("pointerleave",()=>{if(Qv=!1,Di){const e=gu();Di=!1,Sl(),yd(e)}for(const e of gn)nx(e,Math.max(1200,e.left))}),window.addEventListener("resize",()=>Sl(),{passive:!0}))}const ax=new Map;function Hn(t,e){let n=ax.get(t);n||ax.set(t,n=new Set);const a=e;return n.add(a),()=>n.delete(a)}function kd(t,e){ax.get(t)?.forEach(n=>{try{n(e)}catch(a){console.error("bus handler failed",t,a)}})}async function bs(){const[t,e,n,a,i]=await Promise.all([Oe("/api/tree").catch(()=>({})),Oe("/api/folders").catch(()=>null),Oe("/api/stats").catch(()=>({notes:0,links:0,folders:0})),Oe("/api/folder-meta").catch(()=>({})),Oe("/healthz").catch(()=>({}))]);N.tree=t||{},e&&(N.folders=Array.isArray(e.folders)?e.folders:[]),N.stats=n||N.stats,N.folderMeta=a||{},N.health=i||{},te.renderTree()}function vu(){return N.folders.length?new Set(N.folders.map(t=>t.split("/")[0]).filter(t=>t&&!/^root$/i.test(t)&&!t.startsWith("."))).size:N.stats.folders||0}function ix(t){const e=t.toLowerCase();return/^(search|query|find|suggest)/.test(e)?"search":/^(create|batch_create|template_create|duplicate|import|save)/.test(e)?"create":/^(delete|bulk_delete|soft_delete)/.test(e)?"delete":/^(move|rename)/.test(e)?"move":/^(patch|update|set_tags|add_tags|remove_tags|merge|restore|bulk_replace|pin|unpin)/.test(e)?"edit":/^(read|get|list|export|diff|digest|folder_stats|link_stats|broken_links|follow_ups|stale)/.test(e)?"read":"other"}const ox={create:"created",edit:"edited",delete:"deleted",move:"moved",search:"searched for",read:"read",other:"used"};function SL(t,e=48){const n=(t.split("/").pop()||t).replace(/\.md$/i,"").trim();return n.length>e?n.slice(0,e-1)+"…":n}function L2(t,e){if(!e.length)return t;const n=new Set(e.map(o=>ix(o.action)));if(e.length===1){const o=e[0],s=ix(o.action),r=SL(o.label||"");return s==="other"?`${t} used ${o.action.replace(/[_.]+/g," ").trim()||"Memora"}`:r?s==="search"?`${t} searched for “${r}”`:`${t} ${ox[s]} ${r}`:`${t} ${s==="search"?"searched your notes":ox[s]+" a note"}`}const a=new Set(e.map(o=>o.label)).size;if(n.size===1){const o=[...n][0];return o==="search"?`${t} searched your notes ${e.length} times`:o==="other"?`${t} used Memora ${e.length} times`:a===1?L2(t,[e[0]]):`${t} ${ox[o]} ${a} note${a===1?"":"s"}`}const i=e.filter(o=>!["search","read","other"].includes(ix(o.action)));if(i.length){const o=new Set(i.map(s=>s.label)).size;return`${t} changed ${o} note${o===1?"":"s"}`}return`${t} looked through your notes (${e.length} times)`}const sx=["#2dd4bf","#60a5fa","#a78bfa","#f472b6","#fb923c","#facc15","#4ade80","#38bdf8","#e879f9","#f87171","#a3e635","#818cf8"];function ML(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e>>>0}function Co(t){return String(t||"").trim().toLowerCase()}const Ml=new Map,rx=new Map;let lx=null;function R2(t){return lx?lx.has(t):null}const P2="memora:agent-colors";function Sd(t){const e=JSON.stringify([...Ml]);lx=new Set(t.map(a=>a.id)),Ml.clear(),rx.clear();const n=new Map;for(const a of t){const i=a.color&&/^#[0-9a-f]{6}$/i.test(a.color)?a.color.toLowerCase():null;i&&Ml.set(a.id,i);const o=Co(a.name||a.id);n.set(o,n.has(o)&&n.get(o)!==i?null:i)}n.forEach((a,i)=>a&&rx.set(i,a)),JSON.stringify([...Ml])!==e&&window.dispatchEvent(new Event(P2))}function An(t,e){if(e&&Ml.has(e))return Ml.get(e);const n=Co(t);return n?rx.get(n)||sx[ML(n)%sx.length]:"#94a3b8"}function Md(t){const n=String(t||"?").trim().split(/[\s._\-/:@()]+/).filter(Boolean);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();const a=n[0]||"?";return(a.length>1?a[0]+a[1]:a[0]).toUpperCase()}function Yt(t,e=30,n="",a){if(a==="mnemo")return`<span class="ag-av ag-mn${n?" "+n:""}" aria-hidden="true" style="width:${e}px;height:${e}px">${V("mnemo")}</span>`;const i=An(t,a),o=Math.max(9,Math.round(e*.38));return`<span class="ag-av${n?" "+n:""}" aria-hidden="true" style="--ag:${i};width:${e}px;height:${e}px;font-size:${o}px">${x(Md(t))}</span>`}const I2={create_memory:"created",batch_create:"created",duplicate_memory:"created",template_create:"created",import_memory:"created",create_folder:"created",node_created:"created",save_memory:"edited",patch_memory:"edited",add_tags:"edited",remove_tags:"edited",set_tags:"edited",bulk_replace:"edited",merge_memory:"edited",rename_tag:"edited",merge_tag:"edited",set_folder_meta:"edited",restore_memory:"edited",mention_agent:"edited",node_updated:"edited",move_memory:"moved",rename_memory:"moved",move_folder:"moved",move_folder_contents:"moved",rename_folder:"moved",node_renamed:"moved",soft_delete:"trashed",bulk_delete:"trashed",delete_folder:"trashed",delete_memory:"deleted",node_deleted:"deleted",restore_trash:"restored",pin:"pinned",unpin:"pinned",search_memory:"searched",search_by_tag:"searched",query_memory:"searched",find_similar:"searched",suggest_links:"searched",find_path:"searched",search_logs:"searched",set_my_name:"other",set_my_color:"other",lock_node:"other",release_lock:"other",snapshot:"other"},N2=/^(get_|list_|read_|link_stats|folder_stats|broken_links|diff|digest|healthcheck|stale_detection|validate_|presence|follow_ups|export_|admin_list|privacy_list)/,AL=/^(gateway|memora|memora-cli|system|server)$/i,TL=new Set(["actor_alias","key_color","folder_meta"]),Ad=(t,e)=>{const n=t.raw[e];return typeof n=="string"?n:""};function ys(t){if(t.source==="auth")return"system";const e=t.action;return I2[e]?I2[e]:(/^(admin_|privacy_)/.test(e),N2.test(e)?"read":"other")}function ci(t){return t.source==="auth"||AL.test(t.actor)||TL.has(Ad(t,"type"))?!0:!!t.echo}function EL(t){return t.raw.refused===!0}function la(t){return t.running||t.ok!==!1?null:EL(t)?"refused":"failed"}function Oi(t,e=""){return Ad(t,"actor_kind")==="user"||e&&t.actor===e?"You":t.actor}function ws(t){return t.split("/").pop()||t}function cr(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}const Tn=t=>`<em class="act-n">${x(t)}</em>`;function ca(t){return dn(t).replace(/_/g," ")}function Al(t,e){const n=ca(t);return e?`<button type="button" class="act-n" data-note="${C(t)}" title="${C(t)}">${x(n)}</button>`:Tn(n)}function _L(t){const e=t.raw.count;return typeof e=="number"?String(e):t.paths.length>=20?"20+":String(t.paths.length)}function di(t,e,n=e+"s"){return`${t} ${String(t)==="1"?e:n}`}function xu(t){return`“${x(t.length>80?t.slice(0,79)+"…":t)}”`}function cx(t){return t.paths.length>=2?t.paths[1]:""}function da(t){const e=la(t);return e?RL(t,e):z2(t)}function z2(t){const e=t.action,n=ys(t),a=t.paths[0]||"",o=a?Al(a,n!=="deleted"&&n!=="trashed"):"",s=t.label&&!t.paths.includes(t.label)?t.label:"",r=d=>Tn(ws(d)),l=t.raw.folders,c=Array.isArray(l)&&typeof l[0]=="string"?l[0]:"";switch(n){case"system":return O2(t);case"created":{if(e==="create_folder")return`created the folder ${Tn(s||a)}`;if(t.paths.length>1&&e!=="create_memory")return`created ${di(t.paths.length,"note")}`;if(a){const d=cr(a);return`created ${o}${d?` in ${r(d)}`:""}`}return s?`created ${Tn(s)}${c?` in ${r(c)}`:""}`:"created a note"}case"edited":return e==="add_tags"||e==="remove_tags"||e==="set_tags"?a?`changed the tags of ${o}`:"changed some tags":e==="bulk_replace"?t.paths.length?`replaced text in ${di(t.paths.length,"note")}`:"replaced text in your notes":e==="merge_memory"?a?`merged notes into ${o}`:"merged notes":e==="rename_tag"||e==="merge_tag"?s?`renamed the tag ${Tn(s)}`:"renamed a tag":e==="set_folder_meta"?`changed the details of the folder ${Tn(ws(s||a))}`:e==="restore_memory"?a?`brought back an earlier version of ${o}`:"brought back an earlier version of a note":e==="mention_agent"?a?`left a message in ${o}`:"left a message for another AI":a?`edited ${o}`:"changed your notes";case"moved":{if(e==="move_folder"||e==="move_folder_contents"||e==="rename_folder"){const p=Tn(ws(s||a));return e==="rename_folder"?`renamed the folder ${p}`:e==="move_folder"?`moved the folder ${p}`:`moved what is in ${p}`}const d=cx(t);if(d){if(cr(d)===cr(a)&&ca(d)!==ca(a))return`renamed ${Tn(ca(a))} to ${Al(d,!0)}`;const p=cr(d);return`moved ${Al(d,!0)} to ${p?r(p):"the top level"}`}return e==="rename_memory"?a?`renamed ${Tn(ca(a))}`:"renamed a note":a&&c?`moved ${Tn(ca(a))} to ${/^root$/i.test(c)?"the top level":r(c)}`:a?`moved ${Tn(ca(a))}`:"moved a note"}case"trashed":return e==="delete_folder"?`moved the folder ${Tn(ws(s||a))} to Trash`:t.paths.length>1?`moved ${di(t.paths.length,"note")} to Trash`:a?`moved ${o} to Trash`:"moved notes to Trash";case"deleted":return a?`deleted ${o}`:"deleted a note";case"restored":return s||a?`brought back ${Tn(ca(s||a))} from Trash`:"brought back a note from Trash";case"pinned":{const d=a?a.endsWith(".md")?o:`the folder ${Tn(ws(a))}`:"";return e==="unpin"?d?`unpinned ${d}`:"unpinned something":d?`pinned ${d}`:"pinned something"}case"searched":{const d=s||(e==="find_similar"||e==="suggest_links"?"":a);if(e==="find_similar")return a?`looked for notes like ${o}`:"looked for similar notes";if(e==="suggest_links")return a?`looked for links to add to ${o}`:"looked for links to add";if(e==="find_path")return t.paths.length>=2?`looked for a path from ${Al(a,!0)} to ${Al(t.paths[1],!0)}`:"looked for a path between notes";if(e==="search_logs")return d?`searched the activity log for ${xu(d)}`:"searched the activity log";const p=` (${di(_L(t),"result")})`;return e==="search_by_tag"?d?`looked for notes tagged ${Tn("#"+d.replace(/^#/,""))}${p}`:"looked for notes by tag":d?`searched ${xu(d)}${p}`:"searched your notes"}case"read":return CL(t,o,s);default:return e==="set_my_name"?s?`changed its name to ${Tn(s)}`:"changed its name":e==="set_my_color"?"changed its colour":e==="lock_node"?a?`reserved ${o} while it works on it`:"reserved a note":e==="release_lock"?a?`let go of ${o}`:"let go of a note":e==="snapshot"?"saved a snapshot of all your notes":e.startsWith("privacy_")?"changed who can see what":e.startsWith("admin_")?"changed a server setting":t.source==="vault"&&!t.action.startsWith("node_")?O2(t):a?`worked on ${o}`:"did something in your notes"}}function CL(t,e,n){const a=t.action,i=n&&!/\.md$/i.test(n)&&n.length<80?Tn(ws(n)):"";return a==="read_memory"?e?`read ${e}`:"read a note":a==="export_memory"?e?`exported ${e}`:"exported notes":a==="get_neighbors"||a==="get_subgraph"?e?`looked at notes linked to ${e}`:"looked at linked notes":a==="get_history"||a==="get_note_at"||a==="diff"?e?`looked at the history of ${e}`:"looked at a note’s history":a==="validate_memory"?e?`checked ${e}`:"checked a note":a==="list_memory"?i?`looked through ${i}`:"looked through your notes":a==="list_folders"||a==="folder_stats"?i?`looked at the folder ${i}`:"looked at your folders":a==="get_folder_meta"?i?`read the details of the folder ${i}`:"read folder details":a==="healthcheck"?"checked that Memora is working":a==="get_stats"||a==="digest"?"looked at an overview of your notes":/^(get_graph|link_stats|broken_links|get_hubs|get_isolated)$/.test(a)?"looked at how your notes link together":a==="get_tags"||a==="list_tags"?"looked at your tags":a==="get_logs"||a==="get_events"?"looked at recent activity":a==="list_trash"?"looked in Trash":a==="list_pins"?"looked at your pinned notes":/^(get_locks|get_assignments|presence|list_actors)$/.test(a)?"checked who is working on what":/^(get_todos|follow_ups|stale_detection)$/.test(a)?"looked for notes that need attention":a==="admin_list_tools"||a==="privacy_list"?"looked at the server settings":e?`read ${e}`:"looked through your notes"}function D2(t){const e=t.paths[0]||"",n=e?Tn(ca(e)):"",a=t.label&&!t.paths.includes(t.label)?t.label:"";switch(ys(t)){case"created":return n?`create ${n}`:a?`create ${Tn(a)}`:"create a note";case"edited":return n?`change ${n}`:"change your notes";case"read":return n?`read ${n}`:"look through your notes";case"searched":return a?`search ${xu(a)}`:"search your notes";case"moved":return n?`move ${n}`:"move a note";case"trashed":return n?`move ${n} to Trash`:"move notes to Trash";case"deleted":return n?`delete ${n}`:"delete a note";case"restored":return"bring back a note from Trash";case"pinned":return n?`pin ${n}`:"change your pins";default:return t.action.startsWith("admin_")||t.action.startsWith("privacy_")?"change a server setting":"do something"}}function LL(t){return/'write' scope/.test(t)?"but can only read":/'admin' scope/.test(t)?"but does not have full control":/disabled on this server/.test(t)?"but that is switched off on this server":/not allowed/.test(t)?"but is not allowed to":"but was refused"}function RL(t,e){return e==="refused"?`tried to ${D2(t)} ${LL(Ad(t,"error"))}`:`tried to ${D2(t)}, but it did not work`}const PL={signin:"signed in",signout:"signed out",signout_cli:"was signed out from the console",login_fail:"could not sign in",auth_fail:"could not sign in",key_fail:"an unknown key was refused",cooldown:"sign-in paused after too many tries",key_created:"made a new AI key",key_deleted:"removed an AI key",key_restored:"brought back an AI key",key_rolled:"made a new secret for an AI key",key_updated:"changed an AI key",key_permissions:"changed what an AI may do"};function O2(t){const e=PL[t.action],n=t.label&&t.label.length<120?t.label:"";if(e)return x(e);const a=t.action.replace(/[_.]+/g," ").trim();return`${x(a)}${n?` <span class="act-d">${x(n)}</span>`:""}`}const IL={"&":"&","<":"<",">":">",""":'"',"'":"'"};function Wa(t){return t.replace(/<[^>]*>/g,"").replace(/&(amp|lt|gt|quot|#39);/g,e=>IL[e]||e).replace(/\s+/g," ").trim()}function NL(t,e=""){return`${Oi(t,e)} ${Wa(da(t))}`}const zL=120,DL=600,$2=t=>Ad(t,"actor_id")||"name:"+t.actor,F2=t=>`${ys(t)}:${ys(t)==="read"&&t.action!=="read_memory"?"browse":""}`;function U2(t){const e=new Date(t*1e3);return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function bu(t,e=!0,n=zL,a=DL){const i=[];let o=[];const s=()=>{o.length&&(i.push({items:o,it:o[0],kind:ys(o[0]),span:Math.max(0,o[0].ts-o[o.length-1].ts)}),o=[])},r=l=>!!l.running||l.ok===!1||ci(l)||ys(l)==="system";for(const l of t){const c=o[o.length-1];e&&c&&!r(l)&&!r(c)&&$2(l)===$2(c)&&F2(l)===F2(c)&&c.ts-l.ts<=n&&o[0].ts-l.ts<=a&&U2(l.ts)===U2(c.ts)||s(),o.push(l)}return s(),i}function OL(t){if(t.items.length===1)return da(t.it);const e=t.items.length,n=[...new Set(t.items.map(r=>t.kind==="moved"&&cx(r)||r.paths[0]).filter(Boolean))],a=n.length,i=new Set(n.map(cr)),o=i.size===1&&[...i][0]?` in ${Tn(ws([...i][0]))}`:"",s=t.kind==="read"&&t.it.action!=="read_memory";switch(t.kind){case"read":return s||!a?`looked around your notes ${e} times`:`read ${di(a,"note")}${o}`;case"searched":{const r=[...new Set(t.items.map(l=>l.label&&!l.paths.includes(l.label)?l.label:""))];if(r.length<=3&&r.every(Boolean)){const l=r.map(xu);return`searched ${l.length>1?l.slice(0,-1).join(", ")+" and "+l[l.length-1]:l[0]}`}return`searched ${e} times`}case"created":return a?`created ${di(a,"note")}${o}`:`created ${e} notes`;case"edited":return a===1?`edited ${Al(n[0],!0)} ${e} times`:a?`edited ${di(a,"note")}${o}`:`made ${e} changes`;case"moved":return`moved ${di(Math.max(a,1),"note")}`;case"trashed":return`moved ${di(Math.max(a,1),"note")} to Trash`;case"deleted":return`deleted ${di(Math.max(a,1),"note")}`;case"restored":return`brought back ${di(e,"note")} from Trash`;case"pinned":return`changed your pins ${e} times`;default:return`did ${e} things`}}function $L(t){const e=Math.max(1,Math.round(t));return e<60?`${e} s`:`${Math.round(e/60)} min`}const FL=new Set(["create_memory","save_memory","patch_memory","delete_memory","move_memory","rename_memory"]),B2=15,Tl=t=>t.replace(/\.md$/i,"");function UL(t){const e=new Map;for(const i of t)i.source!=="vault"||!i.action.startsWith("node_")||(e.has(i.actor)||e.set(i.actor,[]),e.get(i.actor).push(i));if(!e.size&&!t.some(i=>i.source==="agent"))return;const n=new Set;for(const i of t){if(i.source!=="agent"||i.live)continue;const o=(e.get(i.actor)||[]).filter(l=>!n.has(l)&&l.ts>=i.ts-2&&l.ts-i.ts<=B2),s=i.action;let r;if(s==="create_memory"||s==="template_create"||s==="duplicate_memory")r=o.find(l=>l.action==="node_created"),r&&!i.paths.length&&r.paths[0]&&(i.paths=[r.paths[0]]);else if(s==="move_memory"||s==="rename_memory")r=o.find(l=>l.action==="node_renamed"&&Tl(Ad(l,"old_path"))===Tl(i.paths[0]||"")),r&&r.paths[0]&&i.paths.length<2&&(i.paths=[i.paths[0],r.paths[0]]);else{const l=new Set(i.paths.map(Tl));r=o.find(c=>c.paths.some(d=>l.has(Tl(d))))}r&&(n.add(r),r.echo=!0),i.ok===void 0&&!i.running&&FL.has(s)&&(i.ok=!!r)}const a=new Map;for(const i of t)if(i.source==="agent")for(const o of i.paths){const s=i.actor+"\0"+Tl(o);a.has(s)||a.set(s,[]),a.get(s).push(i.ts)}for(const i of e.values())for(const o of i)o.echo||o.paths.some(s=>(a.get(o.actor+"\0"+Tl(s))||[]).some(r=>Math.abs(r-o.ts)<=B2))&&(o.echo=!0)}const BL=7*86400;function H2(t,e,n=Date.now()/1e3){if(t.source!=="agent"||t.running||t.ok===!1||n-t.ts>BL)return null;const a=t.action;if(a==="move_memory"||a==="rename_memory"){if(t.ok!==!0)return null;const i=t.paths[0],o=cx(t);return!i||!o||i===o||!e(o)||e(i)?null:{type:"moveBack",from:i,to:o}}if(a==="pin"||a==="unpin"){const i=t.paths[0];return i?{type:a==="pin"?"unpin":"pin",path:i,kind:i.endsWith(".md")?"note":"folder"}:null}return null}const q2={create_memory:"Created a note",batch_create:"Created several notes",save_memory:"Rewrote a note",patch_memory:"Edited part of a note",read_memory:"Read a note",search_memory:"Searched notes",query_memory:"Searched with filters",list_memory:"Looked through notes",node_created:"Note created",node_updated:"Note saved",node_renamed:"Note moved or renamed",node_deleted:"Note deleted",folder_changed:"Folder changed"};function dx(t,e="agent"){if(q2[t])return q2[t];const a=Wa(z2({action:t,label:"",paths:[],source:e,raw:{}}));return a.charAt(0).toUpperCase()+a.slice(1)}let HL=0;const px=()=>"a"+(++HL).toString(36),qL=/(fail|denied|invalid|blocked|reject|error|locked)/i;function Ia(t){return typeof t=="string"?t:t==null?"":String(t)}function WL(t){const e=new Set,n=t.paths;Array.isArray(n)&&n.forEach(i=>typeof i=="string"&&i&&e.add(i)),t.path&&e.add(t.path),t.node&&t.node.path&&e.add(t.node.path);const a=Ia(t.label);return/\.md$/i.test(a)&&!/\s/.test(a)&&e.add(a),[...e]}function hx(t){const e=t.type==="ai_activity",n=t.ok,a=t.ms;return{id:px(),ts:Number(t._ts||t.ts||t.at||0),actor:Ia(t.actor||t.by||t.user)||"system",action:Ia(t.action||t.event||t.type)||"activity",label:Ia(t.label||t.node&&(t.node.path||t.node.id)||t.path||t.folder||t.detail||""),paths:WL(t),source:e?"agent":"vault",ok:typeof n=="boolean"?n:void 0,ms:typeof a=="number"?a:void 0,running:e&&t.phase==="start"&&typeof n!="boolean"?!0:void 0,raw:t}}function ux(t){const e=Ia(t.event||t.type)||"auth";return{id:px(),ts:Number(t.at||t.ts||0),actor:Ia(t.user||t.actor)||"gateway",action:e,label:Ia(t.detail||""),paths:[],source:"auth",ok:!qL.test(e),ip:Ia(t.ip)||void 0,raw:t}}function GL(t){return{id:px(),ts:(t.at||Date.now())/1e3,actor:t.actor||"agent",action:t.action||"activity",label:t.label||"",paths:Array.isArray(t.paths)?t.paths.filter(Boolean):[],source:"agent",ok:t.ok,ms:t.ms,running:t.phase==="start"?!0:void 0,live:!0,raw:{...t,...t.actorId?{actor_id:t.actorId}:{},...t.callId?{call_id:t.callId}:{}}}}const El=new Map,VL=1e3;function jL(t,e,n){El.delete(t),El.set(t,{ok:e,ms:n}),El.size>VL&&El.delete(El.keys().next().value)}function W2(t){if(!t.running)return!1;const e=El.get(Ia(t.raw.call_id));return e?(t.running=!1,t.ok=e.ok??!0,e.ms!=null&&(t.ms=e.ms),!0):!1}function dr(t,e=Date.now()/1e3){return!t.running||W2(t)?!1:(e-t.ts>(t.live?120:30)&&(t.running=!1),!!t.running)}function G2(t){const e=[],n=new Map;for(const i of t.sort((o,s)=>o.ts-s.ts)){const o=Ia(i.raw.phase),s=i.actor+"\0"+i.action;if(o==="end"){const r=n.get(s),l=r&&r.shift();if(l&&i.ts-l.ts<600){l.running=!1,l.ok=i.ok??!0,l.ms=i.ms??Math.round((i.ts-l.ts)*1e3),i.paths.length&&(l.paths=[...new Set([...l.paths,...i.paths])]),i.label&&!l.label&&(l.label=i.label);continue}i.running=!1,e.push(i);continue}o==="start"&&(n.has(s)||n.set(s,[]),n.get(s).push(i)),e.push(i)}const a=Date.now()/1e3-30;for(const i of e)!W2(i)&&i.running&&i.ts<a&&(i.running=!1);return UL(e),e.reverse()}const YL={"1h":3600,"1d":86400,"7d":604800,"30d":2592e3};function V2(t){const e=t?new Date(t+"T00:00:00"):new Date;return t||e.setHours(0,0,0,0),e.getTime()/1e3}function j2(t){if(t==="all")return{since:0,until:1/0};if(t==="today")return{since:V2(),until:1/0};if(t.startsWith("day:")){const e=V2(t.slice(4)),n=new Date(e*1e3);return n.setDate(n.getDate()+1),{since:e,until:n.getTime()/1e3}}return{since:Date.now()/1e3-(YL[t]||86400),until:1/0}}const fx=2e3,XL=t=>Number(t._ts||t.ts||t.at||0);async function KL(t,e,n,a){if(n<=fx)return(await Oe(`/api/logs?${t}&limit=${n}`)).events||[];const i=[],o=new Set;let s=e.until;for(;i.length<n;){const r=e.since>0?`&since=${Math.floor(e.since)}`:"",l=Number.isFinite(s)?`&until=${s}`:"",c=(await Oe(`/api/logs?range=all${r}${l}&limit=${fx}`)).events||[];let d=0,p=1/0;for(const h of c){p=Math.min(p,XL(h));const u=JSON.stringify(h);o.has(u)||(o.add(u),i.push(h),d++)}if(c.length<fx||!d||!Number.isFinite(p))break;a?.(i),s=p+.001}return i.slice(0,n)}async function yu(t,e=800,n){const a=j2(t),i=t==="1h"?"range=1d":t==="all"||/^\d+d$/.test(t)?`range=${t}`:`range=1d&since=${Math.floor(a.since)}${Number.isFinite(a.until)?`&until=${Math.ceil(a.until)}`:""}`,s=((await Oe("/api/auth/events?limit=300").catch(()=>({events:[]}))).events||[]).map(ux),r=c=>G2([...c.map(hx),...s.map(d=>({...d}))].filter(d=>d.ts>=a.since&&d.ts<a.until)),l=await KL(i,a,e,n&&(c=>n(r(c)))).catch(()=>[]);return r(l)}function wu(t,e,n=2e3){if(Ia(e.raw.phase)==="end"){const i=Ia(e.raw.call_id),o=i&&t.find(s=>s.running&&Ia(s.raw.call_id)===i)||t.find(s=>s.running&&s.actor===e.actor&&s.action===e.action);if(o)return o.running=!1,o.ok=e.ok??!0,o.ms=e.ms??Math.round((e.ts-o.ts)*1e3),e.paths.length&&(o.paths=[...new Set([...o.paths,...e.paths])]),t;e.running=!1}return t.unshift(e),t.length>n&&(t.length=n),t}class Y2{constructor(e=2e3){this.max=e,this.items=[],this.count=0}get length(){return this.count}push(e){this.items.push(e),this.count++,this.items.length>this.max&&this.items.splice(0,this.items.length-this.max)}take(){const e=this.items;return this.items=[],this.count=0,e}}function ku(t){return Hn("activity",e=>t(GL(e)))}function mx(t){return t.replace(/[_.]+/g," ").trim()}const ZL=`
|
|
1
|
+
(function(){"use strict";const te={openNote:()=>{},renderTree:()=>{},loadCore:async()=>{},go:()=>{},refreshPage:()=>{},refreshTree:()=>{},refreshVault:()=>{},refreshLogs:()=>{},openMoveNote:()=>{},openMoveFolder:()=>{},openFolderColor:()=>{},confirmDeleteFolder:()=>{},openNewNote:()=>{},openNewFolder:()=>{},openTrash:()=>{},vaultChanged:()=>{},askMnemo:()=>{},mnemoButton:()=>!0,mnemoActivity:()=>{}},Jk=te.renderTree,O6=te.refreshTree,$6={add(){},remove(){},toggle(){},contains(){return!1}},Qk=new Proxy({},{get(t,e){if(e==="classList")return $6;if(e==="style")return new Proxy({},{get:()=>"",set:()=>!0});if(e==="dataset")return{};if(e==="querySelector"||e==="closest")return()=>Qk;if(e==="querySelectorAll")return()=>[];if(e==="children")return[];if(e==="offsetParent")return null;if(e==="value"||e==="textContent"||e==="innerHTML"||e==="title")return""},set:()=>!0});function H(t,e=document){return e.querySelector(t)??Qk}function Bn(t,e=document){return Array.from(e.querySelectorAll(t))}function re(t,e,n){const a=document.createElement(t);return e&&(a.className=e),n!=null&&(a.innerHTML=n),a}function x(t){return String(t??"").replace(/[&<>"']/g,e=>{switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function C(t){return x(t)}const F6={"&":"&","<":"<",">":">",""":'"',"'":"'"};function U6(t){return String(t??"").split(/(<\/?b>)/).map(e=>e==="<b>"||e==="</b>"?e:x(e.replace(/&(?:amp|lt|gt|quot|#39);/g,n=>F6[n]??n))).join("")}function Ue(t,e){if(document.getElementById(t))return;const n=document.createElement("style");n.id=t,n.textContent=e,document.head.appendChild(n)}function e2(t,e,n){const a=new Error(t);return a.status=e,a.data=n,a}let t2=!1;function B6(){if(t2||typeof location>"u"||location.pathname==="/login")return;t2=!0;const t=location.pathname+location.search+location.hash;window.setTimeout(()=>location.replace("/login?r="+encodeURIComponent(t)),50)}async function $n(t,e={}){const n={accept:"application/json"};let a;e.body!==void 0&&(n["content-type"]="application/json",a=JSON.stringify(e.body));let i;try{i=await fetch(t,{method:e.method??"GET",credentials:"same-origin",headers:n,body:a,cache:"no-store"})}catch{throw e2("cannot reach the server",0,null)}const o=await i.text();let s=null;try{s=o?JSON.parse(o):null}catch{s={raw:o}}if(i.status===401&&B6(),!i.ok){const r=s??{},l=typeof r.error=="string"?r.error:typeof r.message=="string"?r.message:`HTTP ${i.status}`;throw e2(l,i.status,s)}return s}function Oe(t){return $n(t)}function Ve(t,e={}){return $n(t,{method:"POST",body:e})}async function Iv(){const t=await Oe("/api/tools");return t&&t.tools||[]}function H6(t,e){return Ve("/api/tools",{name:t,enabled:e})}function n2(t){return Ve("/api/keys/update",t)}const q6='<svg class="caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M6 9l6 6 6-6"/></svg>',W6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M12 17v5M8.5 3h7l-1 6 3 3v2H6.5v-2l3-3z"/></svg>',G6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M12 17v5M8.5 3h7l-1 6 3 3v2H6.5v-2l3-3z"/><path d="M3 3l18 18"/></svg>',a2='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M14 13h-4M12 11l2 2-2 2"/></svg>',V6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><circle cx="12" cy="12" r="3"/><path d="M12 3v3M12 18v3M3 12h3M18 12h3"/></svg>',j6='<svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/></svg>',Nv=["#5eead4","#7dd3fc","#a5b4fc","#fbbf24","#f87171","#4ade80","#f0abfc","#fb923c","#94a3b8"];function sa(t){return t?new Date(Number(t)*1e3).toLocaleString("en-US",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"-"}function kn(t){if(!t)return"-";const e=Date.now()/1e3-Number(t),n=(a,i)=>`${a} ${i}${a===1?"":"s"} ago`;return e<60?"just now":e<3600?n(Math.floor(e/60),"minute"):e<86400?n(Math.floor(e/3600),"hour"):e<2592e3?n(Math.floor(e/86400),"day"):new Date(Number(t)*1e3).toLocaleDateString("en-US",{day:"numeric",month:"short",year:"numeric"})}function Y6(t){return new Date(Number(t)*1e3).toLocaleDateString("en-US",{weekday:"short",day:"numeric",month:"short",year:"numeric"})}function X6(t,e){const n=String(t??"");return n.length>e?n.slice(0,e-1)+"...":n}function i2(t){const e=String(t||"").split("/");return e.length>1?e[0]:"Root"}function pn(t){return String(t||"").split("/").pop().replace(/\.md$/,"")}function or(t){return t.replace(/_/g," ").trim()||t}function jn(t){let e=0;const n=String(t||"");for(let a=0;a<n.length;a++)e=e*31+n.charCodeAt(a)>>>0;return Nv[e%Nv.length]}function zv(t,e){let n;return(...a)=>{clearTimeout(n),n=setTimeout(()=>t(...a),e)}}function o2(t){const e=new Set,n=t||"",a=/(?:^|\n)tags\s*:\s*(.*)/i.exec(n);return a&&a[1].replace(/[\[\]'"]/g," ").split(/[,\s]+/).map(i=>i.replace(/^#/,"").trim()).filter(Boolean).forEach(i=>e.add(i)),(n.match(/(^|\s)#([A-Za-z0-9_][\w/-]{1,48})/g)||[]).forEach(i=>e.add(i.trim().replace(/^#/,""))),Array.from(e)}function K6(t){const e=String(t||"").match(/\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g)||[];return Array.from(new Set(e.map(n=>n.replace(/^\[\[|\]\]$/g,"").split("|")[0].replace(/\\$/,"").trim()).filter(Boolean)))}const s2="memora.pins.v3",r2="memora.pinorder.v1",l2="memora.ui.v3",c2="memora.openfolders.v3",d2="memora.updateNotice",p2="memora.toasts.v1",Dv="memora.tagidx";function sr(t,e){try{const n=(t==="local"?localStorage:sessionStorage).getItem(e);return n?JSON.parse(n):void 0}catch{return}}function md(t,e,n){try{(t==="local"?localStorage:sessionStorage).setItem(e,JSON.stringify(n))}catch{}}function gd(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function vs(t,e){return t&&typeof t=="object"?t[e]:void 0}const h2=sr("local",l2),Ov=vs(h2,"width"),Eo={collapsed:vs(h2,"collapsed")===!0,...typeof Ov=="number"&&Number.isFinite(Ov)?{width:Ov}:{}},u2=sr("local",p2),Pa={off:vs(u2,"off")===!0,muted:gd(vs(u2,"muted"))};function f2(){md("local",p2,Pa)}function $v(t){return Pa.off?!1:!t||!Pa.muted.includes(t)&&!Fv.has(t)}const Fv=new Set;function Z6(t){return Fv.add(t),()=>Fv.delete(t)}function m2(){const t=sr("local",s2),e=new Map(gd(sr("local",r2)).map((a,i)=>[a,i])),n=a=>(a.kind==="note"?"n:":"f:")+a.path;return[...gd(vs(t,"folders")).map(a=>({kind:"folder",path:a})),...gd(vs(t,"notes")).map(a=>({kind:"note",path:a}))].sort((a,i)=>(e.get(n(a))??1e9)-(e.get(n(i))??1e9))}function g2(){try{localStorage.removeItem(s2),localStorage.removeItem(r2)}catch{}}function uu(){md("local",l2,Eo)}function J6(){return new Set(gd(sr("local",c2)))}function Uv(t){md("local",c2,Array.from(t))}function Q6(){const t=sr("local",d2);return typeof t=="string"?t:""}function eL(t){md("local",d2,t)}function v2(){const t=sr("session",Dv),e=vs(t,"sig"),n=vs(t,"tags");if(typeof e!="string"||!Array.isArray(n))return null;const a=n.filter(i=>Array.isArray(i)&&typeof i[0]=="string"&&Array.isArray(i[1]));return{sig:e,tags:a}}function tL(t,e){md("session",Dv,{sig:t,tags:e})}function Bv(){try{sessionStorage.removeItem(Dv)}catch{}}const N={page:"brain",tree:{},folders:[],folderMeta:{},stats:{notes:0,links:0,folders:0},health:{},config:{},me:null,open:J6(),filter:"",note:null,editing:!1,graph:{nodes:[],links:[],stop:null},tags:{index:null,built:!1,active:null,progress:0},peekPath:null,keysDeleted:[]};function en(){const t=[];for(const e of Object.keys(N.tree))for(const n of N.tree[e]||[])t.push({...n,folder:n.folder||e});return t}let x2=null;const Hv=new Map;function lt(t){const e=String(t||"");if(x2!==N.tree){x2=N.tree,Hv.clear();for(const n of Object.keys(N.tree))for(const a of N.tree[n]||[])a.title&&Hv.set(a.path,a.title)}return Hv.get(e)||or((e.split("/").pop()||e).replace(/\.md$/i,""))}function b2(){return Object.keys(N.tree).sort((t,e)=>t==="Root"?-1:e==="Root"?1:t.localeCompare(e))}function Yn(t){const e=N.folderMeta[t];return e&&e.color||jn(t)}const y2=[];let qv=N.note;Object.defineProperty(N,"note",{enumerable:!0,configurable:!0,get:()=>qv,set:t=>{if(t!==qv){qv=t;for(const e of y2)try{e(t)}catch(n){console.error("note listener failed",n)}}}});function nL(t){y2.push(t)}async function aL(t){if(window.matchMedia("(max-width: 760px)").matches){te.openNote(t);return}N.peekPath=t,H("#peek").classList.remove("hidden"),H("#peekFolder").textContent=i2(t)+" / "+pn(t),H("#peekBody").innerHTML='<div class="empty">Loading...</div>';try{const e=await Oe("/api/note?path="+encodeURIComponent(t));if(N.peekPath!==t)return;H("#peekBody").innerHTML=e.html||`<pre>${x(e.content||"")}</pre>`}catch(e){if(N.peekPath!==t)return;H("#peekBody").innerHTML=`<div class="empty">Could not load: ${x(e.message)}</div>`}}function Wv(){N.peekPath=null,H("#peek").classList.add("hidden")}const Ha={home:{label:"Overview",title:"Overview",hint:"Your notes and agents at a glance",icon:"overview",group:"system",path:"/overview"},brain:{label:"Brain",title:"Brain",hint:"Your memory as a living brain",icon:"brain",group:"content",path:"/brain"},vault:{label:"Notes",title:"Notes",hint:"Browse, read and write your notes",icon:"note",group:"content",path:"/nodes"},graph:{label:"Graph",title:"Graph",hint:"Map of every link between notes",icon:"graph",group:"content",path:"/brain?mode=graph"},canvas:{label:"Canvas",title:"Canvas",hint:"Arrange notes on an open board",icon:"canvas",group:"content",path:"/brain?mode=canvas"},tags:{label:"Tags",title:"Tags",hint:"Every tag and its notes",icon:"tags",group:"content",path:"/tags"},logs:{label:"Activity",title:"Activity",hint:"What your agents read and changed",icon:"activity",group:"system",path:"/activity"},keys:{label:"Agents",title:"Agents & API keys",hint:"Connect AI apps and choose what they may do",icon:"key",group:"system",path:"/agents"},tools:{label:"Tools",title:"MCP tools",hint:"Turn agent tools on or off",icon:"tools",group:"system",path:"/tools"},access:{label:"Access rules",title:"Access rules",hint:"Which addresses may reach Memora",icon:"shield",group:"system",path:"/access"},settings:{label:"Settings",title:"Settings",hint:"Account, appearance and preferences",icon:"settings",group:"system",path:"/settings"},docs:{label:"Documentation",title:"Documentation",hint:"Guides, agent instructions and reference",icon:"book",group:"system",path:"/docs"},assistant:{label:"Mnemo",title:"Mnemo",hint:"Your notes agent: ask, find, write and tidy",icon:"mnemo",group:"content",path:"/mnemo"},trash:{label:"Trash",title:"Trash",hint:"Deleted notes, ready to restore",icon:"trash",group:"system",path:"/trash"}},_o=Object.keys(Ha);function Gv(t){return typeof t=="string"&&Object.prototype.hasOwnProperty.call(Ha,t)}const w2=/[\u0000-\u001f\u007f]/;function iL(t){if(!t||t.length>1024||t.startsWith("/")||t.includes("\\")||w2.test(t)||/^[a-zA-Z]:/.test(t))return null;const e=t.split("/");for(const n of e)if(!n||n==="."||n===".."||w2.test(n))return null;return e.join("/")}function k2(t){return"/node/"+t.split("/").map(encodeURIComponent).join("/")}const xs=new Map(_o.map(t=>[Ha[t].path,t]));xs.set("/vault","vault"),xs.set("/home","home"),xs.set("/welcome","home"),xs.set("/logs","logs"),xs.set("/keys","keys"),xs.set("/graph","graph"),xs.set("/canvas","canvas");function oL(t){return t==="graph"||t==="canvas"?"brain":t}function sL(t){const e=new URLSearchParams(t.search).get("mode");return e==="graph"||e==="canvas"?e:"brain"}let wl=null;function rL(t){wl=t}let kl=!1;function fu(t){kl=t}function lL(){const t=wl;return wl=null,t}let vd=null,Vv=null;function xd(t){if(vd=t,N.page!=="assistant")return;const e=t?`/mnemo/${t}`:"/mnemo";if(location.pathname!==e)try{history.replaceState({page:"assistant"},"",e)}catch{}}function cL(){const t=Vv;return Vv=null,t}const jv=["overview","setup","activity","access","settings"];let rr=null;function lr(t){rr=t}const dL=new RegExp(`^/(?:new(?:/[a-z0-9-]{1,40})?|[A-Za-z0-9_-]{1,64}(?:/(?:${jv.join("|")}))?)$`),pL=/^#connect(?:=([\w-]{1,40}))?$/;function S2(t=location){const e=t.pathname.replace(/\/+$/,"")||"/",n=e==="/docs"||e.startsWith("/docs/"),a=t.hash.replace(/^#\/?/,"").split(/[/?]/)[0];if(a&&Gv(a)&&!n)return{page:a};if(n)return{page:"docs"};if(e==="/"||e==="/index.html"||e==="/brain")return{page:sL(t)};if(e.startsWith("/node/")){const l=e.slice(6).split("/"),c=[];for(const p of l)try{c.push(decodeURIComponent(p))}catch{return{page:"vault",badNode:!0}}if(c.some(p=>p.includes("/")))return{page:"vault",badNode:!0};const d=iL(c.join("/"));return d?{page:"vault",node:d}:{page:"vault",badNode:!0}}if(e==="/activity/timeline"||e==="/activity")return kl=e!=="/activity",{page:"logs"};const i=/^\/activity\/([A-Za-z0-9_-]{1,64})$/.exec(e);if(i)return wl=i[1],{page:"logs"};const o=/^\/(?:agents|keys)(\/.*)?$/.exec(e);if(o){const l=o[1]||"",c=l?null:pL.exec(t.hash);if(c)rr="/agents/new"+(c[1]?"/"+c[1].toLowerCase():"");else if(l&&dL.test(l))rr="/agents"+l;else{if(l)return{page:"brain",unknown:!0};rr=null}return{page:"keys"}}const s=/^\/mnemo\/(c[0-9a-f]{12})$/.exec(e);if(s)return Vv=s[1],vd=s[1],{page:"assistant"};e==="/mnemo"&&(vd=null);const r=xs.get(e);return r?{page:r}:{page:"brain",unknown:!0}}function hL(t){const e=en(),n=e.find(a=>a.path===t)||e.find(a=>a.path===t+".md")||e.find(a=>a.path.replace(/\.md$/i,"")===t);return n?n.path:null}function uL(t,e,n){if(t.unknown)return{kind:"missing",missing:{what:"page",label:e}};if(t.page==="vault"&&(t.badNode||t.node)){const a=t.node?n(t.node):null;if(a)return{kind:"node",path:a};let i=t.node||e.replace(/^\/node\/?/,"");if(!t.node)try{i=decodeURIComponent(i)}catch{}return{kind:"missing",missing:{what:"node",label:i||e}}}return{kind:"page",page:t.page}}let Yv=null;function fL(t){if(t==="docs"){const e=Yv;if(Yv=null,e)return e;const n=location.pathname;return n==="/docs"||n.startsWith("/docs/")?n+location.hash:"/docs"}if(t==="logs"&&wl)return"/activity/"+wl;if(t==="logs"&&kl)return"/activity/timeline";if(t==="assistant"&&vd)return`/mnemo/${vd}`;if(t==="keys"&&rr){const e=rr;return rr=null,e}return t==="vault"&&N.note?k2(N.note):Ha[t].path}let Xv=!1;function zi(){Xv=!0}function mu(){const t=fL(N.page),e=Xv;if(Xv=!1,location.pathname+location.search+location.hash!==t)try{e?history.replaceState({page:N.page},"",t):history.pushState({page:N.page},"",t)}catch{}}const Kv={},M2=[];function qa(t){M2.push(t)}function ba(t,e){Kv[t]=e}function Zv(){const t=N.page,e=H(".crumb"),n=t==="vault"&&N.note?lt(N.note):Ha[t].title;e.textContent=n,e.title=t==="vault"&&N.note?N.note:"",document.title=n+" · Memora"}let Jv=null;function mL(t){Jv=t}function ra(t,e=!1){if(Gv(t)||(t="brain"),!e&&N.editing&&Jv&&Jv(()=>ra(t,e),()=>{zi(),mu()}))return;e||(N.editing=!1);const n=N.page;N.page=t,Bn("[data-page].nav-item,[data-page].tab-item,[data-page].pm-item").forEach(a=>{const i=a.dataset.page===oL(t);a.classList.toggle("active",i),i?a.setAttribute("aria-current","page"):a.removeAttribute("aria-current")});for(const a of _o)H("#view-"+a).classList.toggle("hidden",a!==t);Zv(),H("#app").classList.remove("side-open"),t!=="graph"&&N.graph.stop&&(N.graph.stop(),N.graph.stop=null),Wv(),mu();for(const a of M2)try{a(t)}catch(i){console.error("navigate listener failed",i)}n!==t&&(H("#views").scrollTop=0),Kv[t]?.()}function bd(t="",e=""){Yv="/docs"+(t?"/"+encodeURIComponent(t):"")+(e?"#"+encodeURIComponent(e):""),ra("docs")}function A2(){Kv[N.page]?.()}nL(()=>{N.page==="vault"&&(mu(),Zv())});const T2={brain:'<path d="M9.5 4.5A2.5 2.5 0 0 0 7 7a2.6 2.6 0 0 0-2.5 3.2A3 3 0 0 0 5 15.6 2.8 2.8 0 0 0 9.5 19.5V4.5z"/><path d="M14.5 4.5A2.5 2.5 0 0 1 17 7a2.6 2.6 0 0 1 2.5 3.2 3 3 0 0 1-.5 5.4 2.8 2.8 0 0 1-4.5 3.9V4.5z"/><path d="M9.5 9H8M14.5 9H16M9.5 14H7.5M14.5 14h2"/>',overview:'<rect x="3.5" y="3.5" width="7" height="8" rx="2"/><rect x="13.5" y="3.5" width="7" height="5" rx="2"/><rect x="13.5" y="11.5" width="7" height="9" rx="2"/><rect x="3.5" y="14.5" width="7" height="6" rx="2"/>',vault:'<path d="M3.5 7.5a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/><path d="M3.5 10.5h17"/>',graph:'<circle cx="6" cy="17" r="2.4"/><circle cx="17.5" cy="6.5" r="2.4"/><circle cx="17.5" cy="17.5" r="2.2"/><path d="M7.9 15.3 15.4 8.4M8.8 17.4h6.3"/>',canvas:'<rect x="3.5" y="3.5" width="17" height="17" rx="3"/><rect x="6.5" y="7" width="5" height="4" rx="1"/><rect x="12.5" y="12.5" width="5" height="4.5" rx="1"/><path d="M11.5 9h3a1 1 0 0 1 1 1v2.5"/>',tags:'<path d="M4 12.5V6a2 2 0 0 1 2-2h6.5L20 11.5a2 2 0 0 1 0 2.8l-5.7 5.7a2 2 0 0 1-2.8 0z"/><circle cx="8.2" cy="8.2" r="1.3"/>',activity:'<path d="M3 12h3.5l2.5-6 3 12 2.5-6H21"/>',agents:'<rect x="4.5" y="7.5" width="15" height="11" rx="3"/><path d="M12 3.5v4M9 12.5h.01M15 12.5h.01M9.5 15.5h5"/><path d="M2.5 12v2.5M21.5 12v2.5"/>',key:'<circle cx="8" cy="12" r="3.2"/><path d="M11.2 12H21M18 12v3M15 12v2.2"/>',tools:'<rect x="3" y="4.5" width="18" height="6.5" rx="3.25"/><circle cx="15.6" cy="7.75" r="1.6"/><rect x="3" y="13" width="18" height="6.5" rx="3.25"/><circle cx="8.4" cy="16.25" r="1.6"/>',shield:'<path d="M12 3 19 6v6c0 4.2-2.9 7.6-7 9-4.1-1.4-7-4.8-7-9V6z"/><path d="m9.2 12 2 2 3.8-4"/>',settings:'<path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20.5 20.5-4.3-4.3"/>',more:'<circle cx="5" cy="12" r="1.3"/><circle cx="12" cy="12" r="1.3"/><circle cx="19" cy="12" r="1.3"/>',menu:'<path d="M4 7h16M4 12h16M4 17h10"/>',sidebar:'<rect x="3.5" y="4.5" width="17" height="15" rx="3"/><path d="M9.5 4.5v15"/>',"chev-left":'<path d="m14.5 6-6 6 6 6"/>',"chev-right":'<path d="m9.5 6 6 6-6 6"/>',"chev-down":'<path d="m6 9.5 6 6 6-6"/>',close:'<path d="M6 6l12 12M18 6 6 18"/>',plus:'<path d="M12 5v14M5 12h14"/>',note:'<path d="M7 3.5h7l4.5 4.5v11a1.5 1.5 0 0 1-1.5 1.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8h4.5M8.5 13h7M8.5 16.5h5"/>',folder:'<path d="M3.5 7.5a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/>',trash:'<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/>',"folder-plus":'<path d="M3.5 7.5a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/><path d="M12 11v5M9.5 13.5h5"/>',sun:'<circle cx="12" cy="12" r="4"/><path d="M12 2.5v2M12 19.5v2M4.6 4.6 6 6M18 18l1.4 1.4M2.5 12h2M19.5 12h2M4.6 19.4 6 18M18 6l1.4-1.4"/>',moon:'<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>',monitor:'<rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/>',image:'<rect x="3" y="4" width="18" height="16" rx="2.5"/><circle cx="9" cy="9.5" r="1.8"/><path d="m21 16-5-5L5 20"/>',book:'<path d="M4.5 5.5A2 2 0 0 1 6.5 3.5h12v14h-12a2 2 0 0 0-2 2z"/><path d="M4.5 19.5a2 2 0 0 0 2 2h12v-4"/><path d="M9 8h6M9 11.5h4"/>',help:'<circle cx="12" cy="12" r="9.2"/><path d="M9.6 9.3a2.4 2.4 0 1 1 3.3 2.2c-.8.4-1.1.9-1.1 1.7M12 16.6h.01"/>',download:'<path d="M12 3.5v12"/><path d="m7 10.5 5 5 5-5"/><path d="M4.5 19.5h15"/>',refresh:'<path d="M20 11a8 8 0 1 0-2.3 6.3"/><path d="M20 5v6h-6"/>',logout:'<path d="M15 4.5h3a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-3"/><path d="M10 16.5 5.5 12 10 7.5M5.5 12H15"/>',user:'<circle cx="12" cy="8.5" r="3.8"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/>',pin:'<path d="M12 17v4.5M8.5 3h7l-1 6 3 3v2h-11v-2l3-3z"/>',bell:'<path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z"/><path d="M10 20.5a2.2 2.2 0 0 0 4 0"/>',bolt:'<path d="M13 2.5 4.5 13.5H12l-1 8 8.5-11H12z"/>',wifi:'<path d="M2.5 9a14 14 0 0 1 19 0M5.5 12.5a9.5 9.5 0 0 1 13 0M8.6 16a5 5 0 0 1 6.8 0"/><circle cx="12" cy="19.3" r=".9"/>',"wifi-off":'<path d="M3 3l18 18M8.6 16a5 5 0 0 1 6.8 0M5.5 12.5a9.5 9.5 0 0 1 4-2.3M14.6 10.3a9.5 9.5 0 0 1 3.9 2.2M2.5 9a14 14 0 0 1 4-2.6M11 5.6A14 14 0 0 1 21.5 9"/><circle cx="12" cy="19.3" r=".9"/>',enter:'<path d="M19.5 5v6a3 3 0 0 1-3 3h-12"/><path d="m8.5 10-4 4 4 4"/>',arrow:'<path d="M5 12h14M13 6l6 6-6 6"/>',check:'<path d="m5 12.5 4.5 4.5L19 7.5"/>',alert:'<path d="M12 3.5 2.8 19.5h18.4z"/><path d="M12 10v4.5M12 17.2h.01"/>',info:'<circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.8h.01"/>',x_circle:'<circle cx="12" cy="12" r="9"/><path d="m9 9 6 6M15 9l-6 6"/>',mnemo:'<path d="M4 18v-8a2.6 2.6 0 0 1 5.2 0v4.2a2.8 2.8 0 0 0 5.6 0V10a2.6 2.6 0 0 1 5.2 0v8"/><path d="M12 2.8v2.6M10.7 4.1h2.6"/>',send:'<path d="M12 19V5M6 11l6-6 6 6"/>',stop:'<rect x="6.5" y="6.5" width="11" height="11" rx="2.5"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="2.5"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>',edit:'<path d="M4.5 19.5h4l10-10a2.1 2.1 0 0 0-4-4l-10 10z"/><path d="m13.5 6.5 4 4"/>',star:'<path d="m12 4 2.4 5 5.4.6-4 3.7 1.1 5.3L12 16l-4.9 2.6 1.1-5.3-4-3.7 5.4-.6z"/>',code:'<path d="m8.5 7.5-5 4.5 5 4.5M15.5 7.5l5 4.5-5 4.5M13.5 5l-3 14"/>',eye:'<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="2.8"/>',"eye-off":'<path d="M10 5.7A9.6 9.6 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a16 16 0 0 1-2.4 3.2M6.3 7.2C3.9 8.8 2.5 12 2.5 12S6 18.5 12 18.5a9 9 0 0 0 4.4-1.1M4 4l16 16"/><path d="M9.9 10a2.8 2.8 0 0 0 4 4"/>',chat:'<path d="M5 18.5V7a2.5 2.5 0 0 1 2.5-2.5h9A2.5 2.5 0 0 1 19 7v6.5a2.5 2.5 0 0 1-2.5 2.5H9z"/><path d="M9 9.5h6M9 12.5h3.5"/>',expand:'<path d="M14 4.5h5.5V10M10 19.5H4.5V14M19.5 4.5 13.5 10.5M4.5 19.5l6-6"/>',chev:'<path d="m9 6 6 6-6 6"/>',sparkle:'<path d="M12 3.5 13.8 9 19.5 10.8 13.8 12.6 12 18.5 10.2 12.6 4.5 10.8 10.2 9z"/><path d="M19 3.5v3M17.5 5h3"/>',command:'<path d="M9 6.5A2.5 2.5 0 1 0 6.5 9H9zM15 6.5A2.5 2.5 0 1 1 17.5 9H15zM9 17.5A2.5 2.5 0 1 1 6.5 15H9zM15 17.5a2.5 2.5 0 1 0 2.5-2.5H15zM9 9h6v6H9z"/>'};function gL(t){return T2[t]||T2.note}function V(t,e="i"){return`<svg class="${e}" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true" focusable="false">${gL(t)}</svg>`}const vL={ok:"check",warn:"alert",err:"alert",info:"info"},E2=3,xL=12,gn=[];let Qv=!1,Di=!1;const ex=()=>window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;function tx(){return H("#toasts")}function yd(t){if(!ex())for(const e of gn){const n=t.get(e.node);if(n==null)continue;const a=n-e.node.getBoundingClientRect().top;a&&(e.node.style.transition="none",e.node.style.transform=`translateY(${a}px)`,requestAnimationFrame(()=>{e.node.style.transition="",e.node.style.transform=""}))}}function gu(){return new Map(gn.map(t=>[t.node,t.node.getBoundingClientRect().top]))}function nx(t,e){window.clearTimeout(t.timer),!t.sticky&&(t.left=e,t.until=Date.now()+e,Qv||(t.timer=window.setTimeout(()=>wd(t.node),e)))}function Sl(){const t=tx();if(!t.classList)return;const e=Math.max(0,gn.length-E2);e||(Di=!1),gn.forEach((i,o)=>i.node.classList.toggle("stowed",!Di&&o>=E2));let n=t.querySelector(".t-more");e&&!n&&(n=re("button","t-more"),n.type="button",n.onclick=()=>{const i=gu();Di=!Di,Sl(),yd(i)},t.prepend(n)),n&&(e?(n.textContent=Di?"Show fewer":`+${e} more`,n.setAttribute("aria-expanded",String(Di)),n.setAttribute("aria-label",Di?"Show only the latest notifications":`Show ${e} more notification${e===1?"":"s"}`)):n.remove()),t.classList.toggle("expanded",Di);const a=gn.length?Math.ceil(t.getBoundingClientRect().height):0;document.documentElement.style.setProperty("--toasts-h",a?a+12+"px":"0px")}function wd(t,e=!1){const n=gn.findIndex(o=>o.node===t);if(n<0)return;const[a]=gn.splice(n,1);window.clearTimeout(a.timer);const i=gu();t.classList.add(e?"out-fast":"out"),t.style.pointerEvents="none",window.setTimeout(()=>{t.remove(),Sl(),yd(i)},ex()?0:e?160:260)}function bL(t){const e=gn.find(n=>n.group===t);e&&wd(e.node,!0)}function yL(t){return gn.some(e=>e.group===t)}function wL(t){let e=0,n=0,a=-1;t.addEventListener("pointerdown",o=>{o.target.closest("button")||(a=o.pointerId,e=o.clientX,n=0,t.setPointerCapture(a),t.style.transition="none")}),t.addEventListener("pointermove",o=>{o.pointerId===a&&(n=Math.max(0,o.clientX-e),t.style.transform=`translateX(${n}px)`,t.style.opacity=String(1-Math.min(.9,n/220)))});const i=o=>{o.pointerId===a&&(a=-1,t.style.transition="",n>70?(t.style.transform=`translateX(${n+120}px)`,t.style.opacity="0",wd(t,!0)):(t.style.transform="",t.style.opacity=""))};t.addEventListener("pointerup",i),t.addEventListener("pointercancel",i)}function _2(t,e,n,a,i){t.className="toast "+n+(i?.iconHtml?" has-av":""),t.innerHTML=`<span class="t-ico">${i?.iconHtml||V(vL[n]||"info")}</span><span class="t-msg">${x(e)}</span>${a?`<button type="button" class="t-act">${a.icon||""}${x(a.label)}</button>`:""}<button type="button" class="t-x" aria-label="Dismiss" title="Dismiss">${V("close")}</button>`,n==="err"?t.setAttribute("role","alert"):t.removeAttribute("role"),t.querySelector(".t-x").onclick=()=>wd(t,!0);const o=t.querySelector(".t-act");o&&a&&(o.onclick=async()=>{o.disabled=!0,wd(t,!0),await a.run()})}function Xn(t,e="ok",n=4200,a,i){const o=tx();if(!o.classList)return;const s=e==="err",r=gu(),l=i?.group?gn.find(p=>p.group===i.group):void 0;if(l){gn.splice(gn.indexOf(l),1),gn.unshift(l),l.sticky=s,_2(l.node,t,e,a,i),o.appendChild(l.node),ex()||(l.node.classList.remove("bump"),l.node.offsetWidth,l.node.classList.add("bump")),Sl(),yd(r),nx(l,n);return}const c=re("div","toast");_2(c,t,e,a,i),o.appendChild(c);const d={node:c,until:0,timer:0,left:n,sticky:s,group:i?.group};for(gn.unshift(d),wL(c);gn.length>xL;){const p=[...gn].reverse().find(h=>!h.sticky)||gn[gn.length-1];gn.splice(gn.indexOf(p),1),window.clearTimeout(p.timer),p.node.remove()}Sl(),yd(r),nx(d,n)}function ye(t,e="ok",n=4200){Xn(t,e,n)}let C2=!1;function kL(){if(C2)return;const t=tx();t.classList&&(C2=!0,t.addEventListener("pointerenter",()=>{Qv=!0;for(const e of gn)window.clearTimeout(e.timer),!e.sticky&&(e.left=Math.max(600,e.until-Date.now()))}),t.addEventListener("pointerleave",()=>{if(Qv=!1,Di){const e=gu();Di=!1,Sl(),yd(e)}for(const e of gn)nx(e,Math.max(1200,e.left))}),window.addEventListener("resize",()=>Sl(),{passive:!0}))}const ax=new Map;function Hn(t,e){let n=ax.get(t);n||ax.set(t,n=new Set);const a=e;return n.add(a),()=>n.delete(a)}function kd(t,e){ax.get(t)?.forEach(n=>{try{n(e)}catch(a){console.error("bus handler failed",t,a)}})}async function bs(){const[t,e,n,a,i]=await Promise.all([Oe("/api/tree").catch(()=>({})),Oe("/api/folders").catch(()=>null),Oe("/api/stats").catch(()=>({notes:0,links:0,folders:0})),Oe("/api/folder-meta").catch(()=>({})),Oe("/healthz").catch(()=>({}))]);N.tree=t||{},e&&(N.folders=Array.isArray(e.folders)?e.folders:[]),N.stats=n||N.stats,N.folderMeta=a||{},N.health=i||{},te.renderTree()}function vu(){return N.folders.length?new Set(N.folders.map(t=>t.split("/")[0]).filter(t=>t&&!/^root$/i.test(t)&&!t.startsWith("."))).size:N.stats.folders||0}function ix(t){const e=t.toLowerCase();return/^(search|query|find|suggest)/.test(e)?"search":/^(create|batch_create|template_create|duplicate|import|save)/.test(e)?"create":/^(delete|bulk_delete|soft_delete)/.test(e)?"delete":/^(move|rename)/.test(e)?"move":/^(patch|update|set_tags|add_tags|remove_tags|merge|restore|bulk_replace|pin|unpin)/.test(e)?"edit":/^(read|get|list|export|diff|digest|folder_stats|link_stats|broken_links|follow_ups|stale)/.test(e)?"read":"other"}const ox={create:"created",edit:"edited",delete:"deleted",move:"moved",search:"searched for",read:"read",other:"used"};function SL(t,e=48){const n=(t.split("/").pop()||t).replace(/\.md$/i,"").trim();return n.length>e?n.slice(0,e-1)+"…":n}function L2(t,e){if(!e.length)return t;const n=new Set(e.map(o=>ix(o.action)));if(e.length===1){const o=e[0],s=ix(o.action),r=SL(o.label||"");return s==="other"?`${t} used ${o.action.replace(/[_.]+/g," ").trim()||"Memora"}`:r?s==="search"?`${t} searched for “${r}”`:`${t} ${ox[s]} ${r}`:`${t} ${s==="search"?"searched your notes":ox[s]+" a note"}`}const a=new Set(e.map(o=>o.label)).size;if(n.size===1){const o=[...n][0];return o==="search"?`${t} searched your notes ${e.length} times`:o==="other"?`${t} used Memora ${e.length} times`:a===1?L2(t,[e[0]]):`${t} ${ox[o]} ${a} note${a===1?"":"s"}`}const i=e.filter(o=>!["search","read","other"].includes(ix(o.action)));if(i.length){const o=new Set(i.map(s=>s.label)).size;return`${t} changed ${o} note${o===1?"":"s"}`}return`${t} looked through your notes (${e.length} times)`}const sx=["#2dd4bf","#60a5fa","#a78bfa","#f472b6","#fb923c","#facc15","#4ade80","#38bdf8","#e879f9","#f87171","#a3e635","#818cf8"];function ML(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e>>>0}function Co(t){return String(t||"").trim().toLowerCase()}const Ml=new Map,rx=new Map;let lx=null;function R2(t){return lx?lx.has(t):null}const P2="memora:agent-colors";function Sd(t){const e=JSON.stringify([...Ml]);lx=new Set(t.map(a=>a.id)),Ml.clear(),rx.clear();const n=new Map;for(const a of t){const i=a.color&&/^#[0-9a-f]{6}$/i.test(a.color)?a.color.toLowerCase():null;i&&Ml.set(a.id,i);const o=Co(a.name||a.id);n.set(o,n.has(o)&&n.get(o)!==i?null:i)}n.forEach((a,i)=>a&&rx.set(i,a)),JSON.stringify([...Ml])!==e&&window.dispatchEvent(new Event(P2))}function An(t,e){if(e&&Ml.has(e))return Ml.get(e);const n=Co(t);return n?rx.get(n)||sx[ML(n)%sx.length]:"#94a3b8"}function Md(t){const n=String(t||"?").trim().split(/[\s._\-/:@()]+/).filter(Boolean);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();const a=n[0]||"?";return(a.length>1?a[0]+a[1]:a[0]).toUpperCase()}function Yt(t,e=30,n="",a){if(a==="mnemo")return`<span class="ag-av ag-mn${n?" "+n:""}" aria-hidden="true" style="width:${e}px;height:${e}px">${V("mnemo")}</span>`;const i=An(t,a),o=Math.max(9,Math.round(e*.38));return`<span class="ag-av${n?" "+n:""}" aria-hidden="true" style="--ag:${i};width:${e}px;height:${e}px;font-size:${o}px">${x(Md(t))}</span>`}const I2={create_memory:"created",batch_create:"created",duplicate_memory:"created",template_create:"created",import_memory:"created",create_folder:"created",node_created:"created",save_memory:"edited",patch_memory:"edited",add_tags:"edited",remove_tags:"edited",set_tags:"edited",bulk_replace:"edited",merge_memory:"edited",rename_tag:"edited",merge_tag:"edited",set_folder_meta:"edited",restore_memory:"edited",mention_agent:"edited",node_updated:"edited",move_memory:"moved",rename_memory:"moved",move_folder:"moved",move_folder_contents:"moved",rename_folder:"moved",node_renamed:"moved",soft_delete:"trashed",bulk_delete:"trashed",delete_folder:"trashed",delete_memory:"deleted",node_deleted:"deleted",restore_trash:"restored",pin:"pinned",unpin:"pinned",search_memory:"searched",search_by_tag:"searched",query_memory:"searched",find_similar:"searched",suggest_links:"searched",find_path:"searched",search_logs:"searched",set_my_name:"other",set_my_color:"other",lock_node:"other",release_lock:"other",snapshot:"other"},N2=/^(get_|list_|read_|link_stats|folder_stats|broken_links|diff|digest|healthcheck|stale_detection|validate_|presence|follow_ups|export_|admin_list|privacy_list)/,AL=/^(gateway|memora|memora-cli|system|server)$/i,TL=new Set(["actor_alias","key_color","folder_meta"]),Ad=(t,e)=>{const n=t.raw[e];return typeof n=="string"?n:""};function ys(t){if(t.source==="auth")return"system";const e=t.action;return I2[e]?I2[e]:(/^(admin_|privacy_)/.test(e),N2.test(e)?"read":"other")}function ci(t){return t.source==="auth"||AL.test(t.actor)||TL.has(Ad(t,"type"))?!0:!!t.echo}function EL(t){return t.raw.refused===!0}function la(t){return t.running||t.ok!==!1?null:EL(t)?"refused":"failed"}function Oi(t,e=""){return Ad(t,"actor_kind")==="user"||e&&t.actor===e?"You":t.actor}function ws(t){return t.split("/").pop()||t}function cr(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}const Tn=t=>`<em class="act-n">${x(t)}</em>`;function ca(t){return pn(t).replace(/_/g," ")}function Al(t,e){const n=ca(t);return e?`<button type="button" class="act-n" data-note="${C(t)}" title="${C(t)}">${x(n)}</button>`:Tn(n)}function _L(t){const e=t.raw.count;return typeof e=="number"?String(e):t.paths.length>=20?"20+":String(t.paths.length)}function di(t,e,n=e+"s"){return`${t} ${String(t)==="1"?e:n}`}function xu(t){return`“${x(t.length>80?t.slice(0,79)+"…":t)}”`}function cx(t){return t.paths.length>=2?t.paths[1]:""}function da(t){const e=la(t);return e?RL(t,e):z2(t)}function z2(t){const e=t.action,n=ys(t),a=t.paths[0]||"",o=a?Al(a,n!=="deleted"&&n!=="trashed"):"",s=t.label&&!t.paths.includes(t.label)?t.label:"",r=d=>Tn(ws(d)),l=t.raw.folders,c=Array.isArray(l)&&typeof l[0]=="string"?l[0]:"";switch(n){case"system":return O2(t);case"created":{if(e==="create_folder")return`created the folder ${Tn(s||a)}`;if(t.paths.length>1&&e!=="create_memory")return`created ${di(t.paths.length,"note")}`;if(a){const d=cr(a);return`created ${o}${d?` in ${r(d)}`:""}`}return s?`created ${Tn(s)}${c?` in ${r(c)}`:""}`:"created a note"}case"edited":return e==="add_tags"||e==="remove_tags"||e==="set_tags"?a?`changed the tags of ${o}`:"changed some tags":e==="bulk_replace"?t.paths.length?`replaced text in ${di(t.paths.length,"note")}`:"replaced text in your notes":e==="merge_memory"?a?`merged notes into ${o}`:"merged notes":e==="rename_tag"||e==="merge_tag"?s?`renamed the tag ${Tn(s)}`:"renamed a tag":e==="set_folder_meta"?`changed the details of the folder ${Tn(ws(s||a))}`:e==="restore_memory"?a?`brought back an earlier version of ${o}`:"brought back an earlier version of a note":e==="mention_agent"?a?`left a message in ${o}`:"left a message for another AI":a?`edited ${o}`:"changed your notes";case"moved":{if(e==="move_folder"||e==="move_folder_contents"||e==="rename_folder"){const p=Tn(ws(s||a));return e==="rename_folder"?`renamed the folder ${p}`:e==="move_folder"?`moved the folder ${p}`:`moved what is in ${p}`}const d=cx(t);if(d){if(cr(d)===cr(a)&&ca(d)!==ca(a))return`renamed ${Tn(ca(a))} to ${Al(d,!0)}`;const p=cr(d);return`moved ${Al(d,!0)} to ${p?r(p):"the top level"}`}return e==="rename_memory"?a?`renamed ${Tn(ca(a))}`:"renamed a note":a&&c?`moved ${Tn(ca(a))} to ${/^root$/i.test(c)?"the top level":r(c)}`:a?`moved ${Tn(ca(a))}`:"moved a note"}case"trashed":return e==="delete_folder"?`moved the folder ${Tn(ws(s||a))} to Trash`:t.paths.length>1?`moved ${di(t.paths.length,"note")} to Trash`:a?`moved ${o} to Trash`:"moved notes to Trash";case"deleted":return a?`deleted ${o}`:"deleted a note";case"restored":return s||a?`brought back ${Tn(ca(s||a))} from Trash`:"brought back a note from Trash";case"pinned":{const d=a?a.endsWith(".md")?o:`the folder ${Tn(ws(a))}`:"";return e==="unpin"?d?`unpinned ${d}`:"unpinned something":d?`pinned ${d}`:"pinned something"}case"searched":{const d=s||(e==="find_similar"||e==="suggest_links"?"":a);if(e==="find_similar")return a?`looked for notes like ${o}`:"looked for similar notes";if(e==="suggest_links")return a?`looked for links to add to ${o}`:"looked for links to add";if(e==="find_path")return t.paths.length>=2?`looked for a path from ${Al(a,!0)} to ${Al(t.paths[1],!0)}`:"looked for a path between notes";if(e==="search_logs")return d?`searched the activity log for ${xu(d)}`:"searched the activity log";const p=` (${di(_L(t),"result")})`;return e==="search_by_tag"?d?`looked for notes tagged ${Tn("#"+d.replace(/^#/,""))}${p}`:"looked for notes by tag":d?`searched ${xu(d)}${p}`:"searched your notes"}case"read":return CL(t,o,s);default:return e==="set_my_name"?s?`changed its name to ${Tn(s)}`:"changed its name":e==="set_my_color"?"changed its colour":e==="lock_node"?a?`reserved ${o} while it works on it`:"reserved a note":e==="release_lock"?a?`let go of ${o}`:"let go of a note":e==="snapshot"?"saved a snapshot of all your notes":e.startsWith("privacy_")?"changed who can see what":e.startsWith("admin_")?"changed a server setting":t.source==="vault"&&!t.action.startsWith("node_")?O2(t):a?`worked on ${o}`:"did something in your notes"}}function CL(t,e,n){const a=t.action,i=n&&!/\.md$/i.test(n)&&n.length<80?Tn(ws(n)):"";return a==="read_memory"?e?`read ${e}`:"read a note":a==="export_memory"?e?`exported ${e}`:"exported notes":a==="get_neighbors"||a==="get_subgraph"?e?`looked at notes linked to ${e}`:"looked at linked notes":a==="get_history"||a==="get_note_at"||a==="diff"?e?`looked at the history of ${e}`:"looked at a note’s history":a==="validate_memory"?e?`checked ${e}`:"checked a note":a==="list_memory"?i?`looked through ${i}`:"looked through your notes":a==="list_folders"||a==="folder_stats"?i?`looked at the folder ${i}`:"looked at your folders":a==="get_folder_meta"?i?`read the details of the folder ${i}`:"read folder details":a==="healthcheck"?"checked that Memora is working":a==="get_stats"||a==="digest"?"looked at an overview of your notes":/^(get_graph|link_stats|broken_links|get_hubs|get_isolated)$/.test(a)?"looked at how your notes link together":a==="get_tags"||a==="list_tags"?"looked at your tags":a==="get_logs"||a==="get_events"?"looked at recent activity":a==="list_trash"?"looked in Trash":a==="list_pins"?"looked at your pinned notes":/^(get_locks|get_assignments|presence|list_actors)$/.test(a)?"checked who is working on what":/^(get_todos|follow_ups|stale_detection)$/.test(a)?"looked for notes that need attention":a==="admin_list_tools"||a==="privacy_list"?"looked at the server settings":e?`read ${e}`:"looked through your notes"}function D2(t){const e=t.paths[0]||"",n=e?Tn(ca(e)):"",a=t.label&&!t.paths.includes(t.label)?t.label:"";switch(ys(t)){case"created":return n?`create ${n}`:a?`create ${Tn(a)}`:"create a note";case"edited":return n?`change ${n}`:"change your notes";case"read":return n?`read ${n}`:"look through your notes";case"searched":return a?`search ${xu(a)}`:"search your notes";case"moved":return n?`move ${n}`:"move a note";case"trashed":return n?`move ${n} to Trash`:"move notes to Trash";case"deleted":return n?`delete ${n}`:"delete a note";case"restored":return"bring back a note from Trash";case"pinned":return n?`pin ${n}`:"change your pins";default:return t.action.startsWith("admin_")||t.action.startsWith("privacy_")?"change a server setting":"do something"}}function LL(t){return/'write' scope/.test(t)?"but can only read":/'admin' scope/.test(t)?"but does not have full control":/disabled on this server/.test(t)?"but that is switched off on this server":/not allowed/.test(t)?"but is not allowed to":"but was refused"}function RL(t,e){return e==="refused"?`tried to ${D2(t)} ${LL(Ad(t,"error"))}`:`tried to ${D2(t)}, but it did not work`}const PL={signin:"signed in",signout:"signed out",signout_cli:"was signed out from the console",login_fail:"could not sign in",auth_fail:"could not sign in",key_fail:"an unknown key was refused",cooldown:"sign-in paused after too many tries",key_created:"made a new AI key",key_deleted:"removed an AI key",key_restored:"brought back an AI key",key_rolled:"made a new secret for an AI key",key_updated:"changed an AI key",key_permissions:"changed what an AI may do"};function O2(t){const e=PL[t.action],n=t.label&&t.label.length<120?t.label:"";if(e)return x(e);const a=t.action.replace(/[_.]+/g," ").trim();return`${x(a)}${n?` <span class="act-d">${x(n)}</span>`:""}`}const IL={"&":"&","<":"<",">":">",""":'"',"'":"'"};function Wa(t){return t.replace(/<[^>]*>/g,"").replace(/&(amp|lt|gt|quot|#39);/g,e=>IL[e]||e).replace(/\s+/g," ").trim()}function NL(t,e=""){return`${Oi(t,e)} ${Wa(da(t))}`}const zL=120,DL=600,$2=t=>Ad(t,"actor_id")||"name:"+t.actor,F2=t=>`${ys(t)}:${ys(t)==="read"&&t.action!=="read_memory"?"browse":""}`;function U2(t){const e=new Date(t*1e3);return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function bu(t,e=!0,n=zL,a=DL){const i=[];let o=[];const s=()=>{o.length&&(i.push({items:o,it:o[0],kind:ys(o[0]),span:Math.max(0,o[0].ts-o[o.length-1].ts)}),o=[])},r=l=>!!l.running||l.ok===!1||ci(l)||ys(l)==="system";for(const l of t){const c=o[o.length-1];e&&c&&!r(l)&&!r(c)&&$2(l)===$2(c)&&F2(l)===F2(c)&&c.ts-l.ts<=n&&o[0].ts-l.ts<=a&&U2(l.ts)===U2(c.ts)||s(),o.push(l)}return s(),i}function OL(t){if(t.items.length===1)return da(t.it);const e=t.items.length,n=[...new Set(t.items.map(r=>t.kind==="moved"&&cx(r)||r.paths[0]).filter(Boolean))],a=n.length,i=new Set(n.map(cr)),o=i.size===1&&[...i][0]?` in ${Tn(ws([...i][0]))}`:"",s=t.kind==="read"&&t.it.action!=="read_memory";switch(t.kind){case"read":return s||!a?`looked around your notes ${e} times`:`read ${di(a,"note")}${o}`;case"searched":{const r=[...new Set(t.items.map(l=>l.label&&!l.paths.includes(l.label)?l.label:""))];if(r.length<=3&&r.every(Boolean)){const l=r.map(xu);return`searched ${l.length>1?l.slice(0,-1).join(", ")+" and "+l[l.length-1]:l[0]}`}return`searched ${e} times`}case"created":return a?`created ${di(a,"note")}${o}`:`created ${e} notes`;case"edited":return a===1?`edited ${Al(n[0],!0)} ${e} times`:a?`edited ${di(a,"note")}${o}`:`made ${e} changes`;case"moved":return`moved ${di(Math.max(a,1),"note")}`;case"trashed":return`moved ${di(Math.max(a,1),"note")} to Trash`;case"deleted":return`deleted ${di(Math.max(a,1),"note")}`;case"restored":return`brought back ${di(e,"note")} from Trash`;case"pinned":return`changed your pins ${e} times`;default:return`did ${e} things`}}function $L(t){const e=Math.max(1,Math.round(t));return e<60?`${e} s`:`${Math.round(e/60)} min`}const FL=new Set(["create_memory","save_memory","patch_memory","delete_memory","move_memory","rename_memory"]),B2=15,Tl=t=>t.replace(/\.md$/i,"");function UL(t){const e=new Map;for(const i of t)i.source!=="vault"||!i.action.startsWith("node_")||(e.has(i.actor)||e.set(i.actor,[]),e.get(i.actor).push(i));if(!e.size&&!t.some(i=>i.source==="agent"))return;const n=new Set;for(const i of t){if(i.source!=="agent"||i.live)continue;const o=(e.get(i.actor)||[]).filter(l=>!n.has(l)&&l.ts>=i.ts-2&&l.ts-i.ts<=B2),s=i.action;let r;if(s==="create_memory"||s==="template_create"||s==="duplicate_memory")r=o.find(l=>l.action==="node_created"),r&&!i.paths.length&&r.paths[0]&&(i.paths=[r.paths[0]]);else if(s==="move_memory"||s==="rename_memory")r=o.find(l=>l.action==="node_renamed"&&Tl(Ad(l,"old_path"))===Tl(i.paths[0]||"")),r&&r.paths[0]&&i.paths.length<2&&(i.paths=[i.paths[0],r.paths[0]]);else{const l=new Set(i.paths.map(Tl));r=o.find(c=>c.paths.some(d=>l.has(Tl(d))))}r&&(n.add(r),r.echo=!0),i.ok===void 0&&!i.running&&FL.has(s)&&(i.ok=!!r)}const a=new Map;for(const i of t)if(i.source==="agent")for(const o of i.paths){const s=i.actor+"\0"+Tl(o);a.has(s)||a.set(s,[]),a.get(s).push(i.ts)}for(const i of e.values())for(const o of i)o.echo||o.paths.some(s=>(a.get(o.actor+"\0"+Tl(s))||[]).some(r=>Math.abs(r-o.ts)<=B2))&&(o.echo=!0)}const BL=7*86400;function H2(t,e,n=Date.now()/1e3){if(t.source!=="agent"||t.running||t.ok===!1||n-t.ts>BL)return null;const a=t.action;if(a==="move_memory"||a==="rename_memory"){if(t.ok!==!0)return null;const i=t.paths[0],o=cx(t);return!i||!o||i===o||!e(o)||e(i)?null:{type:"moveBack",from:i,to:o}}if(a==="pin"||a==="unpin"){const i=t.paths[0];return i?{type:a==="pin"?"unpin":"pin",path:i,kind:i.endsWith(".md")?"note":"folder"}:null}return null}const q2={create_memory:"Created a note",batch_create:"Created several notes",save_memory:"Rewrote a note",patch_memory:"Edited part of a note",read_memory:"Read a note",search_memory:"Searched notes",query_memory:"Searched with filters",list_memory:"Looked through notes",node_created:"Note created",node_updated:"Note saved",node_renamed:"Note moved or renamed",node_deleted:"Note deleted",folder_changed:"Folder changed"};function dx(t,e="agent"){if(q2[t])return q2[t];const a=Wa(z2({action:t,label:"",paths:[],source:e,raw:{}}));return a.charAt(0).toUpperCase()+a.slice(1)}let HL=0;const px=()=>"a"+(++HL).toString(36),qL=/(fail|denied|invalid|blocked|reject|error|locked)/i;function Ia(t){return typeof t=="string"?t:t==null?"":String(t)}function WL(t){const e=new Set,n=t.paths;Array.isArray(n)&&n.forEach(i=>typeof i=="string"&&i&&e.add(i)),t.path&&e.add(t.path),t.node&&t.node.path&&e.add(t.node.path);const a=Ia(t.label);return/\.md$/i.test(a)&&!/\s/.test(a)&&e.add(a),[...e]}function hx(t){const e=t.type==="ai_activity",n=t.ok,a=t.ms;return{id:px(),ts:Number(t._ts||t.ts||t.at||0),actor:Ia(t.actor||t.by||t.user)||"system",action:Ia(t.action||t.event||t.type)||"activity",label:Ia(t.label||t.node&&(t.node.path||t.node.id)||t.path||t.folder||t.detail||""),paths:WL(t),source:e?"agent":"vault",ok:typeof n=="boolean"?n:void 0,ms:typeof a=="number"?a:void 0,running:e&&t.phase==="start"&&typeof n!="boolean"?!0:void 0,raw:t}}function ux(t){const e=Ia(t.event||t.type)||"auth";return{id:px(),ts:Number(t.at||t.ts||0),actor:Ia(t.user||t.actor)||"gateway",action:e,label:Ia(t.detail||""),paths:[],source:"auth",ok:!qL.test(e),ip:Ia(t.ip)||void 0,raw:t}}function GL(t){return{id:px(),ts:(t.at||Date.now())/1e3,actor:t.actor||"agent",action:t.action||"activity",label:t.label||"",paths:Array.isArray(t.paths)?t.paths.filter(Boolean):[],source:"agent",ok:t.ok,ms:t.ms,running:t.phase==="start"?!0:void 0,live:!0,raw:{...t,...t.actorId?{actor_id:t.actorId}:{},...t.callId?{call_id:t.callId}:{}}}}const El=new Map,VL=1e3;function jL(t,e,n){El.delete(t),El.set(t,{ok:e,ms:n}),El.size>VL&&El.delete(El.keys().next().value)}function W2(t){if(!t.running)return!1;const e=El.get(Ia(t.raw.call_id));return e?(t.running=!1,t.ok=e.ok??!0,e.ms!=null&&(t.ms=e.ms),!0):!1}function dr(t,e=Date.now()/1e3){return!t.running||W2(t)?!1:(e-t.ts>(t.live?120:30)&&(t.running=!1),!!t.running)}function G2(t){const e=[],n=new Map;for(const i of t.sort((o,s)=>o.ts-s.ts)){const o=Ia(i.raw.phase),s=i.actor+"\0"+i.action;if(o==="end"){const r=n.get(s),l=r&&r.shift();if(l&&i.ts-l.ts<600){l.running=!1,l.ok=i.ok??!0,l.ms=i.ms??Math.round((i.ts-l.ts)*1e3),i.paths.length&&(l.paths=[...new Set([...l.paths,...i.paths])]),i.label&&!l.label&&(l.label=i.label);continue}i.running=!1,e.push(i);continue}o==="start"&&(n.has(s)||n.set(s,[]),n.get(s).push(i)),e.push(i)}const a=Date.now()/1e3-30;for(const i of e)!W2(i)&&i.running&&i.ts<a&&(i.running=!1);return UL(e),e.reverse()}const YL={"1h":3600,"1d":86400,"7d":604800,"30d":2592e3};function V2(t){const e=t?new Date(t+"T00:00:00"):new Date;return t||e.setHours(0,0,0,0),e.getTime()/1e3}function j2(t){if(t==="all")return{since:0,until:1/0};if(t==="today")return{since:V2(),until:1/0};if(t.startsWith("day:")){const e=V2(t.slice(4)),n=new Date(e*1e3);return n.setDate(n.getDate()+1),{since:e,until:n.getTime()/1e3}}return{since:Date.now()/1e3-(YL[t]||86400),until:1/0}}const fx=2e3,XL=t=>Number(t._ts||t.ts||t.at||0);async function KL(t,e,n,a){if(n<=fx)return(await Oe(`/api/logs?${t}&limit=${n}`)).events||[];const i=[],o=new Set;let s=e.until;for(;i.length<n;){const r=e.since>0?`&since=${Math.floor(e.since)}`:"",l=Number.isFinite(s)?`&until=${s}`:"",c=(await Oe(`/api/logs?range=all${r}${l}&limit=${fx}`)).events||[];let d=0,p=1/0;for(const h of c){p=Math.min(p,XL(h));const u=JSON.stringify(h);o.has(u)||(o.add(u),i.push(h),d++)}if(c.length<fx||!d||!Number.isFinite(p))break;a?.(i),s=p+.001}return i.slice(0,n)}async function yu(t,e=800,n){const a=j2(t),i=t==="1h"?"range=1d":t==="all"||/^\d+d$/.test(t)?`range=${t}`:`range=1d&since=${Math.floor(a.since)}${Number.isFinite(a.until)?`&until=${Math.ceil(a.until)}`:""}`,s=((await Oe("/api/auth/events?limit=300").catch(()=>({events:[]}))).events||[]).map(ux),r=c=>G2([...c.map(hx),...s.map(d=>({...d}))].filter(d=>d.ts>=a.since&&d.ts<a.until)),l=await KL(i,a,e,n&&(c=>n(r(c)))).catch(()=>[]);return r(l)}function wu(t,e,n=2e3){if(Ia(e.raw.phase)==="end"){const i=Ia(e.raw.call_id),o=i&&t.find(s=>s.running&&Ia(s.raw.call_id)===i)||t.find(s=>s.running&&s.actor===e.actor&&s.action===e.action);if(o)return o.running=!1,o.ok=e.ok??!0,o.ms=e.ms??Math.round((e.ts-o.ts)*1e3),e.paths.length&&(o.paths=[...new Set([...o.paths,...e.paths])]),t;e.running=!1}return t.unshift(e),t.length>n&&(t.length=n),t}class Y2{constructor(e=2e3){this.max=e,this.items=[],this.count=0}get length(){return this.count}push(e){this.items.push(e),this.count++,this.items.length>this.max&&this.items.splice(0,this.items.length-this.max)}take(){const e=this.items;return this.items=[],this.count=0,e}}function ku(t){return Hn("activity",e=>t(GL(e)))}function mx(t){return t.replace(/[_.]+/g," ").trim()}const ZL=`
|
|
2
2
|
.cc{max-width:1240px;margin:0 auto}
|
|
3
3
|
.cc-muted{color:var(--muted)}
|
|
4
4
|
.cc-mono{font-family:var(--mono);font-size:12px}
|
|
@@ -285,7 +285,7 @@ button.act-n:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
|
|
|
285
285
|
<span class="act-meta"><span title="${C(sa(t.ts))}">${gx(t.ts)} · ${$i(t.ts)}</span>${aR(t)}${d}${oR(t)}</span>
|
|
286
286
|
</div>`;return!i||!e.open||e.compact?p:`${p}<div class="act-kids" role="group" aria-label="${C(r)}">${i.items.map(rR).join("")}</div>`}function rR(t){const e=da(t),n=`${Oi(t,ks())} ${Wa(e)}`;return`<div class="act kid" role="button" tabindex="0" data-act="${C(t.id)}" aria-label="${C(n)}">
|
|
287
287
|
<span class="av"></span><span style="min-width:0"><span class="act-l1"><span class="act-p cap">${e}</span></span>${Z2(t,J2(t))}</span>
|
|
288
|
-
<span class="act-meta"><span title="${C(sa(t.ts))}">${gx(t.ts)}</span></span></div>`}const lR='<svg class="cc-i act-chev" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>',eS=t=>en().some(e=>e.path===t);async function tS(t){const e=H2(t,eS);if(!e)return ye("This can no longer be undone: the note has changed since.","warn"),!1;try{if(e.type==="moveBack"){const n=cr(e.from);let a=e.to;cr(a)!==n&&(a=(await Ve("/api/move",{path:a,folder:n||"Root"})).path||a),
|
|
288
|
+
<span class="act-meta"><span title="${C(sa(t.ts))}">${gx(t.ts)}</span></span></div>`}const lR='<svg class="cc-i act-chev" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>',eS=t=>en().some(e=>e.path===t);async function tS(t){const e=H2(t,eS);if(!e)return ye("This can no longer be undone: the note has changed since.","warn"),!1;try{if(e.type==="moveBack"){const n=cr(e.from);let a=e.to;cr(a)!==n&&(a=(await Ve("/api/move",{path:a,folder:n||"Root"})).path||a),pn(a)!==pn(e.from)&&(a=(await Ve("/api/rename",{path:a,name:pn(e.from)})).path||a);const i=n?ws(n):"the top level";ye(a===e.from?`“${ca(e.from)}” is back in ${i}.`:`“${ca(a)}” is back in ${i}, saved as ${pn(a)}.`,"ok")}else{const a=((await Oe("/api/pins")).pins||[]).some(i=>i.kind===e.kind&&i.path===e.path);if(a===(e.type==="pin"))return ye(`Nothing to undo: “${ca(e.path)}” is ${a?"pinned":"not pinned"} already.`,"info"),Eu.add(t.id),!0;await Ve(`/api/pins/${e.type}`,{kind:e.kind,path:e.path}),ye(e.type==="unpin"?`“${ca(e.path)}” is no longer pinned.`:`“${ca(e.path)}” is pinned again.`,"ok")}return Eu.add(t.id),!0}catch(n){return ye(`Could not undo this: ${n.message||"try again in a moment"}.`,"err"),!1}}function cR(t){return!Eu.has(t.id)&&!!H2(t,eS)}function Rl(t,e,n,a={}){t.onclick=i=>{const o=i.target,s=o.closest("[data-burst]");if(s&&a.onBurst){i.stopPropagation(),a.onBurst(s.dataset.burst);return}const r=o.closest("[data-undo]");if(r&&a.onUndo){i.stopPropagation();const h=e(r.dataset.undo);h&&a.onUndo(h);return}const l=o.closest("[data-note]");if(l){i.stopPropagation(),te.openNote(l.dataset.note);return}const c=o.closest("[data-agent-page]");if(c){i.stopPropagation(),hr(c.dataset.agentPage);return}const d=o.closest("[data-act]");if(!d)return;const p=e(d.dataset.act);p&&nS(p,n,a.agentPage)},t.onkeydown=i=>{if(i.key!=="Enter"&&i.key!==" ")return;const o=i.target;if(!o.matches("[data-act]"))return;i.preventDefault();const s=e(o.dataset.act);s&&nS(s,n,a.agentPage)}}function hr(t,e=""){if(t==="mnemo"){te.mnemoActivity();return}lr("/agents/"+encodeURIComponent(t)+(e?"/"+e:"")),te.go("keys")}function nS(t,e,n){Ll(),dr(t);const a=la(t),i=t.running?"Working":a==="refused"?"Refused":a?"Did not work":t.ok===!0||t.ms!=null?"Done":"Recorded",o=t.running?"acc":a?"err":t.ok===!0||t.ms!=null?"ok":"",s={...t.raw},r=typeof s.actor_id=="string"?s.actor_id:null,l=Oi(t,ks()),c=da(t),d=typeof s.error=="string"?s.error:"",p=a==="refused"?`${x(l)} asked for something its access does not allow. If it should be able to, change its access.`:a?`It reached Memora but did not finish${d?`: <span class="cc-mono">${x(d)}</span>`:"."} It often works on the next try.`:"",h=t.source==="agent"?"An AI app (MCP tool call)":t.source==="auth"?"Sign-in and keys (gateway audit)":"Your notes (vault log)",u=t.running?"run":a?"err":o==="ok"?"ok":"idle",f=`<div class="adr-hero" style="--ag:${An(t.actor,r)}">${Yt(t.actor,40,t.running?"live":"",r)}
|
|
289
289
|
<div style="min-width:0"><div class="v"><b style="color:var(--ag)">${x(l)}</b> ${c}</div></div></div>
|
|
290
290
|
<dl class="cc-kv">
|
|
291
291
|
<dt>Result</dt><dd><span class="ad-res ${o}"><span class="cc-dot ${u}"></span>${x(i)}</span></dd>
|
|
@@ -293,7 +293,7 @@ button.act-n:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
|
|
|
293
293
|
${typeof t.raw.for=="string"&&t.raw.for?`<dt>For</dt><dd>${x(t.raw.for)}</dd>`:""}
|
|
294
294
|
<dt>When</dt><dd>${x(new Date(t.ts*1e3).toLocaleString("en-US"))}</dd>
|
|
295
295
|
</dl>
|
|
296
|
-
${t.paths.length?`<div class="ad-sec">${ys(t)==="searched"?"Notes it found":"Notes"} <span class="n">${t.paths.length}</span></div><div class="ad-notes">${t.paths.map(k=>`<button type="button" data-note="${C(k)}">${ve.note}<span style="min-width:0"><span>${x(
|
|
296
|
+
${t.paths.length?`<div class="ad-sec">${ys(t)==="searched"?"Notes it found":"Notes"} <span class="n">${t.paths.length}</span></div><div class="ad-notes">${t.paths.map(k=>`<button type="button" data-note="${C(k)}">${ve.note}<span style="min-width:0"><span>${x(pn(k))}</span><small>${x(k)}</small></span></button>`).join("")}</div>`:""}
|
|
297
297
|
<details class="ad-tech" open><summary>Technical details</summary>
|
|
298
298
|
<dl class="cc-kv">
|
|
299
299
|
<dt>Action</dt><dd class="cc-mono">${x(t.action)}</dd>
|
|
@@ -461,7 +461,7 @@ button.act-n:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
|
|
|
461
461
|
.af-ring{position:absolute;left:0;top:0;width:18px;height:18px;margin:-9px 0 0 -9px;border-radius:50%;border:2px solid var(--c);
|
|
462
462
|
box-shadow:0 0 14px var(--c);animation:af-ring .75s ease-out forwards}
|
|
463
463
|
@keyframes af-ring{from{opacity:.95;transform:var(--t) scale(.4)}to{opacity:0;transform:var(--t) scale(3.4)}}
|
|
464
|
-
`,Ex=new Map,Lu=new Map;let _x=0;const ER=6;function Ru(t,e){e?Ex.set(t,e):Ex.delete(t)}function dS(){Ue("af-css",TR);let t=document.getElementById("afLayer");return t||(t=document.createElement("div"),t.id="afLayer",t.className="af-layer",t.setAttribute("aria-hidden","true"),document.body.appendChild(t)),t}function Pu(t){if(!t)return null;const e=t.getBoundingClientRect();return!e.width&&!e.height?null:{x:e.left+e.width/2,y:e.top+e.height/2}}function pS(t){const n=Ex.get(N.page)?.(t.actor,t.id,t.paths)||null;return n&&n.x>=0&&n.y>=0&&n.x<=innerWidth&&n.y<=innerHeight?n:null}function hS(){const t=document.getElementById("main")?.getBoundingClientRect();return t?{x:t.left+t.width/2,y:t.top+t.height*.45}:{x:innerWidth/2,y:innerHeight/2}}const uS=()=>window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1,_R=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;function fS(t,e,n,a,i){if(uS()||document.hidden||_x>=ER)return;_x++;const o=dS(),s=An(n.actor,n.id),r=document.createElement("div");r.className="af-orb",r.style.setProperty("--c",s),r.textContent=Md(n.actor),o.appendChild(r);const l=e.x-t.x,c=e.y-t.y,d=Math.hypot(l,c)||1,p=Math.min(220,d*.35),h={x:(t.x+e.x)/2-c/d*p*Math.sign(l||1),y:Math.min(t.y,e.y)-p*.4},u=Math.min(1300,650+d*.6),f=b=>{const k=document.createElement("div");k.className="af-ring",k.style.setProperty("--c",s),k.style.setProperty("--t",`translate(${b.x}px,${b.y}px)`),k.style.transform=`translate(${b.x}px,${b.y}px)`,o.appendChild(k),window.setTimeout(()=>k.remove(),800)};a==="start"&&f(t);const v=performance.now();let g=0;const m=b=>{const k=Math.min(1,(b-v)/u),y=_R(k),w=1-y,A=w*w*t.x+2*w*y*h.x+y*y*e.x,_=w*w*t.y+2*w*y*h.y+y*y*e.y,S=.7+Math.sin(Math.PI*k)*.55;if(r.style.transform=`translate(${A}px,${_}px) scale(${S})`,r.style.opacity=String(k>.9?(1-k)*10:Math.min(1,k*6)),b-g>28){g=b;const T=document.createElement("div");T.className="af-dot",T.style.setProperty("--c",s),T.style.setProperty("--t",`translate(${A}px,${_}px)`),T.style.transform=`translate(${A}px,${_}px)`,o.appendChild(T),window.setTimeout(()=>T.remove(),600)}if(k<1){requestAnimationFrame(m);return}r.remove(),_x--,a==="end"&&f(e)};requestAnimationFrame(m)}const Iu=t=>t.id||t.actor;function mS(t){if(uS()||document.hidden)return;const e=document.getElementById("rtPill"),n=e?.getBoundingClientRect();if(!e||!n||!n.width)return;dS();const a=An(t.actor,t.id);e.style.setProperty("--afc",a),e.classList.remove("af-glow"),e.offsetWidth,e.classList.add("af-glow")}const gS=new Set(["graph","canvas"]);function CR(t){if(N.page==="brain")return;if(!gS.has(N.page)){mS(t);return}const e=Pu(document.querySelector("#rtAgents .i"))||Pu(document.getElementById("rtPill"));e&&window.setTimeout(()=>{const n=pS(t)||hS();Lu.set(Iu(t),n),fS(e,n,t,"end")},120)}function LR(t){if(N.page==="brain")return;if(!gS.has(N.page)){Lu.delete(Iu(t)),mS(t);return}const e=Pu(document.querySelector("#rtIdle .i"))||Pu(document.getElementById("rtPill"));if(!e)return;const n=pS(t)||Lu.get(Iu(t))||hS();Lu.delete(Iu(t)),fS(n,e,t,"start")}const RR=new Set(["node_created","node_updated","node_deleted","node_renamed"]),PR=new Set(["pin","unpin"]),IR=5e3,NR=30*6e4,Cx=new Map,Nu=[];function Nd(t){return Nu.push(t),t(zd().length,Pl()),()=>{const e=Nu.indexOf(t);e>=0&&Nu.splice(e,1)}}function vS(t,e=Date.now()){return t.open>0&&e-t.lastAt<2*6e4||e-t.lastAt<IR}function zd(){const t=Date.now();return Pl().filter(e=>e.kind==="agent"&&vS(e,t))}function Pl(){const t=Date.now();return Array.from(Cx.values()).filter(e=>t-e.lastAt<NR).sort((e,n)=>n.lastAt-e.lastAt)}function zR(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function DR(){return(N.me&&(N.me.user||N.me.username)||"").trim()}let Lx=new Map,Ss=null,xS=0;async function Rx(){xS=Date.now();try{const t=await Oe("/api/keys"),e=Array.isArray(t)?t:t.keys||[];Ss=e.filter(n=>n.enabled!==!1).map(n=>({id:n.id,name:n.name||n.id,lastUsed:(n.last_used||0)*1e3})),Sd(e),Dd.paint()}catch{}}function bS(t,e){return t||Ss?.find(n=>n.name===e)?.id||""}function OR(t){const e=new Set(t.map(n=>n.id||n.actor));return Ss?Ss.filter(n=>!e.has(n.id)&&!e.has(n.name)).length:Pl().filter(n=>n.kind==="agent"&&!e.has(n.id||n.actor)).length}function zu(t,e){t.classList.remove(e),t.offsetWidth,t.classList.add(e)}const yS={on:"Live",connecting:"Connecting",off:"Offline"},wS=new Map,Dd={ws:null,tries:0,timer:0,state:"connecting",clients:0,lastActive:-1,stopped:!1,setState(t){const e=t!==this.state;this.state=t,this.paint(),e&&kd("connection",t)},paint(){const t=H("#rtPill"),e=zd(),n=e.length,a=new Map(e.map(l=>[l.id||l.actor,l]));for(const[l,c]of a)Lx.has(l)||CR({actor:c.actor,id:c.id,paths:c.lastPaths||[]});for(const[l,c]of Lx)a.has(l)||LR({actor:c.actor,id:c.id,paths:c.lastPaths||[]});Lx=a;const i=OR(e);!this.stopped&&Date.now()-xS>6e4&&Rx(),t.dataset.state=this.state,H("#rtText").textContent=yS[this.state];const o=H("#rtAgentN"),s=H("#rtAgents"),r=H("#rtIdle");if(this.lastActive>=0&&n>this.lastActive?(s.classList.remove("drop"),r.classList.remove("sleep"),zu(r,"wake"),window.setTimeout(()=>zu(s,"bump"),260)):this.lastActive>=0&&n<this.lastActive&&(s.classList.remove("bump"),r.classList.remove("wake"),zu(s,"drop"),window.setTimeout(()=>zu(r,"sleep"),200)),o.textContent=String(n),H("#rtIdleN").textContent=String(i),s.classList.toggle("on",n>0),r.classList.toggle("none",i===0),t.setAttribute("aria-label",`Realtime ${yS[this.state].toLowerCase()}, ${n} agent${n===1?"":"s"} active, ${i} idle. Show details`),t.title=this.state==="on"?`Live updates on · ${n} active · ${i} idle`:this.state==="off"?"Live updates offline, retrying":"Connecting to live updates",n!==this.lastActive){this.lastActive=n;const l=Pl();for(const c of Nu)c(n,l)}H("#rtPop").classList.contains("hidden")||this.renderPop()},url(){return(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws"},start(){if(this.wirePop(),window.setInterval(()=>this.paint(),1e3),!("WebSocket"in window)){this.setState("off");return}window.addEventListener("online",()=>{this.tries=0,this.kick()}),window.addEventListener("offline",()=>this.setState("off")),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.state==="off"&&(this.tries=0,this.kick())}),this.setState("connecting"),this.kick()},stop(){this.stopped=!0,clearTimeout(this.timer);const t=this.ws;if(this.ws=null,t){t.onopen=t.onmessage=t.onclose=t.onerror=null;try{t.close()}catch{}}this.setState("off")},kick(){if(clearTimeout(this.timer),this.stopped||this.ws&&(this.ws.readyState===0||this.ws.readyState===1))return;let t;try{t=new WebSocket(this.url())}catch{this.retry();return}this.ws=t,this.setState("connecting"),t.onopen=()=>{this.tries=0,this.setState("on")},t.onmessage=e=>{if(this.ws!==t)return;let n=null;try{n=JSON.parse(e.data)}catch{return}this.handle(n)},t.onclose=()=>{this.ws===t&&(this.setState("off"),this.retry())},t.onerror=()=>{try{t.close()}catch{}}},retry(){if(clearTimeout(this.timer),this.stopped)return;this.tries++;const t=Math.min(3e4,1e3*Math.pow(1.6,Math.min(this.tries,6)));this.timer=setTimeout(()=>this.kick(),t),this.tries>1&&this.setState("off")},handle(t){const e=t&&t.type;if(e){if(e==="hello"||e==="presence"){typeof t.clients=="number"&&(this.clients=t.clients,kd("presence",t.clients)),e==="hello"?this.setState("on"):this.paint();return}if(!t.replay){if(RR.has(e)){kd("mutation",t),N.editing||bs().then(()=>{te.refreshPage()});return}if(e==="ai_activity"){this.activity(t);return}if(e==="vault_changed"){te.vaultChanged(String(t.vault||""));return}if(e==="key_color"){Rx();return}if(e==="folder_changed"){N.editing||bs().then(()=>te.refreshPage());return}if(e==="privacy_changed"){window.dispatchEvent(new Event("memora:privacy"));return}if(e==="pins_changed"){const n=typeof t.actor=="string"?t.actor:"";kd("pins",n?{actor:n,actorId:typeof t.actor_id=="string"?t.actor_id:"",kind:t.actor_kind==="user"?"user":"agent"}:null);return}(e==="folder_meta"||e==="actor_alias")&&(N.editing||bs().then(()=>te.refreshTree()))}}},activity(t){const e=String(t.actor||"agent"),n=t.phase==="end"?"end":"start",a={actor:e,action:String(t.action||""),label:String(t.label||t.action||"activity"),phase:n,paths:zR(t.paths),at:Date.now()};typeof t.actor_id=="string"&&(a.actorId=t.actor_id),typeof t.call_id=="string"&&t.call_id&&(a.callId=t.call_id),typeof t.actor_kind=="string"&&(a.kind=t.actor_kind),typeof t.ok=="boolean"&&(a.ok=t.ok),typeof t.ms=="number"&&(a.ms=t.ms);const i=t.actor_kind==="user"||t.actor_kind==null&&e===DR()&&e?"user":"agent",o=typeof t.actor_id=="string"&&t.actor_id?t.actor_id:"",s=o||e,r=Cx.get(s)||{id:o||void 0,actor:e,kind:i,lastAt:0,lastLabel:"",lastAction:"",open:0,calls:0};if(r.kind=i,r.lastAt=a.at,n==="start"?(r.open++,r.calls++,r.lastLabel=a.label,r.lastAction=a.action,r.lastPaths=a.paths,r.lastOk=a.ok,r.lastRefused=t.refused===!0,r.lastError=typeof t.error=="string"?t.error:""):(r.open=Math.max(0,r.open-1),a.action===r.lastAction&&(r.lastOk=a.ok,r.lastRefused=t.refused===!0,r.lastError=typeof t.error=="string"?t.error:""),a.callId&&jL(a.callId,a.ok,a.ms)),Cx.set(s,r),kd("activity",a),this.paint(),n==="start"){if(N.page==="logs")te.refreshLogs?.();else if(N.page!=="brain"&&!N.editing&&i==="agent"&&!PR.has(a.action)&&$v(bS(o,e))){const l="agent:"+s,c=yL(l)&&wS.get(l)||[];c.push({action:a.action,label:a.label}),wS.set(l,c),Xn(L2(e,c),"info",3600,void 0,{group:l,iconHtml:Yt(e,22,"",o||void 0)})}}else a.ok===!1&&N.page!=="brain"&&N.page!=="logs"&&!N.editing&&$v(i==="agent"?bS(o,e):"")&&ye(e+" · "+X6(a.label,60)+" failed","warn",3200)},wirePop(){window.addEventListener(P2,()=>{this.paint(),(N.page==="logs"||N.page==="home"||N.page==="keys")&&te.refreshPage()});const t=H("#rtPill"),e=H("#rtPop");t.onclick=n=>{n.stopPropagation(),e.classList.contains("hidden")?this.openPop():this.closePop()},document.addEventListener("click",n=>{if(e.classList.contains("hidden"))return;const a=n.target;!e.contains(a)&&!t.contains(a)&&this.closePop()}),document.addEventListener("keydown",n=>{n.key==="Escape"&&!e.classList.contains("hidden")&&(n.preventDefault(),this.closePop(!0))})},openPop(){const t=H("#rtPill").getBoundingClientRect(),e=H("#rtPop");e.style.top=Math.round(t.bottom+8)+"px",e.style.right=Math.max(8,Math.round(window.innerWidth-t.right))+"px",this.renderPop(),e.classList.remove("hidden"),H("#rtPill").setAttribute("aria-expanded","true")},closePop(t=!1){H("#rtPop").classList.add("hidden"),fR(),H("#rtPill").setAttribute("aria-expanded","false"),t&&H("#rtPill").focus?.()},renderPop(){const t=Date.now(),e=Pl().filter(s=>s.kind==="agent"),n=new Map(e.map(s=>[s.id||s.actor,s])),a=new Set((Ss||[]).flatMap(s=>[s.id,s.name])),o=[...(Ss||[]).map(s=>({id:s.id,name:s.name,keyed:!0,lastUsed:s.lastUsed})),...e.filter(s=>!a.has(s.id||"")&&!(Ss&&!s.id&&a.has(s.actor))).map(s=>({id:s.id||"",name:s.actor,keyed:!Ss,lastUsed:0}))].map(s=>{const r=n.get(s.id)||n.get(s.name);return{name:s.name,id:s.id||void 0,active:!!r&&vS(r,t),keyed:s.keyed,lastAt:r?.lastAt||0,lastUsed:s.lastUsed,lastAction:r?.lastAction||"",lastLabel:r?.lastLabel||"",lastPaths:r?.lastPaths||[],lastOk:r?.lastOk,lastRefused:r?.lastRefused,lastError:r?.lastError||""}});o.sort((s,r)=>Number(r.active)-Number(s.active)||Math.max(r.lastAt,r.lastUsed||0)-Math.max(s.lastAt,s.lastUsed||0)||s.name.localeCompare(r.name)),xR(H("#rtPop"),{state:this.state,agents:o,close:()=>this.closePop(),retry:()=>{this.tries=0,this.kick()},rerender:()=>this.renderPop()})}},kS="memora.vault.v1",$R="memora.vault.open.v1";function FR(t,e){try{const n=localStorage.getItem(t);return n?{...e,...JSON.parse(n)}:e}catch{return e}}function SS(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch{}}const Ge=FR(kS,{folder:null,sort:"mtime",dir:-1,filter:"all",treeW:264,showNotesInTree:!1,view:"list"});Ge.filter==="agents"&&(Ge.filter="all");function Va(){SS(kS,Ge)}const pn=new Set;function Po(){SS($R,Array.from(pn))}const Je=new Set;function Be(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function ct(t){const e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}const Tt="All notes";function Px(t){return t===""?"Root":t}function Fi(t,e){return e===""?!0:t===e||t.startsWith(e+"/")}let MS="",AS=null,Ix=null;const Il=new Map;function Du(){const t=en(),e=Object.keys(N.tree).join("|")+"#"+N.folders.join("|")+"#"+t.map(o=>o.path).join("|");if(Ix&&AS===N.tree&&e===MS)return Ix;Il.clear();const n={path:"",name:Tt,depth:0,children:[],notes:[],total:0};Il.set("",n);const a=o=>{const s=Il.get(o);if(s)return s;const r=a(Be(o)),l={path:o,name:ct(o),depth:r.depth+1,children:[],notes:[],total:0};return r.children.push(l),Il.set(o,l),l};for(const o of Object.keys(N.tree))o!=="Root"&&a(o);for(const o of N.folders)a(o);for(const o of t)a(Be(o.path)).notes.push(o);const i=o=>(o.children.sort((s,r)=>s.name.localeCompare(r.name,void 0,{numeric:!0})),o.total=o.notes.length+o.children.reduce((s,r)=>s+i(r),0),o.total);return i(n),Ix=n,AS=N.tree,MS=e,n}function Nl(t){return Du(),Il.get(t)||null}function UR(){return Du(),Array.from(Il.keys()).sort((t,e)=>t.localeCompare(e))}function Ms(){const t=new Set(UR());for(const e of N.folders)t.add(e);return t.delete(""),Array.from(t).sort((e,n)=>e.localeCompare(n))}function fr(t){return en().filter(e=>Fi(Be(e.path),t))}function En(t){if(t==="")return"var(--accent)";const e=N.folderMeta[t];if(e&&e.color)return e.color;let n=Be(t);for(;n;){const a=N.folderMeta[n];if(a&&a.color)return a.color;n=Be(n)}return jn(t.split("/")[0])}function Io(t){const e=N.folderMeta[t];return e&&e.icon||""}let ja=[],Ou=0,TS=Promise.resolve();const Nx=new Set;function ES(t){return Nx.add(t),()=>Nx.delete(t)}function $u(){Nx.forEach(t=>{try{t()}catch(e){console.error(e)}})}const Od=(t,e)=>t.kind===e.kind&&t.key===e.key,_S=t=>t.kind+":"+t.key,zx=1400,Fu=new Map;function CS(t){const e=performance.now();for(const[n,a]of Fu)e-a>zx&&Fu.delete(n);Fu.set(_S(t),e)}function BR(t){const e=Fu.get(_S(t));if(e==null)return-1;const n=performance.now()-e;return n<zx?n:-1}let $d=null,LS=!1;const HR=t=>t.kind==="note"?lt(t.key):ct(t.key);function qR(t,e,n){if(t.kind!=="agent"||N.editing||N.page==="brain"||!$v(t.actorId))return;const a=(i,o)=>{if(!o.length)return;const s=o.length===1?HR(o[0]):`${o.length} items`;ye(`${t.actor} ${i} ${s}`,"ok",3200)};a("pinned",e),a("unpinned",n)}function WR(t){if(!t||!Array.isArray(t.pins))return;const e=ja;ja=t.pins.map(a=>({kind:a.kind,key:a.path,missing:!!a.missing}));const n=$d&&performance.now()-$d.at<1e4?$d:null;if($d=null,LS){const a=ja.filter(o=>!e.some(s=>Od(s,o))),i=e.filter(o=>!ja.some(s=>Od(o,s)));a.length<=6&&a.forEach(CS),n&&qR(n,a,i)}LS=!0,$u()}function zl(t,e=!1){Ou++;const n=TS.then(t).then(a=>{Ou--,Ou||WR(a)},a=>{Ou--,e||(ye("Could not save pins: "+a.message,"err"),Dl())});return TS=n,n}function Dl(){return zl(()=>Oe("/api/pins"),!0)}function GR(){const t=e=>!!e.path&&!e.path.split("/").some(n=>!n||n.startsWith("."))&&(e.kind==="folder"||e.path.endsWith(".md"));return m2().filter(t).slice(0,200)}function VR(){zl(async()=>{const t=await Oe("/api/pins"),e=GR();if(!t.pins.length&&e.length){const n=await $n("/api/pins",{method:"PUT",body:{pins:e}});return g2(),n}return m2().length&&g2(),t},!0)}function Ol(){return ja.slice()}function pi(t,e){return ja.some(n=>n.kind===t&&n.key===e)}function mr(t,e){const n=ja.find(o=>Od(o,t)),a=ja.filter(o=>!Od(o,t)),i=e==null?a.length:Math.max(0,Math.min(a.length,e));if(a.splice(i,0,{kind:t.kind,key:t.key,missing:n?n.missing:!1}),ja=a,n||CS(t),$u(),n){const o={pins:a.map(s=>({kind:s.kind,path:s.key}))};zl(()=>$n("/api/pins",{method:"PUT",body:o}))}else{const o={kind:t.kind,path:t.key,position:i};zl(()=>Ve("/api/pins/pin",o))}}function Uu(t){ja=ja.filter(n=>!Od(n,t)),$u();const e={kind:t.kind,path:t.key};zl(()=>Ve("/api/pins/unpin",e))}function Bu(t){return pi(t.kind,t.key)?(Uu(t),!1):(mr(t),!0)}function jR(){return ja=[],$u(),zl(()=>$n("/api/pins",{method:"PUT",body:{pins:[]}}))}function Fd(t,e){Je.delete(t)&&e&&Je.add(e),N.note===t&&(N.note=e);const n=gr.get(t);n&&e&&(gr.delete(t),gr.set(e,n))}function Hu(t,e){const n=a=>a===t||a.startsWith(t+"/")?e==null?null:e+a.slice(t.length):a;for(const a of Array.from(pn)){const i=n(a);pn.delete(a),i!=null&&pn.add(i)}if(Po(),Ge.folder!=null){const a=n(Ge.folder);Ge.folder=a,Va()}}const gr=new Map,RS=()=>N.me&&(N.me.user||N.me.username)||"",Dx=new Set;function YR(t){return Dx.add(t),()=>Dx.delete(t)}function Ox(){Dx.forEach(t=>{try{t()}catch(e){console.error(e)}})}function $x(t){const e=String(t||"?").replace(/[^\p{L}\p{N}]+/gu," ").trim().split(/\s+/).filter(Boolean);return e.length?e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase():"?"}const PS=9e4,vr=new Map;function XR(t,e,n){if(!t||!e||e===RS())return;const a=t.endsWith(".md")?t:t+".md",i=vr.get(a)||new Map;i.set(n||e,{actor:e,id:n,at:Date.now()}),vr.set(a,i)}function KR(t,e){for(const[n,a]of vr)e.has(n)||a.delete(t)&&!a.size&&vr.delete(n)}function IS(){const t=new Set;for(const e of zd())e.id&&t.add(e.id),t.add(e.actor);return t}function NS(t,e=!1){const n=Date.now(),a=IS(),i=new Map;for(const[o,s]of vr)if(!(e?!Fi(Be(o),t):o!==t))for(const[r,l]of s){if(n-l.at>PS||!a.has(r))continue;const c=i.get(r);(!c||c.at<l.at)&&i.set(r,l)}return[...i.values()].sort((o,s)=>s.at-o.at)}let zS="";setInterval(()=>{const t=Date.now();let e=!1;for(const[a,i]of vr){for(const[o,s]of i)t-s.at>PS&&(i.delete(o),e=!0);i.size||vr.delete(a)}const n=[...IS()].sort().join("|");n!==zS&&(zS=n,e=!0),e&&Ox()},1e3);function DS(t,e,n){if(!t||!e||e===RS())return;const a=t.endsWith(".md")?t:t+".md";gr.set(a,{actor:e,action:n,at:Date.now()})}function OS(t){const e=t.node||{};return{type:String(t.type||""),actor:String(t.actor||""),path:String(e.path||t.path||""),oldPath:String(t.old_path||"")}}let $S=0;function ZR(){clearTimeout($S),$S=window.setTimeout(()=>{Dl()},400)}let FS=!1;function Fx(){FS||(FS=!0,VR(),Hn("pins",t=>{t&&($d={...t,at:performance.now()}),Dl()}),Hn("connection",t=>{t==="on"&&Dl()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Dl()}),Hn("activity",t=>{if(!(!t||!t.paths||!t.paths.length)){t.kind!=="user"&&KR(t.actorId||t.actor,new Set(t.paths.map(e=>e.endsWith(".md")?e:e+".md")));for(const e of t.paths)DS(e,t.actor,t.action),t.kind!=="user"&&XR(e,t.actor,t.actorId);Ox()}}),Hn("mutation",t=>{const e=OS(t);e.type==="node_renamed"&&e.oldPath&&e.path&&Fd(e.oldPath,e.path),e.type==="node_deleted"&&e.path&&Fd(e.path,null),e.path&&e.type!=="node_deleted"&&DS(e.path,e.actor,e.type.replace("node_","")),(e.type==="node_created"||e.type==="node_deleted")&&ZR(),Ox()}))}const tt="Mnemo";async function JR(t){const e=await fetch(`/api/assistant/uploads?name=${encodeURIComponent(t.name||"image.png")}`,{method:"POST",credentials:"same-origin",headers:{accept:"application/json","content-type":t.type||"application/octet-stream"},body:t}),n=await e.json().catch(()=>({}));if(!e.ok||!n.id)throw new Error(n.error||`could not attach the image (HTTP ${e.status})`);return n}let qu=null,Wu=null;const Ux=new Set;function za(){return qu}function $l(t=!1){return qu&&!t?Promise.resolve(qu):(Wu||(Wu=Oe("/api/assistant/state").then(e=>US(e)).finally(()=>{Wu=null})),Wu)}function US(t){return qu=t,Ux.forEach(e=>e(t)),t}function Bx(t){return Ux.add(t),()=>Ux.delete(t)}async function Fl(t,e){return US(await Ve(t,e))}const BS=t=>Fl("/api/assistant/providers",t),QR=t=>Fl("/api/assistant/providers/delete",{id:t}),eP=t=>Ve("/api/assistant/providers/test",{id:t}),tP=t=>Fl("/api/assistant/models/fetch",{provider:t}),HS=t=>Fl("/api/assistant/models",t),nP=(t,e)=>Fl("/api/assistant/models/delete",{provider:t,model:e}),xr=t=>Fl("/api/assistant/prefs",t),qS=()=>Oe("/api/assistant/sessions"),aP=t=>Oe(`/api/assistant/sessions?about=${encodeURIComponent(t)}`),iP=(t,e="",n=!1)=>Ve("/api/assistant/sessions",{scope:t,model:e,...n?{fleeting:!0}:{}});function oP(t){try{fetch(`/api/assistant/sessions/${encodeURIComponent(t)}/delete`,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{accept:"application/json","content-type":"application/json"},body:"{}"}).catch(()=>{})}catch{}}const sP=t=>Oe(`/api/assistant/search?q=${encodeURIComponent(t)}&limit=80`),Ud="@mnemo · ",rP=t=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/compact`,{}),WS=t=>Oe(`/api/assistant/sessions/${encodeURIComponent(t)}`),Gu=(t,e)=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}`,e),GS=t=>Ve("/api/assistant/sessions/prune",t),lP=()=>Oe("/api/assistant/skills"),cP=()=>Oe("/api/assistant/suggestions"),dP=t=>Ve("/api/assistant/suggestions",{own:t}),pP=()=>Ve("/api/assistant/suggestions/refresh",{}),hP=(t,e)=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/seen`,{messages:e}),uP=t=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/delete`,{});function fP(t,e,n,a,i,o,s){let r="";try{r=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const l={text:e,...n?{model:n}:{},...a.length?{attach:a.map(c=>({kind:c.kind,path:c.path}))}:{},...r?{tz:r}:{},...s?{answer:s}:{},tz_offset:-new Date().getTimezoneOffset()};return jS(`/api/assistant/sessions/${encodeURIComponent(t)}/chat`,l,i,o)}const VS=t=>`/api/assistant/sessions/${encodeURIComponent(t)}/export`,mP=(t,e)=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/steer`,{text:e}),gP=t=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/stop`,{});async function vP(t,e,n){const a=await fetch(`/api/assistant/sessions/${encodeURIComponent(t)}/live`,{credentials:"same-origin",headers:{accept:"text/event-stream"},signal:e,cache:"no-store"});return a.status===204?!1:(await YS(a,n),!0)}function xP(t,e,n,a,i){return jS(`/api/assistant/sessions/${encodeURIComponent(t)}/rerun`,{message_id:e,...n?{model:n}:{}},a,i)}async function jS(t,e,n,a){const i=await fetch(t,{method:"POST",credentials:"same-origin",headers:{accept:"text/event-stream","content-type":"application/json"},body:JSON.stringify(e),signal:n,cache:"no-store"});await YS(i,a)}async function YS(t,e){if(!t.ok||!t.body){const o=await t.json().catch(()=>({}));throw new Error(o.error||`HTTP ${t.status}`)}const n=t.body.getReader(),a=new TextDecoder;let i="";for(;;){const{value:o,done:s}=await n.read();if(s)break;i+=a.decode(o,{stream:!0});let r;for(;(r=i.indexOf(`
|
|
464
|
+
`,Ex=new Map,Lu=new Map;let _x=0;const ER=6;function Ru(t,e){e?Ex.set(t,e):Ex.delete(t)}function dS(){Ue("af-css",TR);let t=document.getElementById("afLayer");return t||(t=document.createElement("div"),t.id="afLayer",t.className="af-layer",t.setAttribute("aria-hidden","true"),document.body.appendChild(t)),t}function Pu(t){if(!t)return null;const e=t.getBoundingClientRect();return!e.width&&!e.height?null:{x:e.left+e.width/2,y:e.top+e.height/2}}function pS(t){const n=Ex.get(N.page)?.(t.actor,t.id,t.paths)||null;return n&&n.x>=0&&n.y>=0&&n.x<=innerWidth&&n.y<=innerHeight?n:null}function hS(){const t=document.getElementById("main")?.getBoundingClientRect();return t?{x:t.left+t.width/2,y:t.top+t.height*.45}:{x:innerWidth/2,y:innerHeight/2}}const uS=()=>window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1,_R=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;function fS(t,e,n,a,i){if(uS()||document.hidden||_x>=ER)return;_x++;const o=dS(),s=An(n.actor,n.id),r=document.createElement("div");r.className="af-orb",r.style.setProperty("--c",s),r.textContent=Md(n.actor),o.appendChild(r);const l=e.x-t.x,c=e.y-t.y,d=Math.hypot(l,c)||1,p=Math.min(220,d*.35),h={x:(t.x+e.x)/2-c/d*p*Math.sign(l||1),y:Math.min(t.y,e.y)-p*.4},u=Math.min(1300,650+d*.6),f=b=>{const k=document.createElement("div");k.className="af-ring",k.style.setProperty("--c",s),k.style.setProperty("--t",`translate(${b.x}px,${b.y}px)`),k.style.transform=`translate(${b.x}px,${b.y}px)`,o.appendChild(k),window.setTimeout(()=>k.remove(),800)};a==="start"&&f(t);const v=performance.now();let g=0;const m=b=>{const k=Math.min(1,(b-v)/u),y=_R(k),w=1-y,A=w*w*t.x+2*w*y*h.x+y*y*e.x,_=w*w*t.y+2*w*y*h.y+y*y*e.y,S=.7+Math.sin(Math.PI*k)*.55;if(r.style.transform=`translate(${A}px,${_}px) scale(${S})`,r.style.opacity=String(k>.9?(1-k)*10:Math.min(1,k*6)),b-g>28){g=b;const T=document.createElement("div");T.className="af-dot",T.style.setProperty("--c",s),T.style.setProperty("--t",`translate(${A}px,${_}px)`),T.style.transform=`translate(${A}px,${_}px)`,o.appendChild(T),window.setTimeout(()=>T.remove(),600)}if(k<1){requestAnimationFrame(m);return}r.remove(),_x--,a==="end"&&f(e)};requestAnimationFrame(m)}const Iu=t=>t.id||t.actor;function mS(t){if(uS()||document.hidden)return;const e=document.getElementById("rtPill"),n=e?.getBoundingClientRect();if(!e||!n||!n.width)return;dS();const a=An(t.actor,t.id);e.style.setProperty("--afc",a),e.classList.remove("af-glow"),e.offsetWidth,e.classList.add("af-glow")}const gS=new Set(["graph","canvas"]);function CR(t){if(N.page==="brain")return;if(!gS.has(N.page)){mS(t);return}const e=Pu(document.querySelector("#rtAgents .i"))||Pu(document.getElementById("rtPill"));e&&window.setTimeout(()=>{const n=pS(t)||hS();Lu.set(Iu(t),n),fS(e,n,t,"end")},120)}function LR(t){if(N.page==="brain")return;if(!gS.has(N.page)){Lu.delete(Iu(t)),mS(t);return}const e=Pu(document.querySelector("#rtIdle .i"))||Pu(document.getElementById("rtPill"));if(!e)return;const n=pS(t)||Lu.get(Iu(t))||hS();Lu.delete(Iu(t)),fS(n,e,t,"start")}const RR=new Set(["node_created","node_updated","node_deleted","node_renamed"]),PR=new Set(["pin","unpin"]),IR=5e3,NR=30*6e4,Cx=new Map,Nu=[];function Nd(t){return Nu.push(t),t(zd().length,Pl()),()=>{const e=Nu.indexOf(t);e>=0&&Nu.splice(e,1)}}function vS(t,e=Date.now()){return t.open>0&&e-t.lastAt<2*6e4||e-t.lastAt<IR}function zd(){const t=Date.now();return Pl().filter(e=>e.kind==="agent"&&vS(e,t))}function Pl(){const t=Date.now();return Array.from(Cx.values()).filter(e=>t-e.lastAt<NR).sort((e,n)=>n.lastAt-e.lastAt)}function zR(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function DR(){return(N.me&&(N.me.user||N.me.username)||"").trim()}let Lx=new Map,Ss=null,xS=0;async function Rx(){xS=Date.now();try{const t=await Oe("/api/keys"),e=Array.isArray(t)?t:t.keys||[];Ss=e.filter(n=>n.enabled!==!1).map(n=>({id:n.id,name:n.name||n.id,lastUsed:(n.last_used||0)*1e3})),Sd(e),Dd.paint()}catch{}}function bS(t,e){return t||Ss?.find(n=>n.name===e)?.id||""}function OR(t){const e=new Set(t.map(n=>n.id||n.actor));return Ss?Ss.filter(n=>!e.has(n.id)&&!e.has(n.name)).length:Pl().filter(n=>n.kind==="agent"&&!e.has(n.id||n.actor)).length}function zu(t,e){t.classList.remove(e),t.offsetWidth,t.classList.add(e)}const yS={on:"Live",connecting:"Connecting",off:"Offline"},wS=new Map,Dd={ws:null,tries:0,timer:0,state:"connecting",clients:0,lastActive:-1,stopped:!1,setState(t){const e=t!==this.state;this.state=t,this.paint(),e&&kd("connection",t)},paint(){const t=H("#rtPill"),e=zd(),n=e.length,a=new Map(e.map(l=>[l.id||l.actor,l]));for(const[l,c]of a)Lx.has(l)||CR({actor:c.actor,id:c.id,paths:c.lastPaths||[]});for(const[l,c]of Lx)a.has(l)||LR({actor:c.actor,id:c.id,paths:c.lastPaths||[]});Lx=a;const i=OR(e);!this.stopped&&Date.now()-xS>6e4&&Rx(),t.dataset.state=this.state,H("#rtText").textContent=yS[this.state];const o=H("#rtAgentN"),s=H("#rtAgents"),r=H("#rtIdle");if(this.lastActive>=0&&n>this.lastActive?(s.classList.remove("drop"),r.classList.remove("sleep"),zu(r,"wake"),window.setTimeout(()=>zu(s,"bump"),260)):this.lastActive>=0&&n<this.lastActive&&(s.classList.remove("bump"),r.classList.remove("wake"),zu(s,"drop"),window.setTimeout(()=>zu(r,"sleep"),200)),o.textContent=String(n),H("#rtIdleN").textContent=String(i),s.classList.toggle("on",n>0),r.classList.toggle("none",i===0),t.setAttribute("aria-label",`Realtime ${yS[this.state].toLowerCase()}, ${n} agent${n===1?"":"s"} active, ${i} idle. Show details`),t.title=this.state==="on"?`Live updates on · ${n} active · ${i} idle`:this.state==="off"?"Live updates offline, retrying":"Connecting to live updates",n!==this.lastActive){this.lastActive=n;const l=Pl();for(const c of Nu)c(n,l)}H("#rtPop").classList.contains("hidden")||this.renderPop()},url(){return(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws"},start(){if(this.wirePop(),window.setInterval(()=>this.paint(),1e3),!("WebSocket"in window)){this.setState("off");return}window.addEventListener("online",()=>{this.tries=0,this.kick()}),window.addEventListener("offline",()=>this.setState("off")),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.state==="off"&&(this.tries=0,this.kick())}),this.setState("connecting"),this.kick()},stop(){this.stopped=!0,clearTimeout(this.timer);const t=this.ws;if(this.ws=null,t){t.onopen=t.onmessage=t.onclose=t.onerror=null;try{t.close()}catch{}}this.setState("off")},kick(){if(clearTimeout(this.timer),this.stopped||this.ws&&(this.ws.readyState===0||this.ws.readyState===1))return;let t;try{t=new WebSocket(this.url())}catch{this.retry();return}this.ws=t,this.setState("connecting"),t.onopen=()=>{this.tries=0,this.setState("on")},t.onmessage=e=>{if(this.ws!==t)return;let n=null;try{n=JSON.parse(e.data)}catch{return}this.handle(n)},t.onclose=()=>{this.ws===t&&(this.setState("off"),this.retry())},t.onerror=()=>{try{t.close()}catch{}}},retry(){if(clearTimeout(this.timer),this.stopped)return;this.tries++;const t=Math.min(3e4,1e3*Math.pow(1.6,Math.min(this.tries,6)));this.timer=setTimeout(()=>this.kick(),t),this.tries>1&&this.setState("off")},handle(t){const e=t&&t.type;if(e){if(e==="hello"||e==="presence"){typeof t.clients=="number"&&(this.clients=t.clients,kd("presence",t.clients)),e==="hello"?this.setState("on"):this.paint();return}if(!t.replay){if(RR.has(e)){kd("mutation",t),N.editing||bs().then(()=>{te.refreshPage()});return}if(e==="ai_activity"){this.activity(t);return}if(e==="vault_changed"){te.vaultChanged(String(t.vault||""));return}if(e==="key_color"){Rx();return}if(e==="folder_changed"){N.editing||bs().then(()=>te.refreshPage());return}if(e==="privacy_changed"){window.dispatchEvent(new Event("memora:privacy"));return}if(e==="pins_changed"){const n=typeof t.actor=="string"?t.actor:"";kd("pins",n?{actor:n,actorId:typeof t.actor_id=="string"?t.actor_id:"",kind:t.actor_kind==="user"?"user":"agent"}:null);return}(e==="folder_meta"||e==="actor_alias")&&(N.editing||bs().then(()=>te.refreshTree()))}}},activity(t){const e=String(t.actor||"agent"),n=t.phase==="end"?"end":"start",a={actor:e,action:String(t.action||""),label:String(t.label||t.action||"activity"),phase:n,paths:zR(t.paths),at:Date.now()};typeof t.actor_id=="string"&&(a.actorId=t.actor_id),typeof t.call_id=="string"&&t.call_id&&(a.callId=t.call_id),typeof t.actor_kind=="string"&&(a.kind=t.actor_kind),typeof t.ok=="boolean"&&(a.ok=t.ok),typeof t.ms=="number"&&(a.ms=t.ms);const i=t.actor_kind==="user"||t.actor_kind==null&&e===DR()&&e?"user":"agent",o=typeof t.actor_id=="string"&&t.actor_id?t.actor_id:"",s=o||e,r=Cx.get(s)||{id:o||void 0,actor:e,kind:i,lastAt:0,lastLabel:"",lastAction:"",open:0,calls:0};if(r.kind=i,r.lastAt=a.at,n==="start"?(r.open++,r.calls++,r.lastLabel=a.label,r.lastAction=a.action,r.lastPaths=a.paths,r.lastOk=a.ok,r.lastRefused=t.refused===!0,r.lastError=typeof t.error=="string"?t.error:""):(r.open=Math.max(0,r.open-1),a.action===r.lastAction&&(r.lastOk=a.ok,r.lastRefused=t.refused===!0,r.lastError=typeof t.error=="string"?t.error:""),a.callId&&jL(a.callId,a.ok,a.ms)),Cx.set(s,r),kd("activity",a),this.paint(),n==="start"){if(N.page==="logs")te.refreshLogs?.();else if(N.page!=="brain"&&!N.editing&&i==="agent"&&!PR.has(a.action)&&$v(bS(o,e))){const l="agent:"+s,c=yL(l)&&wS.get(l)||[];c.push({action:a.action,label:a.label}),wS.set(l,c),Xn(L2(e,c),"info",3600,void 0,{group:l,iconHtml:Yt(e,22,"",o||void 0)})}}else a.ok===!1&&N.page!=="brain"&&N.page!=="logs"&&!N.editing&&$v(i==="agent"?bS(o,e):"")&&ye(e+" · "+X6(a.label,60)+" failed","warn",3200)},wirePop(){window.addEventListener(P2,()=>{this.paint(),(N.page==="logs"||N.page==="home"||N.page==="keys")&&te.refreshPage()});const t=H("#rtPill"),e=H("#rtPop");t.onclick=n=>{n.stopPropagation(),e.classList.contains("hidden")?this.openPop():this.closePop()},document.addEventListener("click",n=>{if(e.classList.contains("hidden"))return;const a=n.target;!e.contains(a)&&!t.contains(a)&&this.closePop()}),document.addEventListener("keydown",n=>{n.key==="Escape"&&!e.classList.contains("hidden")&&(n.preventDefault(),this.closePop(!0))})},openPop(){const t=H("#rtPill").getBoundingClientRect(),e=H("#rtPop");e.style.top=Math.round(t.bottom+8)+"px",e.style.right=Math.max(8,Math.round(window.innerWidth-t.right))+"px",this.renderPop(),e.classList.remove("hidden"),H("#rtPill").setAttribute("aria-expanded","true")},closePop(t=!1){H("#rtPop").classList.add("hidden"),fR(),H("#rtPill").setAttribute("aria-expanded","false"),t&&H("#rtPill").focus?.()},renderPop(){const t=Date.now(),e=Pl().filter(s=>s.kind==="agent"),n=new Map(e.map(s=>[s.id||s.actor,s])),a=new Set((Ss||[]).flatMap(s=>[s.id,s.name])),o=[...(Ss||[]).map(s=>({id:s.id,name:s.name,keyed:!0,lastUsed:s.lastUsed})),...e.filter(s=>!a.has(s.id||"")&&!(Ss&&!s.id&&a.has(s.actor))).map(s=>({id:s.id||"",name:s.actor,keyed:!Ss,lastUsed:0}))].map(s=>{const r=n.get(s.id)||n.get(s.name);return{name:s.name,id:s.id||void 0,active:!!r&&vS(r,t),keyed:s.keyed,lastAt:r?.lastAt||0,lastUsed:s.lastUsed,lastAction:r?.lastAction||"",lastLabel:r?.lastLabel||"",lastPaths:r?.lastPaths||[],lastOk:r?.lastOk,lastRefused:r?.lastRefused,lastError:r?.lastError||""}});o.sort((s,r)=>Number(r.active)-Number(s.active)||Math.max(r.lastAt,r.lastUsed||0)-Math.max(s.lastAt,s.lastUsed||0)||s.name.localeCompare(r.name)),xR(H("#rtPop"),{state:this.state,agents:o,close:()=>this.closePop(),retry:()=>{this.tries=0,this.kick()},rerender:()=>this.renderPop()})}},kS="memora.vault.v1",$R="memora.vault.open.v1";function FR(t,e){try{const n=localStorage.getItem(t);return n?{...e,...JSON.parse(n)}:e}catch{return e}}function SS(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch{}}const Ge=FR(kS,{folder:null,sort:"mtime",dir:-1,filter:"all",treeW:264,showNotesInTree:!1,view:"list"});Ge.filter==="agents"&&(Ge.filter="all");function Va(){SS(kS,Ge)}const hn=new Set;function Po(){SS($R,Array.from(hn))}const Je=new Set;function Be(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function ct(t){const e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}const Tt="All notes";function Px(t){return t===""?"Root":t}function Fi(t,e){return e===""?!0:t===e||t.startsWith(e+"/")}let MS="",AS=null,Ix=null;const Il=new Map;function Du(){const t=en(),e=Object.keys(N.tree).join("|")+"#"+N.folders.join("|")+"#"+t.map(o=>o.path).join("|");if(Ix&&AS===N.tree&&e===MS)return Ix;Il.clear();const n={path:"",name:Tt,depth:0,children:[],notes:[],total:0};Il.set("",n);const a=o=>{const s=Il.get(o);if(s)return s;const r=a(Be(o)),l={path:o,name:ct(o),depth:r.depth+1,children:[],notes:[],total:0};return r.children.push(l),Il.set(o,l),l};for(const o of Object.keys(N.tree))o!=="Root"&&a(o);for(const o of N.folders)a(o);for(const o of t)a(Be(o.path)).notes.push(o);const i=o=>(o.children.sort((s,r)=>s.name.localeCompare(r.name,void 0,{numeric:!0})),o.total=o.notes.length+o.children.reduce((s,r)=>s+i(r),0),o.total);return i(n),Ix=n,AS=N.tree,MS=e,n}function Nl(t){return Du(),Il.get(t)||null}function UR(){return Du(),Array.from(Il.keys()).sort((t,e)=>t.localeCompare(e))}function Ms(){const t=new Set(UR());for(const e of N.folders)t.add(e);return t.delete(""),Array.from(t).sort((e,n)=>e.localeCompare(n))}function fr(t){return en().filter(e=>Fi(Be(e.path),t))}function En(t){if(t==="")return"var(--accent)";const e=N.folderMeta[t];if(e&&e.color)return e.color;let n=Be(t);for(;n;){const a=N.folderMeta[n];if(a&&a.color)return a.color;n=Be(n)}return jn(t.split("/")[0])}function Io(t){const e=N.folderMeta[t];return e&&e.icon||""}let ja=[],Ou=0,TS=Promise.resolve();const Nx=new Set;function ES(t){return Nx.add(t),()=>Nx.delete(t)}function $u(){Nx.forEach(t=>{try{t()}catch(e){console.error(e)}})}const Od=(t,e)=>t.kind===e.kind&&t.key===e.key,_S=t=>t.kind+":"+t.key,zx=1400,Fu=new Map;function CS(t){const e=performance.now();for(const[n,a]of Fu)e-a>zx&&Fu.delete(n);Fu.set(_S(t),e)}function BR(t){const e=Fu.get(_S(t));if(e==null)return-1;const n=performance.now()-e;return n<zx?n:-1}let $d=null,LS=!1;const HR=t=>t.kind==="note"?lt(t.key):ct(t.key);function qR(t,e,n){if(t.kind!=="agent"||N.editing||N.page==="brain"||!$v(t.actorId))return;const a=(i,o)=>{if(!o.length)return;const s=o.length===1?HR(o[0]):`${o.length} items`;ye(`${t.actor} ${i} ${s}`,"ok",3200)};a("pinned",e),a("unpinned",n)}function WR(t){if(!t||!Array.isArray(t.pins))return;const e=ja;ja=t.pins.map(a=>({kind:a.kind,key:a.path,missing:!!a.missing}));const n=$d&&performance.now()-$d.at<1e4?$d:null;if($d=null,LS){const a=ja.filter(o=>!e.some(s=>Od(s,o))),i=e.filter(o=>!ja.some(s=>Od(o,s)));a.length<=6&&a.forEach(CS),n&&qR(n,a,i)}LS=!0,$u()}function zl(t,e=!1){Ou++;const n=TS.then(t).then(a=>{Ou--,Ou||WR(a)},a=>{Ou--,e||(ye("Could not save pins: "+a.message,"err"),Dl())});return TS=n,n}function Dl(){return zl(()=>Oe("/api/pins"),!0)}function GR(){const t=e=>!!e.path&&!e.path.split("/").some(n=>!n||n.startsWith("."))&&(e.kind==="folder"||e.path.endsWith(".md"));return m2().filter(t).slice(0,200)}function VR(){zl(async()=>{const t=await Oe("/api/pins"),e=GR();if(!t.pins.length&&e.length){const n=await $n("/api/pins",{method:"PUT",body:{pins:e}});return g2(),n}return m2().length&&g2(),t},!0)}function Ol(){return ja.slice()}function pi(t,e){return ja.some(n=>n.kind===t&&n.key===e)}function mr(t,e){const n=ja.find(o=>Od(o,t)),a=ja.filter(o=>!Od(o,t)),i=e==null?a.length:Math.max(0,Math.min(a.length,e));if(a.splice(i,0,{kind:t.kind,key:t.key,missing:n?n.missing:!1}),ja=a,n||CS(t),$u(),n){const o={pins:a.map(s=>({kind:s.kind,path:s.key}))};zl(()=>$n("/api/pins",{method:"PUT",body:o}))}else{const o={kind:t.kind,path:t.key,position:i};zl(()=>Ve("/api/pins/pin",o))}}function Uu(t){ja=ja.filter(n=>!Od(n,t)),$u();const e={kind:t.kind,path:t.key};zl(()=>Ve("/api/pins/unpin",e))}function Bu(t){return pi(t.kind,t.key)?(Uu(t),!1):(mr(t),!0)}function jR(){return ja=[],$u(),zl(()=>$n("/api/pins",{method:"PUT",body:{pins:[]}}))}function Fd(t,e){Je.delete(t)&&e&&Je.add(e),N.note===t&&(N.note=e);const n=gr.get(t);n&&e&&(gr.delete(t),gr.set(e,n))}function Hu(t,e){const n=a=>a===t||a.startsWith(t+"/")?e==null?null:e+a.slice(t.length):a;for(const a of Array.from(hn)){const i=n(a);hn.delete(a),i!=null&&hn.add(i)}if(Po(),Ge.folder!=null){const a=n(Ge.folder);Ge.folder=a,Va()}}const gr=new Map,RS=()=>N.me&&(N.me.user||N.me.username)||"",Dx=new Set;function YR(t){return Dx.add(t),()=>Dx.delete(t)}function Ox(){Dx.forEach(t=>{try{t()}catch(e){console.error(e)}})}function $x(t){const e=String(t||"?").replace(/[^\p{L}\p{N}]+/gu," ").trim().split(/\s+/).filter(Boolean);return e.length?e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase():"?"}const PS=9e4,vr=new Map;function XR(t,e,n){if(!t||!e||e===RS())return;const a=t.endsWith(".md")?t:t+".md",i=vr.get(a)||new Map;i.set(n||e,{actor:e,id:n,at:Date.now()}),vr.set(a,i)}function KR(t,e){for(const[n,a]of vr)e.has(n)||a.delete(t)&&!a.size&&vr.delete(n)}function IS(){const t=new Set;for(const e of zd())e.id&&t.add(e.id),t.add(e.actor);return t}function NS(t,e=!1){const n=Date.now(),a=IS(),i=new Map;for(const[o,s]of vr)if(!(e?!Fi(Be(o),t):o!==t))for(const[r,l]of s){if(n-l.at>PS||!a.has(r))continue;const c=i.get(r);(!c||c.at<l.at)&&i.set(r,l)}return[...i.values()].sort((o,s)=>s.at-o.at)}let zS="";setInterval(()=>{const t=Date.now();let e=!1;for(const[a,i]of vr){for(const[o,s]of i)t-s.at>PS&&(i.delete(o),e=!0);i.size||vr.delete(a)}const n=[...IS()].sort().join("|");n!==zS&&(zS=n,e=!0),e&&Ox()},1e3);function DS(t,e,n){if(!t||!e||e===RS())return;const a=t.endsWith(".md")?t:t+".md";gr.set(a,{actor:e,action:n,at:Date.now()})}function OS(t){const e=t.node||{};return{type:String(t.type||""),actor:String(t.actor||""),path:String(e.path||t.path||""),oldPath:String(t.old_path||"")}}let $S=0;function ZR(){clearTimeout($S),$S=window.setTimeout(()=>{Dl()},400)}let FS=!1;function Fx(){FS||(FS=!0,VR(),Hn("pins",t=>{t&&($d={...t,at:performance.now()}),Dl()}),Hn("connection",t=>{t==="on"&&Dl()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Dl()}),Hn("activity",t=>{if(!(!t||!t.paths||!t.paths.length)){t.kind!=="user"&&KR(t.actorId||t.actor,new Set(t.paths.map(e=>e.endsWith(".md")?e:e+".md")));for(const e of t.paths)DS(e,t.actor,t.action),t.kind!=="user"&&XR(e,t.actor,t.actorId);Ox()}}),Hn("mutation",t=>{const e=OS(t);e.type==="node_renamed"&&e.oldPath&&e.path&&Fd(e.oldPath,e.path),e.type==="node_deleted"&&e.path&&Fd(e.path,null),e.path&&e.type!=="node_deleted"&&DS(e.path,e.actor,e.type.replace("node_","")),(e.type==="node_created"||e.type==="node_deleted")&&ZR(),Ox()}))}const tt="Mnemo";async function JR(t){const e=await fetch(`/api/assistant/uploads?name=${encodeURIComponent(t.name||"image.png")}`,{method:"POST",credentials:"same-origin",headers:{accept:"application/json","content-type":t.type||"application/octet-stream"},body:t}),n=await e.json().catch(()=>({}));if(!e.ok||!n.id)throw new Error(n.error||`could not attach the image (HTTP ${e.status})`);return n}let qu=null,Wu=null;const Ux=new Set;function za(){return qu}function $l(t=!1){return qu&&!t?Promise.resolve(qu):(Wu||(Wu=Oe("/api/assistant/state").then(e=>US(e)).finally(()=>{Wu=null})),Wu)}function US(t){return qu=t,Ux.forEach(e=>e(t)),t}function Bx(t){return Ux.add(t),()=>Ux.delete(t)}async function Fl(t,e){return US(await Ve(t,e))}const BS=t=>Fl("/api/assistant/providers",t),QR=t=>Fl("/api/assistant/providers/delete",{id:t}),eP=t=>Ve("/api/assistant/providers/test",{id:t}),tP=t=>Fl("/api/assistant/models/fetch",{provider:t}),HS=t=>Fl("/api/assistant/models",t),nP=(t,e)=>Fl("/api/assistant/models/delete",{provider:t,model:e}),xr=t=>Fl("/api/assistant/prefs",t),qS=()=>Oe("/api/assistant/sessions"),aP=t=>Oe(`/api/assistant/sessions?about=${encodeURIComponent(t)}`),iP=(t,e="",n=!1)=>Ve("/api/assistant/sessions",{scope:t,model:e,...n?{fleeting:!0}:{}});function oP(t){try{fetch(`/api/assistant/sessions/${encodeURIComponent(t)}/delete`,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{accept:"application/json","content-type":"application/json"},body:"{}"}).catch(()=>{})}catch{}}const sP=t=>Oe(`/api/assistant/search?q=${encodeURIComponent(t)}&limit=80`),Ud="@mnemo · ",rP=t=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/compact`,{}),WS=t=>Oe(`/api/assistant/sessions/${encodeURIComponent(t)}`),Gu=(t,e)=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}`,e),GS=t=>Ve("/api/assistant/sessions/prune",t),lP=()=>Oe("/api/assistant/skills"),cP=()=>Oe("/api/assistant/suggestions"),dP=t=>Ve("/api/assistant/suggestions",{own:t}),pP=()=>Ve("/api/assistant/suggestions/refresh",{}),hP=(t,e)=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/seen`,{messages:e}),uP=t=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/delete`,{});function fP(t,e,n,a,i,o,s){let r="";try{r=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const l={text:e,...n?{model:n}:{},...a.length?{attach:a.map(c=>({kind:c.kind,path:c.path}))}:{},...r?{tz:r}:{},...s?{answer:s}:{},tz_offset:-new Date().getTimezoneOffset()};return jS(`/api/assistant/sessions/${encodeURIComponent(t)}/chat`,l,i,o)}const VS=t=>`/api/assistant/sessions/${encodeURIComponent(t)}/export`,mP=(t,e)=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/steer`,{text:e}),gP=t=>Ve(`/api/assistant/sessions/${encodeURIComponent(t)}/stop`,{});async function vP(t,e,n){const a=await fetch(`/api/assistant/sessions/${encodeURIComponent(t)}/live`,{credentials:"same-origin",headers:{accept:"text/event-stream"},signal:e,cache:"no-store"});return a.status===204?!1:(await YS(a,n),!0)}function xP(t,e,n,a,i){return jS(`/api/assistant/sessions/${encodeURIComponent(t)}/rerun`,{message_id:e,...n?{model:n}:{}},a,i)}async function jS(t,e,n,a){const i=await fetch(t,{method:"POST",credentials:"same-origin",headers:{accept:"text/event-stream","content-type":"application/json"},body:JSON.stringify(e),signal:n,cache:"no-store"});await YS(i,a)}async function YS(t,e){if(!t.ok||!t.body){const o=await t.json().catch(()=>({}));throw new Error(o.error||`HTTP ${t.status}`)}const n=t.body.getReader(),a=new TextDecoder;let i="";for(;;){const{value:o,done:s}=await n.read();if(s)break;i+=a.decode(o,{stream:!0});let r;for(;(r=i.indexOf(`
|
|
465
465
|
|
|
466
466
|
`))>=0;){const l=i.slice(0,r);i=i.slice(r+2);const c=l.split(`
|
|
467
467
|
`).filter(d=>d.startsWith("data:")).map(d=>d.slice(5).replace(/^ /,"")).join(`
|
|
@@ -1938,7 +1938,7 @@ button.ax-kpi:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
|
|
|
1938
1938
|
${t.narrowed?'<button type="button" class="btn" data-pick="clear">Clear search and filters</button>':""}</div>`}function KP(t){return t.replace(/(<div class="act[^"]*"[^>]*>)(\s*<span class="av">[\s\S]*?)<span class="act-meta"><span title="([^"]*)">([^<]*?)(?: · ([^<]*))?<\/span>/g,(e,n,a,i,o,s)=>`${n}<span class="act-t" title="${i}"><b>${o}</b>${s?`<small>${s==="now"?"just now":s==="-"?"":x(s)+" ago"}</small>`:""}</span>${a}<span class="act-meta">`)}function MM(t){if(!t.rows.length)return t.older&&!t.narrowed?SM():XP(t);const e=new Map;for(const s of t.rows){const r=wr(s.ts),l=e.get(r)||{n:0,f:0};l.n++,ka(s)==="fail"&&l.f++,e.set(r,l)}const n=bu(t.rows,t.compact),a=n.slice(0,t.limit);let i="",o="";for(const s of a){const r=wr(s.it.ts);if(r!==o){o&&(i+="</div></section>"),o=r;const l=YP(s.it.ts),c=e.get(r);i+=`<section class="ax-day" data-day="${r}" aria-label="${C(l.t)}"><h3 class="ax-dh"><span class="ax-dh-c"><span class="ax-dh-t">${x(l.t)}</span><span class="ax-dh-d">${x(l.d)}</span></span><span class="grow"></span><span class="ax-dh-n">${Zt(c.n,"action")}${c.f?`<span class="ax-dh-f">${Zt(c.f,"problem")}</span>`:""}</span></h3><div class="act-list">`}i+=KP(Q2(s.it,{fresh:t.fresh.has(s.it.id),burst:s,open:t.open.has(s.it.id),undo:s.items.length===1&&cR(s.it)}))}return o&&(i+="</div></section>"),n.length>a.length||t.older?i+=SM():i+='<div class="tl-end">That’s everything</div>',i}const eb=new WeakMap;function AM(t,e,n){eb.get(t)?.disconnect();const a=t.querySelector("[data-sentinel]");if(!a||typeof IntersectionObserver>"u")return;const i=new IntersectionObserver(o=>{o.some(s=>s.isIntersecting)&&(i.disconnect(),n())},{root:e,rootMargin:"0px 0px 600px 0px"});eb.set(t,i),i.observe(a)}function ZP(t){t&&eb.get(t)?.disconnect()}function JP(t,e,n="Nothing in this range"){if(!t.length)return`<div class="ax-bempty">${x(n)}</div>`;const a=Math.max(1,...t.map(i=>i.n));return`<div class="ax-hbs">${t.map(i=>`<button type="button" class="ax-hb" data-f="${C(i.f)}" style="--c:${i.color}" title="${C(`Show only: ${i.label}`)}">
|
|
1939
1939
|
<span class="ax-hb-l">${i.lead||'<i class="sw"></i>'}<span class="t">${x(i.label)}</span></span>
|
|
1940
1940
|
<span class="ax-hb-n">${i.n}<em>${e?Math.round(i.n/e*100):0}%</em></span>
|
|
1941
|
-
<span class="ax-hb-track"><span style="width:${Math.max(2,i.n/a*100)}%"></span></span></button>`).join("")}</div>`}function TM(t,e=6){const n=new Map;t.forEach(i=>(n.get(i.action)||n.set(i.action,[]).get(i.action)).push(i));const a=[...n.entries()].sort((i,o)=>o[1].length-i[1].length).slice(0,e);return JP(a.map(([i,o])=>({label:dx(i,o[0].source),n:o.length,color:Gl[yr(o[0])],f:"actions:"+i})),t.length)}function EM(t,e){if(!t.length)return'<div class="ax-bempty">Nothing in this range</div>';const n=Date.now()/1e3,a=Number.isFinite(e.until)?Math.min(e.until,n):n,i=e.since>0?e.since:Math.min(...t.map(m=>m.ts)),s=a-i<=2*86400,r=s?3600:86400,l=new Date(i*1e3);s?l.setMinutes(0,0,0):l.setHours(0,0,0,0);const c=l.getTime()/1e3,d=Math.min(s?48:62,Math.max(1,Math.ceil((a-c)/r))),p=a-d*r<c?c:c+(Math.ceil((a-c)/r)-d)*r,h=new Array(d).fill(0),u=new Array(d).fill(0);t.forEach(m=>{const b=Math.floor((m.ts-p)/r);b>=0&&b<d&&(h[b]++,ka(m)==="fail"&&u[b]++)});const f=Math.max(1,...h),v=m=>{const b=new Date((p+m*r)*1e3);return s?b.toLocaleTimeString("en-US",{hour:"numeric"}):b.toLocaleDateString("en-US",{month:"short",day:"numeric"})},g=[0,Math.floor((d-1)/2),d-1].filter((m,b,k)=>k.indexOf(m)===b);return`<div class="ax-cols" role="img" aria-label="Actions per ${s?"hour":"day"}">${h.map((m,b)=>`<span class="ax-col" title="${C(`${v(b)}: ${Zt(m,"action")}${u[b]?`, ${Zt(u[b],"problem")}`:""}`)}"><i style="height:${m?Math.max(4,m/f*100):0}%"><b style="height:${m?u[b]/m*100:0}%"></b></i></span>`).join("")}</div><div class="ax-ticks">${g.map(m=>`<span>${x(v(m))}</span>`).join("")}</div>`}function _M(t,e){const n=Date.now()/1e3,a=Number.isFinite(e.until)?Math.min(e.until,n):n,i=e.since>0?e.since:t.length?t[t.length-1].ts:n;return a-i<=2*86400?"Actions per hour":"Actions per day"}function CM(t,e=6,n="No notes were touched in this range"){const a=new Map;t.forEach(o=>o.paths.forEach(s=>a.set(s,(a.get(s)||0)+1)));const i=[...a.entries()].sort((o,s)=>s[1]-o[1]).slice(0,e);return i.length?`<div class="sm-notes">${i.map(([o,s])=>{const r=o.includes("/")?o.slice(0,o.lastIndexOf("/")):"Top level";return`<button type="button" class="ax-node" data-note="${C(o)}" title="${C(`Open ${o}`)}">${ve.note}<span class="t"><span>${x(
|
|
1941
|
+
<span class="ax-hb-track"><span style="width:${Math.max(2,i.n/a*100)}%"></span></span></button>`).join("")}</div>`}function TM(t,e=6){const n=new Map;t.forEach(i=>(n.get(i.action)||n.set(i.action,[]).get(i.action)).push(i));const a=[...n.entries()].sort((i,o)=>o[1].length-i[1].length).slice(0,e);return JP(a.map(([i,o])=>({label:dx(i,o[0].source),n:o.length,color:Gl[yr(o[0])],f:"actions:"+i})),t.length)}function EM(t,e){if(!t.length)return'<div class="ax-bempty">Nothing in this range</div>';const n=Date.now()/1e3,a=Number.isFinite(e.until)?Math.min(e.until,n):n,i=e.since>0?e.since:Math.min(...t.map(m=>m.ts)),s=a-i<=2*86400,r=s?3600:86400,l=new Date(i*1e3);s?l.setMinutes(0,0,0):l.setHours(0,0,0,0);const c=l.getTime()/1e3,d=Math.min(s?48:62,Math.max(1,Math.ceil((a-c)/r))),p=a-d*r<c?c:c+(Math.ceil((a-c)/r)-d)*r,h=new Array(d).fill(0),u=new Array(d).fill(0);t.forEach(m=>{const b=Math.floor((m.ts-p)/r);b>=0&&b<d&&(h[b]++,ka(m)==="fail"&&u[b]++)});const f=Math.max(1,...h),v=m=>{const b=new Date((p+m*r)*1e3);return s?b.toLocaleTimeString("en-US",{hour:"numeric"}):b.toLocaleDateString("en-US",{month:"short",day:"numeric"})},g=[0,Math.floor((d-1)/2),d-1].filter((m,b,k)=>k.indexOf(m)===b);return`<div class="ax-cols" role="img" aria-label="Actions per ${s?"hour":"day"}">${h.map((m,b)=>`<span class="ax-col" title="${C(`${v(b)}: ${Zt(m,"action")}${u[b]?`, ${Zt(u[b],"problem")}`:""}`)}"><i style="height:${m?Math.max(4,m/f*100):0}%"><b style="height:${m?u[b]/m*100:0}%"></b></i></span>`).join("")}</div><div class="ax-ticks">${g.map(m=>`<span>${x(v(m))}</span>`).join("")}</div>`}function _M(t,e){const n=Date.now()/1e3,a=Number.isFinite(e.until)?Math.min(e.until,n):n,i=e.since>0?e.since:t.length?t[t.length-1].ts:n;return a-i<=2*86400?"Actions per hour":"Actions per day"}function CM(t,e=6,n="No notes were touched in this range"){const a=new Map;t.forEach(o=>o.paths.forEach(s=>a.set(s,(a.get(s)||0)+1)));const i=[...a.entries()].sort((o,s)=>s[1]-o[1]).slice(0,e);return i.length?`<div class="sm-notes">${i.map(([o,s])=>{const r=o.includes("/")?o.slice(0,o.lastIndexOf("/")):"Top level";return`<button type="button" class="ax-node" data-note="${C(o)}" title="${C(`Open ${o}`)}">${ve.note}<span class="t"><span>${x(pn(o))}</span><small>${x(r)}</small></span><span class="n">${s}×</span></button>`}).join("")}</div>`:`<div class="sm-card-b"><div class="ax-bempty">${x(n)}</div></div>`}function LM(t){const e=new Map;t.forEach(a=>a.paths.forEach(i=>e.set(i,(e.get(i)||0)+1)));const n=[...e.entries()].sort((a,i)=>i[1]-a[1])[0];return{n:e.size,top:n?pn(n[0]):""}}function RM(t,e=4,n=!0){const a=new Map;for(const o of t){const s=la(o);if(!s)continue;const r=o.actor+"\0"+o.action+"\0"+s;(a.get(r)||a.set(r,[]).get(r)).push(o)}return a.size?`<div class="sm-probs">${[...a.values()].sort((o,s)=>s.length-o.length||s[0].ts-o[0].ts).slice(0,e).map(o=>{const s=o[0],r=typeof s.raw.actor_id=="string"?s.raw.actor_id:null,l=Wa(da(s)),c=la(s)==="refused"?"Refused":"Did not work",d=n?Yt(s.actor,30,"",r):`<span class="sm-prob-i">${GP[yr(s)]||ve.x}</span>`;return`<button type="button" class="sm-prob" data-prob="${C(s.actor)}" title="${C(n?`Show ${s.actor}'s problems in the timeline`:"Show its problems in the timeline")}">${d}<span class="s">${n?`<b>${x(s.actor)}</b> `:""}${x(n?l:l.charAt(0).toUpperCase()+l.slice(1))}</span><span class="m">${c} · ${x(Qx(s.ts))}</span><span class="n">${o.length>1?o.length+"×":""}</span></button>`}).join("")}</div>`:'<div class="sm-card-b"><div class="ax-bempty ok">No problems in this range</div></div>'}function QP(t,e,n=20){const a=Date.now()/1e3,i=Number.isFinite(e.until)?Math.min(e.until,a):a,o=e.since>0?e.since:t.length?Math.min(...t.map(c=>c.ts)):i-86400,s=Math.max(60,i-o),r=new Array(n).fill(0);t.forEach(c=>{const d=Math.min(n-1,Math.max(0,Math.floor((c.ts-o)/s*n)));r[d]++});const l=Math.max(1,...r);return`<span class="sm-spark" aria-hidden="true">${r.map(c=>`<i style="height:${c?Math.max(14,Math.round(c/l*100)):8}%"${c?"":' class="z"'}></i>`).join("")}</span>`}function eI(t){return t.disabled?{cls:"off",word:"Turned off"}:t.cls==="active"?{cls:"active",word:"Active"}:t.cls==="recent"?{cls:"recent",word:"Recent"}:t.cls==="removed"?{cls:"removed",word:"Removed"}:t.cls==="people"?{cls:"people",word:/^(gateway|system|memora|memora-cli)$/i.test(t.name)?"Server":"Person"}:{cls:"idle",word:"Idle"}}function tI(t){if(t.last){const e=Wa(da(t.last));return e.charAt(0).toUpperCase()+e.slice(1)}return t.lastTs?"Nothing in this range":"No activity yet"}function nI(t,e,n,a){if(!t.length)return'<div class="sm-card-b"><div class="ax-bempty">No agents yet</div></div>';const i='<div class="sm-ag sm-ag-h" aria-hidden="true"><span></span><span>Agent</span><span>Last action</span><span class="r">Actions</span><span class="r">Problems</span><span>Over time</span><span></span></div>';let o="",s="";return t.slice(0,a).forEach(r=>{const l=r.cls==="removed"?"removed":r.cls==="people"?"people":"";l&&l!==s&&(o+=`<div class="sm-ag-g">${x(Zx.find(f=>f.id===r.cls).label)}</div>`),s=l;const c=e(r),d=eI(r),p=!!r.id&&r.cls!=="removed"&&r.cls!=="people",h=r.last?Qx(r.last.ts):r.lastTs?Qx(r.lastTs):"",u=p?`<a class="sm-ag${c.length?"":" dim"}" href="/agents/${C(encodeURIComponent(r.id))}/activity" data-kid="${C(r.id)}"`:`<button type="button" class="sm-ag${c.length?"":" dim"}" data-only="${C(r.name)}"`;o+=`${u} style="--ag:${An(r.name,r.id)}" aria-label="${C(`${r.name}, ${d.word}: ${Zt(c.length,"action")}. ${p?"Open its activity":"Show only its activity below"}`)}">
|
|
1942
1942
|
<span class="sm-ag-av">${Yt(r.name,36,r.cls==="active"?"live":"",r.id)}</span>
|
|
1943
1943
|
<span class="sm-ag-id"><b>${x(r.name)}</b><span class="sm-st ${d.cls}">${x(d.word)}${r.fails?`<em>${Zt(r.fails,"problem")}</em>`:""}</span></span>
|
|
1944
1944
|
<span class="sm-ag-last"><span class="t">${x(tI(r))}</span><small>${x(h)}</small></span>
|
|
@@ -2026,16 +2026,16 @@ button.ax-kpi:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
|
|
|
2026
2026
|
.at-ctl .lg-live{height:44px}
|
|
2027
2027
|
.at-ctl .cc-ibtn{width:44px;height:44px}
|
|
2028
2028
|
}
|
|
2029
|
-
`,mi=120,sf=2e3,
|
|
2030
|
-
<div class="ax-opts">${Zu.map(s=>qi("time",s.id,s.label,
|
|
2031
|
-
<div class="ax-range${
|
|
2032
|
-
<label><span>From</span><input type="date" data-date="from" value="${C(
|
|
2033
|
-
<label><span>To</span><input type="date" data-date="to" value="${C(
|
|
2029
|
+
`,mi=120,sf=2e3,We={time:"7d",from:"",to:"",cats:new Set,actions:new Set,status:new Set,q:""};let Xt=null,Mr=null,_n=null,qn=[],Ar=!0,tb=!1,rf=0,Ya=mi,Xd=sf,nb="",_s=!1,NM=!1,jl=!0;const lf=new Set;let Wi=!0;const Yl=new Y2,Kd=new Set;let ab=!1,cf=null,ib=null,gi=null,zM=!1,ob=null;function DM(t,e,n,a){uM(),Ue("at-css",rI),sb();const i=_n?.id===n.id;Xt=t,Mr=e,ob=a,_n={id:n.id,name:n.name,used:n.used},i||(qn=[],We.time="7d",We.from=We.to="",We.cats.clear(),We.actions.clear(),We.status.clear(),We.q="",Wi=!0,jl=!0,lf.clear(),nb=""),Ya=mi,Xd=sf,Yl.take(),Kd.clear(),Ar=!qn.length,fI(),Zd(!!qn.length)}function sb(){rf++,ZP(Xt?.querySelector("#adBody")||null),ib?.(),ib=null,gi&&document.body.contains(gi)&&gi.querySelector("[data-x]")?.click(),gi=null,Xt=null}function OM(){return!!Xt&&Xt.isConnected&&!Xt.closest(".hidden")}async function $M(t,e,n){const a=encodeURIComponent(t.name),[i,o]=await Promise.all([Oe(`/api/logs?range=${encodeURIComponent(e)}&actor=${a}&limit=${n}`).catch(()=>({events:[]})),Oe("/api/auth/events?limit=300").catch(()=>({events:[]}))]),s=(o.events||[]).filter(c=>{const d=c;return t.id&&d.actor_id===t.id||d.actor===t.name||d.user===t.name}),r=i.events||[];return{items:G2([...r.map(hx),...s.map(ux)]).filter(c=>c.actor===t.name||c.raw.actor_id===t.id),logged:r.length}}async function Zd(t,e=!1){if(!_n)return;const n=_n,a=++rf,i=Ju(We);t||(Ar=!0,Kn(!1));try{const o=await $M(n,i,Xd);if(a!==rf||_n!==n)return;const s=o.items,r=s.length?s[0].ts:0,l=qn.filter(c=>c.live&&c.ts>r-15&&!s.some(d=>d.action===c.action&&Math.abs(d.ts-c.ts)<15));if(t&&qn.length&&!e){const c=new Set(qn.map(d=>d.action+Math.round(d.ts)));s.forEach(d=>c.has(d.action+Math.round(d.ts))||Kd.add(d.id))}qn=[...l,...s],_s=o.logged>=Xd*.95,nb=i}catch(o){if(a!==rf)return;ye("Could not load activity: "+o.message,"err"),e&&(_s=!1)}Ar=!1,tb=!1,Kn(t)}function lI(t){if(!_n)return!1;const e=typeof t.raw.actor_id=="string"?t.raw.actor_id:null;return e?e===_n.id:t.actor===_n.name}function cI(t){if(!(!OM()||Ar||!lI(t))){if(!Wi){Yl.push(t),df();return}FM(t)}}function FM(t){Kd.add(t.id),wu(qn,t),!ab&&(ab=!0,setTimeout(()=>{ab=!1,Kn(!0)},400))}function df(){const t=Xt?.querySelector("#adLive");if(!t)return;t.setAttribute("aria-pressed",String(Wi)),t.innerHTML=Wi?'<span class="cc-dot ok"></span>Live':'<span class="cc-dot idle"></span>Paused',t.title=Wi?"Pause: new activity waits until you show it":"Resume: show new activity as it happens";const e=Xt.querySelector("#adNew");e&&(e.hidden=Wi||!Yl.length,e.textContent=`${Yl.length} new · Show`,e.setAttribute("aria-label",`Show ${Zt(Yl.length,"new action")}`))}function UM(){Wi=!0,Yl.take().forEach(FM),df()}function pf(t,e){if(t.echo||e!=="cats"&&(We.cats.size||We.actions.size)&&!We.cats.has(yr(t))&&!We.actions.has(t.action)||e!=="status"&&We.status.size&&!We.status.has(ka(t)))return!1;if(e!=="q"&&We.q){const n=dM(t);if(!We.q.toLowerCase().split(/\s+/).filter(Boolean).every(a=>n.includes(a)))return!1}return!0}function Jd(){return cM(We)}function Qd(){const t=Jd();return qn.filter(e=>e.ts>=t.since&&e.ts<t.until)}function rb(){return Qd().filter(t=>pf(t))}function lb(){return qn.length?qn[qn.length-1].ts:Date.now()/1e3}function dI(){return!!(We.q||We.cats.size||We.actions.size||We.status.size)}function pI(){return We.cats.size+We.actions.size+We.status.size}function hI(t){We.q=t;const e=Xt?.querySelector("#adQ");e&&e.value!==t&&(e.value=t,e.dispatchEvent(new Event("input")))}function cb(t=!1){if(We.cats.clear(),We.actions.clear(),We.status.clear(),hI(""),Ya=mi,t&&We.time!=="7d")return ep("7d");Kn(!1)}function ep(t,e="",n=""){We.time=t,We.from=e,We.to=n,Ya=mi,af(cf),Ju(We)!==nb?(Xd=sf,Zd(!1)):Kn(!1)}function uI(){const t=Qd(),e=Ts(t.filter(s=>pf(s,"status")),ka),n=t.filter(s=>pf(s,"cats")),a=Ts(n,yr),i=[...Ts(n,s=>s.action).entries()].sort((s,r)=>r[1]-s[1]);We.actions.forEach(s=>i.some(([r])=>r===s)||i.push([s,0]));const o=wr(Date.now()/1e3);return`<section class="ax-fg"><h3>Time</h3>
|
|
2030
|
+
<div class="ax-opts">${Zu.map(s=>qi("time",s.id,s.label,We.time===s.id)).join("")}</div>
|
|
2031
|
+
<div class="ax-range${We.time==="custom"?" on":""}">
|
|
2032
|
+
<label><span>From</span><input type="date" data-date="from" value="${C(We.from)}" max="${o}"></label>
|
|
2033
|
+
<label><span>To</span><input type="date" data-date="to" value="${C(We.to)}" max="${o}"></label>
|
|
2034
2034
|
</div></section>
|
|
2035
|
-
<section class="ax-fg"><h3>Result</h3><div class="ax-opts">${Ku.map(s=>qi("status",s.id,s.label,
|
|
2036
|
-
<section class="ax-fg"><h3>What</h3><div class="ax-opts">${Xu.filter(s=>a.get(s.id)||
|
|
2037
|
-
${i.length?`<details class="ax-acts"${
|
|
2038
|
-
<div class="ax-opts">${i.map(([s,r])=>qi("actions",s,mx(s),
|
|
2035
|
+
<section class="ax-fg"><h3>Result</h3><div class="ax-opts">${Ku.map(s=>qi("status",s.id,s.label,We.status.has(s.id),e.get(s.id)||0,`<span class="cc-dot ${s.id==="fail"?"err":s.id==="running"?"run":"ok"}"></span>`)).join("")}</div></section>
|
|
2036
|
+
<section class="ax-fg"><h3>What</h3><div class="ax-opts">${Xu.filter(s=>a.get(s.id)||We.cats.has(s.id)||s.id!=="other").map(s=>qi("cats",s.id,s.label,We.cats.has(s.id),a.get(s.id)||0,`<i class="sw" style="--c:${Gl[s.id]}"></i>`,s.hint)).join("")}</div>
|
|
2037
|
+
${i.length?`<details class="ax-acts"${We.actions.size?" open":""}><summary>Specific actions<span class="n">${i.length}</span></summary>
|
|
2038
|
+
<div class="ax-opts">${i.map(([s,r])=>qi("actions",s,mx(s),We.actions.has(s),r,"",s)).join("")}</div></details>`:""}</section>`}function tp(){if(!gi||!document.body.contains(gi)){gi=null;return}const t=gi.querySelector(".cc-drawer-b"),e=t.scrollTop,n=t.querySelector(".ax-acts")?.open;t.innerHTML=uI(),t.scrollTop=e;const a=t.querySelector(".ax-acts");a&&n&&(a.open=!0),t.querySelectorAll("[data-date]").forEach(r=>{r.onchange=()=>{let l=We.time==="custom"?We.from:"",c=We.time==="custom"?We.to:"";r.dataset.date==="from"?l=r.value:c=r.value,l&&c&&l>c&&([l,c]=[c,l]),ep(l||c?"custom":"7d",l,c),tp()}});const i=rb().length,o=gi.querySelector("[data-done]");o&&(o.textContent=`Show ${Zt(i,"action")}`);const s=gi.querySelector(".cc-drawer-h .s");s&&(s.textContent=`${_n?.name||""} · ${i} of ${Zt(Qd().length,"action")} match`)}function BM(){const t=Mu({title:"Filters",sub:" ",body:"",foot:'<button type="button" class="btn ghost" data-reset>Reset</button><span style="flex:1"></span><button type="button" class="btn primary" data-done>Show actions</button>'});t.classList.add("ax-sheet"),gi=t,tp(),t.onclick=e=>{const n=e.target.closest("[data-k],[data-reset],[data-done]");if(!n)return;if(n.hasAttribute("data-done")){t.querySelector("[data-x]")?.click();return}if(n.hasAttribute("data-reset")){cb(!0),tp();return}const a=n.dataset.k,i=n.dataset.v||"";a==="time"?ep(i):(a==="status"?Es(We.status,i):a==="cats"?Es(We.cats,i):a==="actions"&&Es(We.actions,i),Ya=mi,Kn(!1)),tp(),t.querySelector(`[data-k="${a}"][data-v="${window.CSS.escape(i)}"]`)?.focus({preventScroll:!0})}}function fI(){!Xt||!_n||(Xt.innerHTML=`<div class="at-none sm-card" id="adNone" hidden><span class="at-none-i">${ve.plug}</span><b>No activity yet</b>
|
|
2039
2039
|
<span>Once ${x(_n.name)} is connected, everything it reads, writes and searches shows up here, live.</span>
|
|
2040
2040
|
<button type="button" class="btn" data-setup>Open the setup guide</button></div>
|
|
2041
2041
|
<div class="at" id="adMain">
|
|
@@ -2052,12 +2052,12 @@ button.ax-kpi:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
|
|
|
2052
2052
|
</div>
|
|
2053
2053
|
<section class="tl at-tl" id="adTl" aria-labelledby="adTlH">
|
|
2054
2054
|
<div class="tl-h"><h2 id="adTlH">Timeline</h2><span class="sub">Everything ${x(_n.name)} did, newest first</span></div>
|
|
2055
|
-
${fM("ad",
|
|
2055
|
+
${fM("ad",We.q,"Search notes and actions")}
|
|
2056
2056
|
</section>
|
|
2057
|
-
</div>`,cf=yM(()=>
|
|
2057
|
+
</div>`,cf=yM(()=>We,t=>{t==="custom"?(af(cf),BM()):ep(t)}),Xt.querySelector("#adTime").replaceWith(cf.el),Xt.querySelector("[data-setup]").onclick=()=>ob?.setup(),mI(()=>ob?.top()||0),df(),Kn(!1))}function db(){const t=Xt?.querySelector("#adTl"),e=Mr;!t||!e||requestAnimationFrame(()=>{const n=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-60;e.scrollTo({top:Math.max(0,n),behavior:matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"})})}function mI(t){const e=Xt;mM(e,"ad",{query:i=>{We.q=i,Ya=mi,Kn(!1)},quick:i=>{Wl(i,We),Ya=mi,Kn(!1)},filters:BM,remove:i=>{const[o,...s]=i.split(":"),r=s.join(":");o==="cats"?We.cats.delete(r):o==="actions"?We.actions.delete(r):o==="status"&&We.status.delete(r),Ya=mi,Kn(!1)},clear:()=>cb(),compact:()=>{jl=!jl,Kn(!1)}}),e.querySelector("#adLive").onclick=()=>{Wi?Wi=!1:(UM(),Zd(!0)),df()},e.querySelector("#adNew").onclick=()=>{UM(),db()};const n=e.querySelector("#adMore");n.onclick=()=>pr(n,[{label:"Reload",desc:"Fetch its activity again from the server.",icon:ve.refresh,run:()=>{Zd(!1)}},{label:"See it among all activity",desc:"The Activity page, showing only this agent.",icon:ve.filter,run:()=>{try{sessionStorage.setItem("memora.activity.agent",_n?.name||"")}catch{}te.go("logs")}},{sep:!0,label:""},{label:"Export timeline as JSON",desc:"The actions the timeline shows, for scripts.",icon:ve.download,run:()=>of(rb(),"json",_n?.name)},{label:"Export timeline as CSV",desc:"The actions the timeline shows, for a spreadsheet.",icon:ve.download,run:()=>of(rb(),"csv",_n?.name)}],{title:_n?.name||"Activity"}),e.querySelector(".at").addEventListener("click",i=>{const o=i.target;if(o.closest("#adBody")){const r=o.closest("[data-pick]");if(!r)return;r.dataset.pick==="time:all"?ep("all"):cb();return}let s;if(s=o.closest("[data-f]")){const[r,...l]=s.dataset.f.split(":"),c=l.join(":");r==="actions"?(We.cats.clear(),We.status.clear(),We.actions=new Set([c])):r==="status"&&Wl("fail",We),Ya=mi,Kn(!1),db()}else o.closest("[data-prob]")?(Wl("fail",We),Ya=mi,Kn(!1),db()):(s=o.closest("[data-note]"))&&!o.closest(".act")&&te.openNote(s.dataset.note)});const a=e.querySelector("#adBody");if(Rl(a,i=>qn.find(o=>o.id===i),void 0,{onBurst:i=>{lf.delete(i)||lf.add(i),Kn(!0)},onUndo:i=>{tS(i).then(()=>Kn(!0))},agentPage:_n?.id}),Mr){const i=Mr,o=bM(e,"ad",i,t);i.addEventListener("scroll",o,{passive:!0}),ib=()=>i.removeEventListener("scroll",o)}zM||(zM=!0,document.addEventListener("keydown",i=>{if(i.key!=="/"||i.metaKey||i.ctrlKey||i.altKey||!OM()||i.target.closest("input,textarea,select,[contenteditable=true],.cc-drawer,.modal"))return;const s=Xt?.querySelector("#adQ");s&&(i.preventDefault(),s.focus(),s.select())}))}function gI(){const t=[];return ef(We)||(We.status.forEach(e=>t.push($o("status:"+e,Ku.find(n=>n.id===e).label,"","Result "))),We.cats.forEach(e=>t.push($o("cats:"+e,Xu.find(n=>n.id===e).label,`<i class="sw" style="--c:${Gl[e]}"></i>`)))),We.actions.forEach(e=>t.push($o("actions:"+e,mx(e),"",""))),t}function vI(t){const e=Date.now()/1e3,n=new Date;n.setHours(0,0,0,0);const a=n.getTime()/1e3,i=lb(),o=qn.filter(b=>!b.echo),s=Vd(o.filter(b=>b.ts>=a).length,a,i,_s),r=Vd(o.filter(b=>b.ts>=e-7*86400).length,e-7*86400,i,_s),l=t.filter(b=>ka(b)==="fail").length,c=LM(t),d=Jd(),p=t.length?t[t.length-1].ts:e,h=d.since>0?d.since:p,u=Number.isFinite(d.until)?Math.min(d.until,e):e,f=u-h<=2*86400,v=f?Math.max(1,Math.ceil((u-h)/3600-.01)):Math.max(1,Math.ceil((u-h)/86400-.01)),g=t.length/v;return`${We.time==="today"||We.time==="1h"?Hi(Wd(We),t.length,`${r} in the last 7 days`):Hi(Wd(We),t.length,`${s} today`)}
|
|
2058
2058
|
${Hi("Problems",l,t.length?`${Math.round(l/t.length*100)}% of ${Zt(t.length,"action")}`:"Nothing in this range",l>0,l?"status:fail":"")}
|
|
2059
2059
|
${Hi("Notes touched",c.n,c.top?`Most: ${c.top}`:"None in this range")}
|
|
2060
|
-
${Hi(f?"Per hour":"Per day",(g>=10?String(Math.round(g)):g.toFixed(1).replace(/\.0$/,""))+(_s&&i>h?"+":""),`Average over ${Zt(v,f?"hour":"day")}`)}`}function xI(){const t=Xt,e=o=>t.querySelector("#"+o);if(Ar&&!qn.length){e("adKpis").innerHTML=wM().repeat(4),e("adChart").innerHTML=At("100%",168),e("adTop").innerHTML=Sr(5),e("adProbs").innerHTML=`<div class="sm-card-b">${Sr(2)}</div>`,e("adNotes").innerHTML=`<div class="sm-card-b">${Sr(3)}</div>`;return}const n=Qd().filter(o=>!o.echo),a=Jd();e("adSpan").textContent=Zt(n.length,"action"),e("adKpis").innerHTML=vI(n),e("adChartH").textContent=n.length?_M(n,a):"Actions over time",e("adChartS").innerHTML=n.some(o=>ka(o)==="fail")?'<i class="ax-key"></i>problems':"",e("adChart").innerHTML=EM(n,a),e("adTop").innerHTML=TM(n,6);const i=n.filter(o=>ka(o)==="fail").length;e("adPrA").innerHTML=i?`<button type="button" class="sm-lnk" data-f="status:fail">Show all ${i} ${ve.arrow}</button>`:"",e("adProbs").innerHTML=RM(n,4,!1),e("adNotes").innerHTML=CM(n,6)}function bI(){const t=Mr;if(!t||!Xt||t.scrollTop<40)return()=>{};const e=Xt.querySelector("#adBar")?.offsetHeight||0,n=t.getBoundingClientRect().top+e;let a=null;for(const s of Xt.querySelectorAll("#adBody [data-act]"))if(s.getBoundingClientRect().bottom>n+40){a=s;break}if(!a)return()=>{};const i=a.dataset.act,o=a.getBoundingClientRect().top;return()=>{const s=Xt?.querySelector(`#adBody [data-act="${window.CSS.escape(i)}"]`);s&&(t.scrollTop+=s.getBoundingClientRect().top-o)}}function Kn(t=!0){const e=Xt?.querySelector("#adBody");if(!e||!_n)return;const n=!Ar&&!qn.length&&!_n.used;if(Xt.querySelector("#adNone").hidden=!n,Xt.querySelector("#adMain").hidden=n,n)return;const a=t?bI():()=>{};xI(),vM(Xt,"ad",ef(
|
|
2060
|
+
${Hi(f?"Per hour":"Per day",(g>=10?String(Math.round(g)):g.toFixed(1).replace(/\.0$/,""))+(_s&&i>h?"+":""),`Average over ${Zt(v,f?"hour":"day")}`)}`}function xI(){const t=Xt,e=o=>t.querySelector("#"+o);if(Ar&&!qn.length){e("adKpis").innerHTML=wM().repeat(4),e("adChart").innerHTML=At("100%",168),e("adTop").innerHTML=Sr(5),e("adProbs").innerHTML=`<div class="sm-card-b">${Sr(2)}</div>`,e("adNotes").innerHTML=`<div class="sm-card-b">${Sr(3)}</div>`;return}const n=Qd().filter(o=>!o.echo),a=Jd();e("adSpan").textContent=Zt(n.length,"action"),e("adKpis").innerHTML=vI(n),e("adChartH").textContent=n.length?_M(n,a):"Actions over time",e("adChartS").innerHTML=n.some(o=>ka(o)==="fail")?'<i class="ax-key"></i>problems':"",e("adChart").innerHTML=EM(n,a),e("adTop").innerHTML=TM(n,6);const i=n.filter(o=>ka(o)==="fail").length;e("adPrA").innerHTML=i?`<button type="button" class="sm-lnk" data-f="status:fail">Show all ${i} ${ve.arrow}</button>`:"",e("adProbs").innerHTML=RM(n,4,!1),e("adNotes").innerHTML=CM(n,6)}function bI(){const t=Mr;if(!t||!Xt||t.scrollTop<40)return()=>{};const e=Xt.querySelector("#adBar")?.offsetHeight||0,n=t.getBoundingClientRect().top+e;let a=null;for(const s of Xt.querySelectorAll("#adBody [data-act]"))if(s.getBoundingClientRect().bottom>n+40){a=s;break}if(!a)return()=>{};const i=a.dataset.act,o=a.getBoundingClientRect().top;return()=>{const s=Xt?.querySelector(`#adBody [data-act="${window.CSS.escape(i)}"]`);s&&(t.scrollTop+=s.getBoundingClientRect().top-o)}}function Kn(t=!0){const e=Xt?.querySelector("#adBody");if(!e||!_n)return;const n=!Ar&&!qn.length&&!_n.used;if(Xt.querySelector("#adNone").hidden=!n,Xt.querySelector("#adMain").hidden=n,n)return;const a=t?bI():()=>{};xI(),vM(Xt,"ad",ef(We)),gM(Xt,"ad",gI(),pI());const i=Xt.querySelector("#adSum");if(Ar&&!qn.length){i.innerHTML="<span>Loading…</span>",e.setAttribute("aria-busy","true"),e.innerHTML=kM();return}e.removeAttribute("aria-busy");const o=Qd(),s=o.filter(l=>pf(l)),r=_s&&lb()>Jd().since;i.innerHTML=xM({n:Vd(s.length,Jd().since,lb(),_s),unit:["action","actions"],note:Wd(We),fails:s.filter(l=>ka(l)==="fail").length,compact:jl}),NM=bu(s,jl).length>Ya,e.innerHTML=MM({rows:s,fresh:Kd,limit:Ya,compact:jl,open:lf,older:r,narrowed:dI(),none:!o.length,what:`What ${_n.name} reads, writes and searches shows up here as it happens.`}),a(),Kd.clear(),tp(),Mr&&AM(e,Mr,yI)}function yI(){if(!tb){if(NM){Ya+=mi,Kn(!0);return}_s&&(tb=!0,Xd+=sf,Zd(!0,!0))}}const HM="/api/ui/layout/agent-apps";let Cs={},hf=null;function wI(t=!1){return hf&&!t||(hf=Oe(HM).then(e=>{const n=e?.data?.apps;if(Cs={},n&&typeof n=="object")for(const[a,i]of Object.entries(n))typeof i=="string"&&(Cs[a]=i)}).catch(()=>{Cs={}})),hf}async function pb(t,e){if(!(!t||(Cs[t]||"")===e)){e?Cs[t]=e:delete Cs[t];try{await $n(HM,{method:"PUT",body:{data:{apps:Cs}}})}catch{}}}const kI=[[/claude[\s._-]*code|^cc$/,"claude-code"],[/claude[\s._-]*desktop/,"claude-desktop"],[/cursor/,"cursor"],[/vs[\s._-]*code|copilot/,"vscode"],[/codex/,"codex"],[/gemini/,"gemini"],[/windsurf|codeium|cascade/,"windsurf"],[/chat[\s._-]*gpt|openai/,"chatgpt"],[/claude|anthropic/,"claude-ai"]];function SI(...t){for(const e of t){const n=String(e||"").toLowerCase();if(n){for(const[a,i]of kI)if(a.test(n))return i}}return""}function MI(t,e){const n=Cs[t.id];return n?{id:n,guessed:!1}:{id:SI(e,t.name),guessed:!0}}const Xl=[{id:"balanced",label:"Balanced",desc:"Recalls before it answers and saves decisions, preferences and fixes. Never stores secrets. Fits most people.",full:`From now on, use Memora as your second brain: a shared, long-term memory that you and my other AI agents read and write through the Memora MCP server.
|
|
2061
2061
|
|
|
2062
2062
|
Recall
|
|
2063
2063
|
- At the start of a task, search_memory for the topic, project, person or error you are working on, then read_memory the most relevant notes before you answer.
|
|
@@ -2795,25 +2795,25 @@ export MEMORA_KEY=${n}`;case"cursor":return rp({mcpServers:{memora:{url:e,header
|
|
|
2795
2795
|
${Ql("ro",p==="ro","Can only read","Searches and reads notes. Any change it tries is refused.")}
|
|
2796
2796
|
${Ql("custom",p==="custom","Custom…","Pick exactly what it may do, tool by tool.")}
|
|
2797
2797
|
</div></div>
|
|
2798
|
-
<div class="cn-custom" id="cnCustom" hidden></div>`},
|
|
2798
|
+
<div class="cn-custom" id="cnCustom" hidden></div>`},ln=I=>{const U=a;return!U||I.oauth&&U.oauth?I.oauth?`<div class="cn-note"><span class="ic">${ve.check}</span><span class="tx"><b>No key needed.</b> ${x(I.label)} signs in with your Memora account and shows up as its own agent.</span></div>`:"":i.get(U.id)?"":U.oauth?`<div class="cn-note"><span class="ic">${ve.check}</span><span class="tx"><b>${x(U.name)} signed in with your Memora account.</b> The app holds its own key, so there is nothing to paste. To use ${x(I.label)} with a key, connect it as a new agent.</span></div>`:U.revealable?`<form class="cn-unlock" id="cnUnlock"><div class="hd"><span class="ic">${vi.lock}</span><span><b>Unlock ${x(U.name)}'s key first</b><small>It is kept locked on the server. Enter your Memora password and the buttons below put it in for you.</small></span></div>
|
|
2799
2799
|
<div class="row"><input class="ui-input" type="password" id="cnPw" autocomplete="current-password" placeholder="Your Memora password" aria-label="Your Memora password">
|
|
2800
2800
|
<button type="submit" class="btn primary">${vi.lock}Unlock key</button></div>
|
|
2801
2801
|
<p class="alt">Or <button type="button" class="cn-link" data-roll>make a new key instead</button>; the current one stops working.</p></form>`:`<div class="cn-unlock"><div class="hd"><span class="ic">${ve.key}</span><span><b>Make a new key for ${x(U.name)} first</b><small>Its key was shown only once, when it was made. A new key replaces it and the old one stops working at once.</small></span></div>
|
|
2802
|
-
<div class="row"><button type="button" class="btn primary" data-roll>${ve.key}Make a new key</button></div></div>`},
|
|
2802
|
+
<div class="row"><button type="button" class="btn primary" data-roll>${ve.key}Make a new key</button></div></div>`},cn=I=>{const U=a,Y=U?i.get(U.id):"";if(!U||!Y||I.oauth)return"";const pe=o.has(U.id),Ie=I.id==="http"?"Paste it into the app where it asks for a key.":"The button above already puts it in; copy it only if you need it somewhere else.";return`<div class="cn-key${pe?" once":""}">${Yt(U.name,32,"",U.id)}<span class="kt"><b>${x(U.name)}'s key${pe?" · shown once":""}</b><code class="${f?"full":""}">${x(f?Y:WI(Y))}</code><small>${Ie}${pe?` Anyone with it can use your notes as ${x(U.name)}.`:""}</small></span>
|
|
2803
2803
|
<span class="acts"><button type="button" class="btn sm" id="cnKeyEye" aria-pressed="${f}">${f?"Hide":"Show"}</button>
|
|
2804
2804
|
<button type="button" class="btn sm" id="cnKeyCopy">${ve.copy}Copy key</button></span></div>`},Ut=I=>I.method==="signin"||I.id==="http"?`<pre class="cc-code cn-pre">${x(Fo())}</pre><div class="cn-copy"><span>${I.oauth?"Paste it into "+x(I.label):"Your Memora address"}</span><button type="button" class="btn primary" data-primary>${ae(I)}</button></div>`:I.method==="deeplink"?`<div class="cn-act"><button type="button" class="btn primary" data-primary>${ae(I)}</button><button type="button" class="cn-link" data-alt>Copy setup instead</button></div>`:`<pre class="cc-code cn-pre" aria-label="${C(I.method==="command"?"The command":"The setup")}">${x(yf(I.id,Fo(),wb))}</pre><div class="cn-copy"><span>${y()?"The dots stand for the key; Copy puts it in.":"The dots stand for the key. Unlock it above first."}</span>
|
|
2805
2805
|
<button type="button" class="btn primary" data-primary>${ae(I)}</button></div>`,Jt=I=>{const U=Fo(),Y=Sb()!==location.origin?`<p>Apps use this address (set with <code>MEMORA_BASE_URL</code>), even though this page is open at ${x(location.host)}.</p>`:"",pe=I.method==="deeplink"||I.method==="copy"&&I.id!=="http"?`<h5>Setup${I.file?` · <code>${x(I.file)}</code>`:""}</h5><pre>${x(yf(I.id,U,wb))}</pre>`:I.file?`<h5>File</h5><p><code>${x(I.file)}</code></p>`:"",Ie=I.id==="http"?`<h5>Test it</h5><pre>${x(XI(U,wb))}</pre><p>A list of tools in the answer means the key works.</p>`:"";return`<details class="cn-tech"${b?" open":""}><summary>${vi.right}Technical details</summary><div>
|
|
2806
2806
|
<h5>Memora address (MCP endpoint)</h5><pre>${x(U)}</pre>${Y}${pe}${Ie}${I.tech?`<p>${I.tech}</p>`:""}</div></details>`},K=()=>{const I=w(),U=I.steps.map(Y=>`<li>${Y.includes("{action}")?Y.replace("{action}","")+Ut(I):Y}</li>`).join("");return`<h3 class="cn-h" tabindex="-1" data-autofocus>Connect ${x(I.label)}</h3>
|
|
2807
|
-
<div class="cn-meta">${Xa(I.label,22)}<span>${x(I.kind)} · ${x(I.how)}</span></div>${a?"":Rt()}${
|
|
2808
|
-
<ol class="cn-steps">${U}</ol>${
|
|
2807
|
+
<div class="cn-meta">${Xa(I.label,22)}<span>${x(I.kind)} · ${x(I.how)}</span></div>${a?"":Rt()}${ln(I)}
|
|
2808
|
+
<ol class="cn-steps">${U}</ol>${cn(I)}
|
|
2809
2809
|
<section class="cn-test" aria-label="Connection check"><p class="sr-only" role="status" aria-live="polite" data-say></p><div data-live="full"></div></section>
|
|
2810
|
-
${Jt(I)}`},
|
|
2810
|
+
${Jt(I)}`},dn=I=>`<aside class="cn-count" data-count aria-labelledby="cnCountH"><h4 id="cnCountH">Notes from ${x(I)}</h4>
|
|
2811
2811
|
<div class="nr"><span class="n" aria-hidden="true">0</span><p class="sub" role="status" aria-live="polite"></p></div><p class="wr"></p>
|
|
2812
2812
|
<ul aria-label="Notes it saved"></ul><p class="hint" hidden>No notes yet. Did you send the prompt? Sometimes the app asks before it uses Memora the first time: allow it.</p></aside>`,zt=()=>{const I=w(),U=R&&P?.name||a?.name||I.label,Y=v||(I.short?"short":"full"),pe=g,Ie=Y==="short"?pe.short:pe.full,W=I.short?"short":"full",_e=(Me,Pe)=>`<button type="button" role="tab" data-pk="${Me}" aria-selected="${Y===Me}" aria-controls="cnPrompt" tabindex="${Y===Me?0:-1}">${Pe}${W===Me?'<span class="rec">Recommended</span>':""}</button>`,fe=lA(I.id).map((Me,Pe)=>`<section class="cn-card${Me.recommended?" rec":""}" aria-labelledby="cnP${Pe}"><h4 id="cnP${Pe}">${x(Me.title)}${Me.recommended?'<span class="tag">Recommended</span>':""}</h4><blockquote>${x(Me.text)}</blockquote>
|
|
2813
2813
|
<div class="row"><button type="button" class="btn${Me.recommended?" primary":""}" data-prompt="${Pe}" aria-label="Copy: ${C(Me.title)}">${ve.copy}Copy</button></div></section>`).join("");return`<h3 class="cn-h" tabindex="-1" data-autofocus>Now ask ${x(U)} to save what it knows</h3>
|
|
2814
2814
|
<p class="cn-sub">Copy one of these and send it to ${x(I.label)} like a normal message. The notes it saves show up here as they arrive.</p>
|
|
2815
2815
|
<div class="cn-test mini" data-live="mini"></div>
|
|
2816
|
-
<div class="cn-fp"><div class="cn-cards">${fe}</div>${
|
|
2816
|
+
<div class="cn-fp"><div class="cn-cards">${fe}</div>${dn(U)}</div>
|
|
2817
2817
|
<details class="cn-more"${m?" open":""}><summary>${vi.right}<span>More instruction styles <small>· for every conversation</small></span></summary><div>
|
|
2818
2818
|
<p class="lead">Paste these once where ${x(I.label)} reads its standing instructions, so it uses Memora in every conversation, not only when asked.</p>
|
|
2819
2819
|
<div class="cn-where"><span class="ic">${vi.pin}</span><span><b class="k">Where to paste it</b>${I.rules}</span></div>
|
|
@@ -3140,7 +3140,7 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
3140
3140
|
<button type="button" class="cc-ibtn" data-h="more" aria-haspopup="menu" aria-label="More actions for ${C(n)}" title="More">${ve.more}</button></div>`,s&&t.querySelector("h1")?.focus({preventScroll:!0}),t.querySelectorAll("[data-h]").forEach(r=>{r.onclick=()=>{const l=r.dataset.h;if(l==="setup")return Bo("setup");if(l==="toggle")return void Mf(e);l==="more"&&bN(r,e)}}),document.title=`${n} · Agents · Memora`}function bN(t,e){const n=Ft(e);pr(t,[{label:"Rename & colour",desc:"Change how it shows up everywhere.",icon:Cb,run:()=>Bo("settings")},...e.revealable?[{label:"Show key",desc:"See its key again; asks for your password.",icon:Tf,run:()=>vA(e)}]:[],{label:"Make a new key",desc:"The current key stops working at once.",icon:ve.key,run:()=>gA(e,()=>Bo("setup"))},{label:"Activity",desc:"Its numbers, timeline and export.",icon:Rb,run:()=>Bo("activity")},{sep:!0,label:""},{label:"Delete",desc:"Remove the agent; its key stops working at once.",icon:dp,danger:!0,run:()=>_b(e,()=>Vi(""))}],{title:n,lead:Yt(n,30,"",e.id)})}function Bo(t){Te&&Vi(Te.id+(t==="overview"?"":"/"+t))}function yN(){const t=Te.root.querySelector("[role=tablist]"),e=Array.from(t.querySelectorAll("[role=tab]"));e.forEach((n,a)=>{n.onclick=()=>Bo(n.dataset.tab),n.onkeydown=i=>{let o=-1;i.key==="ArrowRight"?o=(a+1)%e.length:i.key==="ArrowLeft"?o=(a-1+e.length)%e.length:i.key==="Home"?o=0:i.key==="End"&&(o=e.length-1),!(o<0)&&(i.preventDefault(),e[o].focus(),Bo(e[o].dataset.tab))}})}function wN(t,e){if(!Te)return;Te.tab==="setup"&&t!=="setup"&&(Te.wizard?.destroy(),Te.wizard=null,Te.picking=!1),Te.tab=t,Te.perms=null,Te.root.classList.toggle("on-act",t==="activity");const n=Te.root.querySelectorAll("[role=tab]");if(!n.length)return Ef(!1);n.forEach(s=>{const r=s.dataset.tab===t;s.setAttribute("aria-selected",String(r)),s.tabIndex=r?0:-1});const a=Te.root.querySelector(`#apTab-${t}`);a?.scrollIntoView({block:"nearest",inline:"nearest"}),Te.root.querySelector("#apPanel")?.setAttribute("aria-labelledby",`apTab-${t}`);const i=Te.root.querySelector(".ap-tabs"),o=Te.root.closest(".view");i&&o&&i.getBoundingClientRect().top<=o.getBoundingClientRect().top+1&&(o.scrollTop=Math.max(0,i.offsetTop)),Cr(),Nb(),Te.root.querySelector("[role=tablist]")?.contains(document.activeElement)||a?.focus({preventScroll:!0})}function Nb(){const t=Te?.root.querySelector("#apPanel"),e=Ka();!t||!e||(Te.tab!=="activity"&&sb(),Te.tab==="overview"?TN(t,e):Te.tab==="setup"?_f(t,e):Te.tab==="activity"?_N(t,e):Te.tab==="access"?Ob(t,e):LN(t,e),Ps(t))}async function kN(t,e=!1){if(!Te)return;const n=Ka();if(!n||!e&&Te.range===t&&Te.events)return;const a=Te,i=++a.evSeq;a.range=t;const o=await $M({id:n.id,name:Ft(n)},t,t==="all"?3e3:1500).catch(()=>({items:[],logged:0}));Te!==a||i!==a.evSeq||(a.events=o.items.filter(s=>s.source!=="auth"||s.raw.actor_id===n.id),a.tab==="overview"&&Db())}function SN(t){const e=Ka();if(!e)return!1;const n=typeof t.raw.actor_id=="string"?t.raw.actor_id:null;return n?n===e.id:t.actor===Ft(e)}let zb=0;function MN(t){Te?.tab==="activity"&&cI(t),!(!Te||!Te.events||!SN(t))&&(Te.fresh.add(t.id),wu(Te.events,t),!zb&&(zb=window.setTimeout(()=>{zb=0,Te&&(Te.tab==="overview"&&Db(),Te.fresh.clear())},300)))}function AN(t,e=!1){const n=yr(t),a=la(t),i=da(t),o=n==="search"?t.paths.slice(0,2):[],s=t.running?'<span class="ap-ev-st run"><i></i>Working…</span>':a?`<span class="ap-ev-st fail"><i></i>${a==="refused"?"Refused":"Did not work"}</span>`:'<span class="ap-ev-st"></span>',r=$i(t.ts);return`<li class="ap-ev${a?" fail":""}${Te?.fresh.has(t.id)?" new":""}" role="button" tabindex="0" data-act="${C(t.id)}"
|
|
3141
3141
|
aria-label="${C(`${Wa(i)}, ${sa(t.ts)}`)}">
|
|
3142
3142
|
<span class="ap-ev-ic" style="--c:${Gl[n]}">${uN[n]}</span>
|
|
3143
|
-
<span class="ap-ev-m"><span class="ap-ev-s act-p cap">${i}</span>${o.map(l=>`<button type="button" class="ap-ev-p" data-note="${C(l)}" title="${C(l)}">${ve.note}<span>${x(
|
|
3143
|
+
<span class="ap-ev-m"><span class="ap-ev-s act-p cap">${i}</span>${o.map(l=>`<button type="button" class="ap-ev-p" data-note="${C(l)}" title="${C(l)}">${ve.note}<span>${x(pn(l))}</span></button>`).join("")}${t.paths.length>o.length&&o.length?`<span class="ap-ev-more">+${t.paths.length-o.length}</span>`:""}</span>${s}
|
|
3144
3144
|
<span class="ap-ev-t" title="${C(sa(t.ts))}">${e?`<span class="clk">${gx(t.ts)}</span>`:""}${r==="now"?"now":r+" ago"}</span></li>`}function SA(t){return Array.from({length:t},(e,n)=>`<div class="ap-sk">${At("28px",28)}${At(30+n*17%40+"%",12)}</div>`).join("")}function TN(t,e){const n=Ft(e),a=_r(e),i=lp(e),o=Uo(e),s=o.id?Gi(o.id):void 0,r=Sf(e),l=sp(r),c=Et.oauth.has(e.id),d=i?.last||0,p=r.scopes.map(f=>{const v=xf.find(g=>g.id===f);return`<span class="ap-chip${f==="admin"?" admin":""}" title="${C(v.label)}">${x(v.short)}</span>`}).join(""),h=a.st==="off"?`<div class="ap-ban off"><span class="ic">${Af}</span><span class="tx"><b>${x(n)} is turned off</b><small>Its key is refused until you turn it back on. Nothing is deleted.</small></span>
|
|
3145
3145
|
<button type="button" class="btn" data-o="toggle">${ve.check}Turn on</button></div>`:a.st==="never"?`<div class="ap-ban"><span class="ic">${ve.plug}</span><span class="tx"><b>No calls yet</b><small>${s?`Follow the ${x(s.label)} setup guide to connect it.`:"Pick its app, then follow the setup guide to connect it."}</small></span><button type="button" class="btn primary" data-o="setup">${ve.plug}Open the setup guide</button></div>`:"";t.innerHTML=`${h}
|
|
3146
3146
|
<div class="ap-stats">
|
|
@@ -3567,7 +3567,21 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
3567
3567
|
.mn-sug-act:hover{border-color:var(--accent-line,var(--line-strong));color:var(--fg);background:var(--hover)}
|
|
3568
3568
|
.mn-sug-act .i{width:14px;height:14px}
|
|
3569
3569
|
.mn-sug-act[data-amaze] .i{color:var(--accent)}
|
|
3570
|
-
|
|
3570
|
+
/* Fresh ideas at work: a sheen runs across the button and the cards wait as soft placeholders. */
|
|
3571
|
+
.mn-sug-act{position:relative;overflow:hidden;isolation:isolate}
|
|
3572
|
+
.mn-sug-act.busy{border-color:var(--accent-line,var(--accent));color:var(--fg);cursor:progress}
|
|
3573
|
+
.mn-sug-act.busy::after{content:"";position:absolute;inset:0;z-index:-1;
|
|
3574
|
+
background:linear-gradient(100deg,transparent 20%,color-mix(in srgb,var(--accent) 22%,transparent) 50%,transparent 80%);background-size:220% 100%;animation:mnSheen 1.3s ease-in-out infinite}
|
|
3575
|
+
.mn-sug-act.busy span{background:linear-gradient(90deg,var(--muted) 30%,var(--fg) 50%,var(--muted) 70%);background-size:200% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:mnShine 1.4s linear infinite}
|
|
3576
|
+
.mn-sug-act.busy .i{animation:mnTwinkle 1.4s ease-in-out infinite}
|
|
3577
|
+
@keyframes mnSheen{from{background-position:120% 0}to{background-position:-120% 0}}
|
|
3578
|
+
@keyframes mnTwinkle{0%,100%{transform:scale(1) rotate(0);opacity:1}50%{transform:scale(1.18) rotate(18deg);opacity:.7}}
|
|
3579
|
+
.mn-sugs.loading .mn-sug{position:relative;overflow:hidden;color:transparent;pointer-events:none;border-color:var(--line)}
|
|
3580
|
+
.mn-sugs.loading .mn-sug>*{visibility:hidden}
|
|
3581
|
+
.mn-sugs.loading .mn-sug::after{content:"";position:absolute;inset:0;
|
|
3582
|
+
background:linear-gradient(100deg,color-mix(in srgb,var(--fg) 4%,transparent) 30%,color-mix(in srgb,var(--accent) 14%,transparent) 50%,color-mix(in srgb,var(--fg) 4%,transparent) 70%);
|
|
3583
|
+
background-size:240% 100%;animation:mnSheen 1.4s ease-in-out infinite;animation-delay:calc(var(--i) * 90ms)}
|
|
3584
|
+
@media (prefers-reduced-motion:reduce){.mn-sug-act.busy::after,.mn-sug-act.busy span,.mn-sug-act.busy .i,.mn-sugs.loading .mn-sug::after{animation:none}}
|
|
3571
3585
|
.mn-sk-row{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px;margin-top:14px;font-size:12px;color:var(--muted)}
|
|
3572
3586
|
.mn-sk-row[hidden]{display:none}
|
|
3573
3587
|
.mn-sk-row>span{margin-right:2px}
|
|
@@ -3997,13 +4011,13 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
3997
4011
|
<h2>${this.o.compact?`Hi, I'm ${tt}`:`${tt} looks after your notes`}</h2>
|
|
3998
4012
|
<p>${o}</p>
|
|
3999
4013
|
${i?`<div class="mn-sugs" data-kind="${a}"></div>${a==="global"?`<div class="mn-sug-bar"><button type="button" class="mn-sug-act" data-amaze title="${tt} writes new suggestions from your recent notes (yours stay)">${V("sparkle")}<span>Fresh ideas</span></button><button type="button" class="mn-sug-act" data-own-sugs title="Your own suggestions, kept until you change them">${V("edit")}<span>Your suggestions</span></button></div><div class="mn-sk-row" hidden></div>`:""}`:e?`<div class="mn-setup"><b>Connect a model first</b><span>Add an OpenAI, Anthropic or OpenAI-compatible API key in Settings. The key stays sealed on your server.</span><button type="button" class="btn primary sm" data-setup>${V("settings")}<span>Set up ${tt}</span></button></div>`:""}
|
|
4000
|
-
</div>`,i&&this.fillSugs(a)}fillSugs(e,n=!1){const a=this.log.querySelector(".mn-sugs");if(!a)return;const i=[],o=l=>i.some(c=>c.t.toLowerCase()===l.toLowerCase());if(e==="global"&&Ho){for(const l of l0(Ho.own).slice(0,n?1:2))o(l)||i.push({t:l,k:"own"});for(const l of l0(Ho.ai).slice(0,n?3:2))!o(l)&&i.length<4&&i.push({t:l,k:"ai"})}for(const l of l0(Bz[e]))i.length<4&&!o(l)&&i.push({t:l,k:"base"});const s={own:"pin",ai:"sparkle",base:"chat"},r={own:"Yours",ai:"For you",base:""};a.innerHTML=i.map((l,c)=>`<button type="button" class="mn-sug k-${l.k}" style="--i:${c}" data-sug="${C(l.t)}">${V(s[l.k])}<span>${x(l.t)}${r[l.k]?`<em>${r[l.k]}</em>`:""}</span></button>`).join(""),e==="global"&&(Ho||cP().then(l=>{Ho=l,(l.own.length||l.ai.length)&&this.fillSugs(e)}).catch(()=>{}),u3().then(l=>{const c=this.log.querySelector(".mn-sk-row");!c||!l.length||(c.hidden=!1,c.innerHTML=`<span>Your skills</span>${l.slice(0,6).map(d=>`<button type="button" class="mn-sk-chip" data-skill="/${C(d.name)} " title="${C(d.description||d.path)}">/${x(d.name)}</button>`).join("")}`)}))}async amaze(e){e.disabled=!0,e.classList.add("busy");try{const
|
|
4014
|
+
</div>`,i&&this.fillSugs(a)}fillSugs(e,n=!1){const a=this.log.querySelector(".mn-sugs");if(!a)return;const i=[],o=l=>i.some(c=>c.t.toLowerCase()===l.toLowerCase());if(e==="global"&&Ho){for(const l of l0(Ho.own).slice(0,n?1:2))o(l)||i.push({t:l,k:"own"});for(const l of l0(Ho.ai).slice(0,n?3:2))!o(l)&&i.length<4&&i.push({t:l,k:"ai"})}for(const l of l0(Bz[e]))i.length<4&&!o(l)&&i.push({t:l,k:"base"});const s={own:"pin",ai:"sparkle",base:"chat"},r={own:"Yours",ai:"For you",base:""};a.innerHTML=i.map((l,c)=>`<button type="button" class="mn-sug k-${l.k}" style="--i:${c}" data-sug="${C(l.t)}">${V(s[l.k])}<span>${x(l.t)}${r[l.k]?`<em>${r[l.k]}</em>`:""}</span></button>`).join(""),e==="global"&&(Ho||cP().then(l=>{Ho=l,(l.own.length||l.ai.length)&&this.fillSugs(e)}).catch(()=>{}),u3().then(l=>{const c=this.log.querySelector(".mn-sk-row");!c||!l.length||(c.hidden=!1,c.innerHTML=`<span>Your skills</span>${l.slice(0,6).map(d=>`<button type="button" class="mn-sk-chip" data-skill="/${C(d.name)} " title="${C(d.description||d.path)}">/${x(d.name)}</button>`).join("")}`)}))}async amaze(e){e.disabled=!0,e.classList.add("busy");const n=e.querySelector("span");n.textContent="Finding ideas…",this.log.querySelector(".mn-sugs")?.classList.add("loading");try{const i=await pP();Ho={own:i.own,ai:i.ai},this.fillSugs("global",!0),i.fresh||ye(`${tt} could not write new ones just now. Check the model in Settings.`,"info")}catch(i){ye(i.message,"err")}finally{e.disabled=!1,e.classList.remove("busy"),n.textContent="Fresh ideas",this.log.querySelector(".mn-sugs")?.classList.remove("loading")}}editOwnSugs(){const e=re("div","mn-own-sugs",'<p>One per line. They show among the suggestions on a new chat, marked Yours, and stay until you change them.</p><textarea rows="8" placeholder="Summarise my meeting notes from this week What should I write about next?"></textarea>'),n=e.querySelector("textarea");n.value=(Ho?.own||[]).join(`
|
|
4001
4015
|
`),ue.open({title:"Your suggestions",body:e,actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Save",cls:"primary",run:async()=>{try{Ho={own:(await dP(n.value.split(`
|
|
4002
4016
|
`))).own,ai:Ho?.ai||[]},ue.close(),this.fillSugs("global"),ye("Suggestions saved","ok")}catch(a){ye(a.message,"err")}}}]}),window.setTimeout(()=>n.focus(),30)}renderAll(){if(xp(),this.log.innerHTML="",!this.messages.length){this.paintEmpty();return}let e=null,n={in:0,out:0,model:""},a=0;const i=()=>{e&&this.finishAct(e.querySelector(".mn-tb")),e&&this.footer(e,n.model,n.in,n.out),n={in:0,out:0,model:""}};for(const o of this.messages){if(o.role==="user"&&o.meta?.steer===!0&&e){e.querySelector(".mn-tb").append(re("div","mn-steer",`${V("enter")}<span>${x(o.content)}</span>`));continue}if(o.role==="user"){i(),e=null;const r=this.userBubble(o.content,o.created_at,o.meta?.attach||[]);r.dataset.mid=String(o.id),a=o.id,this.log.append(r);continue}if(o.role==="assistant"&&o.meta?.compact===!0){i(),e=null,this.log.append(this.compactNote(Number(o.meta.messages||0),o.content));continue}e||(e=this.turnEl(),a&&(e.dataset.uid=String(a)),this.log.append(e));const s=e.querySelector(".mn-tb");if(o.role==="assistant"){const r=o.meta||{};if(typeof r.model=="string"&&(n.model=r.model),n.in+=Number(r.input_tokens||0),n.out+=Number(r.output_tokens||0),typeof r.error=="string"&&s.append(this.errorCard(r.error)),typeof r.thinking=="string"&&r.thinking&&(this.thought(s,r.thinking),s.querySelector(".mn-act .mn-tools").append(re("span","mn-seg-end"))),o.content){const l=re("div","mn-md");l.innerHTML=Hf(o.content),Jb(l),l.dataset.raw=o.content,l.dataset.mid=String(o.id),s.append(l)}for(const l of o.tool_calls||[])l.name===Yf?s.append(g3({id:l.id,...Gz(l.arguments)||{question:"",options:[],allow_other:!0}},Vz(this.messages,l.id))):l.name!==oc&&this.toolCard(s,l.id,l.name,l.arguments)}else if(!(o.role==="tool"&&o.tool_name===Yf)){if(o.role==="tool"&&o.tool_name===oc)try{const r=JSON.parse(o.content).shown||[];r.length&&s.append(y3(r))}catch{}else if(o.role==="tool"){const r=s.querySelector(`.mn-tool[data-id="${CSS.escape(o.tool_call_id||"")}"]`),l=o.meta||{};r&&this.endTool(r,l.ok!==!1,String(l.summary||""),Number(l.ms||0),o.content)}}}i(),Jb(this.log),this.scrollEnd(!0),this.paintRail(),requestAnimationFrame(()=>this.log.querySelectorAll(".mn-car").forEach(wp))}compactNote(e,n,a=0){const i=re("details","mn-compact"),o=a?Math.max(1,Math.round((performance.now()-a)/1e3)):0;return i.innerHTML=`<summary title="${e?"Open to read the summary":""}"><span>${V("refresh")}${e?"Compacted":"Compacting…"}${o?`<em class="mn-compact-t">${o}s</em>`:""}</span></summary>${n?`<div class="mn-md mn-compact-b">${Hf(n)}</div>`:""}`,i}compactLive(){this.log.querySelector(".mn-compact.live")?.remove();const e=re("div","mn-compact live"),n=performance.now();e.dataset.t0=String(n),e.setAttribute("role","status"),e.innerHTML=`<div class="mn-compact-s"><span><i class="mn-compact-spin" aria-hidden="true"></i><b>Compacting conversation</b><em class="mn-compact-t">0s</em></span></div>
|
|
4003
4017
|
<p class="mn-compact-why">The chat filled ${tt}'s memory for this model, so the older messages are being folded into a summary. The reply continues right after.</p>`;const a=window.setInterval(()=>{if(!e.isConnected)return window.clearInterval(a);e.querySelector(".mn-compact-t").textContent=`${Math.round((performance.now()-n)/1e3)}s`},1e3);return e}userBubble(e,n,a=[]){const i=re("div","mn-u"),o=a.length?`<div class="mn-u-att">${c0(a.map(s=>s.kind==="image"?`<button type="button" class="mn-u-img" data-img="${C(s.path)}" title="${C(s.title)}" aria-label="${C("Image "+s.title)}"><img alt="" loading="lazy" src="/api/assistant/uploads/${C(s.path)}" onerror="this.parentElement.classList.add('gone')"><span>${x(s.title)}</span></button>`:`<span class="mn-att-c sm"${s.kind==="note"?` data-note="${C(s.path)}" role="button" tabindex="0"`:""} title="${C(s.path||"All notes")}">${V(s.kind==="note"?"note":"folder")}<span>${x(s.title)}</span></span>`).join(""))}</div>`:"";return i.innerHTML=`${o}<div class="mn-ub">${x(e)}</div><div class="mn-u-act">${n?`<time title="${C(new Date(n*1e3).toLocaleString())}">${x(kn(n))}</time>`:""}<span class="mn-u-btns"><button type="button" class="mn-ibtn" data-copy-u title="Copy the message" aria-label="Copy the message">${V("copy")}</button><button type="button" class="mn-ibtn" data-retry title="Try again: send this message again" aria-label="Try again">${V("refresh")}</button></span></div>`,i}turnEl(){return re("div","mn-turn",`<div class="mn-av" aria-hidden="true">${bp("sm")}</div><div class="mn-tb"></div>`)}errorCard(e){const n=Yz(e),a=v3(e),i=a&&a!==n.text?a:"";return re("div","mn-err",`${V("alert")}<span class="mn-err-t">${x(n.text)}</span><span class="mn-err-a"><button type="button" class="btn sm" data-retry>${V("refresh")}<span>Try again</span></button>${n.setup?'<button type="button" class="btn ghost sm" data-setup>Open settings</button>':""}</span>${i?`<details class="mn-err-d"><summary>Show the full error</summary><pre>${x(i)}</pre></details>`:""}`)}act(e){let n=e.querySelector(":scope > .mn-act");return n||(n=re("details","mn-act live"),n.innerHTML=`<summary><span class="mn-act-ic"><i class="mn-spin"></i></span><span class="mn-act-t"><b>Working</b><small></small></span>${V("chev","i mn-act-chev")}</summary><div class="mn-act-b"><div class="mn-tools"></div><div class="mn-act-notes"></div></div>`,e.prepend(n),ic.set(n,{steps:0,ms:0,failed:0,read:new Set,changed:new Set,thought:!1})),n}finishAct(e,n){const a=e.querySelector(":scope > .mn-act"),i=a&&ic.get(a);if(!a||!i)return;a.classList.remove("live");const o=Array.from(i.changed),s=Array.from(i.read).filter(h=>!i.changed.has(h)),r=n??i.ms,l=o.length?`Changed ${o.length} note${o.length===1?"":"s"}`:s.length?`Looked at ${s.length} note${s.length===1?"":"s"}`:i.steps?`Used ${i.steps} tool${i.steps===1?"":"s"}`:"Thought it through",c=[i.steps?`${i.steps} step${i.steps===1?"":"s"}`:i.thought?"thinking":"",s.length?`read ${s.length}`:"",o.length?`changed ${o.length}`:"",i.failed?`${i.failed} failed`:"",r?r<1e3?`${r} ms`:`${(r/1e3).toFixed(1)} s`:""].filter(Boolean).join(" · ");a.querySelector(".mn-act-ic").innerHTML=V(i.failed&&!o.length&&!s.length?"alert":"check"),a.querySelector(".mn-act-t").innerHTML=`<b>${x(l)}</b><small>${x(c)}</small>`,a.classList.toggle("bad",i.failed>0);const d=(h,u)=>{const f=Is(h)||h;return`<span class="mn-att-c sm${u?" w":""}" data-note="${C(f)}" role="button" tabindex="0" title="${C(f)}">${V(u?"edit":"note")}<span>${x(lt(f)||f.split("/").pop().replace(/\.md$/i,""))}</span></span>`},p=a.querySelector(".mn-act-notes");p.innerHTML=o.length||s.length?`${o.length?`<div><b>Changed</b>${o.map(h=>d(h,!0)).join("")}</div>`:""}${s.length?`<div><b>Read</b>${s.slice(0,24).map(h=>d(h,!1)).join("")}${s.length>24?`<small>+${s.length-24} more</small>`:""}</div>`:""}`:""}thought(e,n){const a=this.act(e),i=a.querySelector(".mn-tools");let o=i.lastElementChild;(!o||!o.classList.contains("mn-thought"))&&(o=re("div","mn-thought",'<div class="mn-thought-t"></div>'),i.append(o));const s=o.querySelector(".mn-thought-t");s.textContent=(s.textContent||"")+n;const r=ic.get(a);r.thought=!0;const l=a.querySelector(".mn-act-t small");if(l&&a.classList.contains("live")){const c=(s.textContent||"").trim().split(/\n+/);l.textContent=c[c.length-1].slice(-140),a.querySelector(".mn-act-t b").textContent="Thinking"}}toolCard(e,n,a,i){const o=this.act(e),s=o.querySelector(".mn-act-t b");s&&o.classList.contains("live")&&(s.textContent="Working");const r=o.querySelector(".mn-tools"),l=ic.get(o);l.steps++;for(const h of f3(i))(yp(a)?l.changed:l.read).add(h);const c=o.querySelector(".mn-act-t small");c&&o.classList.contains("live")&&(c.textContent=`${s0(a)}${r0(i)?" "+r0(i):""}…`);const d=re("details","mn-tool run"+(yp(a)?" w":""));d.dataset.id=n;const p=r0(i);return d.innerHTML=`<summary><span class="mn-tool-ic">${V(yp(a)?"edit":"search")}</span><span class="mn-tool-t"><b>${x(s0(a))}</b>${p?`<small>${x(p)}</small>`:""}</span><span class="mn-tool-s"><i class="mn-spin"></i></span>${V("chev","i mn-tool-chev")}</summary>
|
|
4004
4018
|
<div class="mn-tool-b"><div class="mn-tool-k">${x(a)}</div><pre>${x(h3(i,1200))}</pre></div>`,r.append(d),d}endTool(e,n,a,i,o){e.classList.remove("run"),e.classList.add(n?"ok":"err");const s=e.closest(".mn-act"),r=s&&ic.get(s);r&&(r.ms+=i,n||r.failed++);const l=e.querySelector(".mn-tool-s"),c=[a,i?i<1e3?`${i} ms`:`${(i/1e3).toFixed(1)} s`:""].filter(Boolean).join(" · ");l.innerHTML=`${V(n?"check":"alert")}<span>${x(c||(n?"Done":"Failed"))}</span>`,o&&e.querySelector(".mn-tool-b").insertAdjacentHTML("beforeend",`<div class="mn-tool-k">Result</div><pre>${x(h3(o))}</pre>`)}footer(e,n,a,i){const o=e.querySelector(".mn-tb");o.querySelector(".mn-foot")?.remove(),o.querySelector(":scope > .mn-rel")?.remove();const s=Wz(o);s&&(o.insertAdjacentHTML("beforeend",s),requestAnimationFrame(()=>o.querySelectorAll(":scope > .mn-rel .mn-car").forEach(wp)));const r=Array.from(o.querySelectorAll(".mn-md")).map(d=>d.dataset.raw||"").join(`
|
|
4005
4019
|
|
|
4006
|
-
`).trim(),l=[n?Hx(za(),n):"",a||i?`${Ui(a)} in · ${Ui(i)} out`:""].filter(Boolean),c=re("div","mn-foot",`<span class="mn-foot-a">${r?`<button type="button" class="mn-ibtn" data-copy title="Copy the reply" aria-label="Copy the reply">${V("copy")}</button>`:""}<button type="button" class="mn-ibtn" data-regen title="Regenerate this reply" aria-label="Regenerate this reply">${V("refresh")}</button></span>${l.length?`<span class="mn-foot-m">${l.map(d=>`<span>${x(d)}</span>`).join("<i></i>")}</span>`:""}`);r&&(c.dataset.raw=r),o.append(c)}scrollEnd(e=!1){const n=this.log.scrollHeight-this.log.scrollTop-this.log.clientHeight;e||n<140?this.log.scrollTop=this.log.scrollHeight:this.paintDown(n)}paintDown(e){const n=e>220;this.downBtn.classList.toggle("on",n),this.downBtn.tabIndex=n?0:-1}onLogClick(e){const n=e.target,a=n.closest("[data-skill]");if(a){this.prefill(a.dataset.skill||"");return}const i=n.closest("[data-amaze]");if(i){this.amaze(i);return}if(n.closest("[data-own-sugs]")){this.editOwnSugs();return}const o=n.closest("[data-sug]");if(o){this.prefill(o.dataset.sug||"",!0);return}if(n.closest("[data-setup]")){zr();return}const s=n.closest(".mn-md a[href]");if(s&&!s.dataset.note){const m=s.getAttribute("href")||"",b=/^\/docs(?:\/([^#?]+))?(?:#(.+))?$/.exec(m);if(b){e.preventDefault(),bd(decodeURIComponent(b[1]||""),decodeURIComponent(b[2]||""));return}if(/^https?:\/\//i.test(m)){e.preventDefault(),window.open(m,"_blank","noopener");return}}const r=n.closest("[data-note]");if(r){e.preventDefault(),te.openNote(r.dataset.note);return}const l=n.closest("[data-ask-opt]");if(l&&!this.busy){const m=l.closest(".mn-ask");if(m.classList.contains("done"))return;const b=m.dataset.ask;if(l.dataset.askOpt==="other"){const k=m.querySelector(".mn-ask-f");k.hidden=!1,l.classList.add("on"),k.querySelector("input").focus();return}m.classList.add("done"),l.classList.add("on"),this.send(l.dataset.label||l.textContent||"",{to:b,approve:l.dataset.approve==="1"});return}const c=n.closest("[data-car]");if(c){const m=c.closest(".mn-car")?.querySelector(".mn-car-row");m?.scrollBy({left:(c.dataset.car==="l"?-1:1)*m.clientWidth*.8,behavior:"smooth"});return}const d=n.closest("[data-img]");if(d){const m=Array.from(d.closest(".mn-car-row")?.querySelectorAll("[data-img]:not(.gone)")||[d]),b=m.map(k=>({src:`/api/assistant/uploads/${k.dataset.img}`,caption:k.title}));up(`/api/assistant/uploads/${d.dataset.img}`,d.title,b,Math.max(0,m.indexOf(d)));return}const p=n.closest("[data-card]");if(p){m3(p.dataset.card||"",p.dataset.path||"");return}const h=n.closest(".mn-ub");if(h&&matchMedia("(hover: none)").matches){const m=h.closest(".mn-u"),b=!m.classList.contains("show-act");this.log.querySelectorAll(".mn-u.show-act").forEach(k=>k.classList.remove("show-act")),m.classList.toggle("show-act",b);return}const u=n.closest("[data-regen],[data-retry]");if(u){const m=u.closest(".mn-u");let b=Number(m?.dataset.mid||u.closest(".mn-turn")?.dataset.uid||0);b||(b=[...this.messages].reverse().find(k=>k.role==="user")?.id||0),this.rerun(b);return}const f=n.closest("[data-copy-u]");if(f){const m=f.closest(".mn-u")?.querySelector(".mn-ub")?.textContent||"";navigator.clipboard?.writeText(m).then(()=>ye("Message copied","ok"),()=>ye("Could not copy","err"));return}const v=n.closest("[data-copy]");if(v){const m=v.closest(".mn-foot")?.dataset.raw||"";navigator.clipboard?.writeText(m).then(()=>ye("Reply copied","ok"),()=>ye("Could not copy","err"));return}const g=n.closest("[data-copy-code]");if(g){const m=g.closest(".dc-code")?.querySelector("pre")?.textContent||"";navigator.clipboard?.writeText(m).then(()=>{g.textContent="Copied",window.setTimeout(()=>g.textContent="Copy",1500)})}}stop(){this.busy&&(this.halted=!0),this.busy&&this.session&&gP(this.session.id).catch(()=>{}),this.ctrl?.abort(),this.ctrl=null}reconnect(e){const n=()=>{document.hidden||!navigator.onLine||(document.removeEventListener("visibilitychange",n),window.removeEventListener("online",n),this.session?.id===e&&!this.ctrl&&this.open(e))};document.addEventListener("visibilitychange",n),window.addEventListener("online",n),window.setTimeout(n,600)}detach(){this.ctrl&&(this.run++,this.ctrl.abort(),this.ctrl=null,this.setBusy(!1))}setBusy(e){this.busy=e,this.o.onBusy?.(e),this.el.classList.toggle("busy",e),this.paintOpen(),this.paintQueue(),this.paintSend()}paintSend(){const e=this.busy&&!this.input.value.trim(),n=this.busy&&!e;this.sendBtn.innerHTML=V(e?"stop":"send"),this.sendBtn.classList.toggle("queue",n);const a=e?"Stop":n?"Add to the queue (Enter) · Ctrl+Enter steers this reply now":"Send (Enter)";this.sendBtn.title=a,this.sendBtn.setAttribute("aria-label",e?"Stop":n?"Add to the queue":"Send")}async send(e,n){const a=e.trim();if(!a||this.busy)return;const i=za()??await $l().catch(()=>null);if(!i||!No(i).length){ye(`Connect a model for ${tt} first`,"err"),zr();return}this.setBusy(!0);try{this.session||(this.model||(this.model=this.select?.value||Ul(i)),this.session=(await iP(this.newScope(),this.model,this.fleetingOn)).session,this.log.innerHTML="",this.o.onChange?.(this.session))}catch(r){this.setBusy(!1),ye(r.message,"err");return}const o=this.attach.slice();this.attach=[],this.paintAtt(),this.input.value="",this.grow(),this.log.querySelector(".mn-hello")?.remove(),this.log.append(this.userBubble(a,void 0,o)),this.paintRail(),requestAnimationFrame(()=>this.log.querySelectorAll(".mn-u:last-of-type .mn-car, .mn-car:not([data-wired])").forEach(wp));const s=this.session.id;n||this.log.querySelectorAll(".mn-ask:not(.done)").forEach(jz),await this.stream((r,l)=>fP(s,a,this.model||void 0,o,r,l,n))}async rerun(e){if(this.busy||!this.session||!e||this.messages.some(o=>o.role==="user"&&o.id>e)&&!await new Promise(s=>{ue.open({title:"Run this message again?",body:"<p>The messages that came after it in this chat are replaced by the new reply.</p>",actions:[{label:"Cancel",cls:"ghost",run:()=>(ue.close(),s(!1))},{label:"Run again",cls:"primary",run:()=>(ue.close(),s(!0))}]})}))return;const a=this.log.querySelector(`.mn-u[data-mid="${e}"]`);if(!a){ye("Open the chat again to run that message again","warn");return}for(;a.nextSibling;)a.nextSibling.remove();this.messages=this.messages.filter(o=>o.id<=e),this.setBusy(!0);const i=this.session.id;this.paintRail(),await this.stream((o,s)=>xP(i,e,this.model||void 0,o,s),e)}async stream(e,n=0,a=!1){const i=++this.run;let o=!1;const s=performance.now(),r=this.turnEl();r.classList.add("live"),n&&(r.dataset.uid=String(n));const l=r.querySelector(".mn-tb");l.innerHTML='<div class="mn-think"><i></i><i></i><i></i><span>Thinking</span></div>',this.log.append(r),this.scrollEnd(!0);let c=null,d="",p=0,h=!1,u="";const f=()=>{p=0,c&&(c.innerHTML=Hf(d,!0)+'<span class="mn-caret"></span>'),this.scrollEnd()},v=(k,y="Thinking")=>{let w=l.querySelector(".mn-think");k?(w||(w=re("div","mn-think","<i></i><i></i><i></i><span></span>"),l.append(w)),w.querySelector("span").textContent=y):w?.remove()},g=()=>{c&&(c.innerHTML=Hf(d),c.dataset.raw=d,Jb(c,!0)),c=null,d=""};this.ctrl=new AbortController;const m=this.session.id;let b=!1;try{await e(this.ctrl.signal,k=>{switch(o=!0,k.type){case"start":u=k.model,this.setContext(k.context);break;case"ask":g(),v(!1),l.append(g3(k,null)),this.scrollEnd();break;case"steered":g(),l.append(re("div","mn-steer",`${V("enter")}<span>${x(k.text)}</span>`)),this.scrollEnd();break;case"compacting":v(!1),r.before(this.compactLive()),this.scrollEnd();break;case"compacted":{const y=this.log.querySelector(".mn-compact.live"),w=this.compactNote(k.messages,"",y?Number(y.dataset.t0):0);y?y.replaceWith(w):r.before(w),v(!0);break}case"notice":l.insertAdjacentHTML("beforeend",`<div class="mn-notice">${V("info")}<span>${x(k.text)}</span></div>`);break;case"thinking":v(!1),this.thought(l,k.delta),this.scrollEnd();break;case"text":v(!1),c||(c=re("div","mn-md"),l.append(c)),d+=k.delta,p||(p=requestAnimationFrame(f));break;case"tool_start":{if(g(),v(!1),k.name===oc||k.name===Yf){v(!0);break}this.toolCard(l,k.id,k.name,k.args),v(!0,s0(k.name)+"…"),this.scrollEnd();break}case"tool_end":{if(k.name===Yf){v(!1);break}if(k.name===oc){k.shown?.length&&l.append(y3(k.shown)),this.scrollEnd();break}const y=l.querySelector(`.mn-tool[data-id="${CSS.escape(k.id)}"]`);y&&this.endTool(y,k.ok,k.summary,k.ms),k.ok&&yp(k.name)&&(h=!0),v(!0);break}case"error":g(),v(!1),l.append(this.errorCard(k.message));break;case"done":v(!1),g(),this.footer(r,u,k.input_tokens,k.output_tokens),this.setContext(k.context),this.session&&k.title&&(this.session={...this.session,title:k.title,updated_at:Date.now()/1e3});break}})}catch(k){const y=k;y.name==="AbortError"?i===this.run&&l.insertAdjacentHTML("beforeend",`<div class="mn-notice">${V("stop")}<span>Stopped.</span></div>`):Zz(y)?b=!0:l.append(this.errorCard(y.message))}finally{if(i!==this.run){p&&cancelAnimationFrame(p);return}if(b){p&&cancelAnimationFrame(p),this.ctrl=null,this.setBusy(!1),this.reconnect(m);return}if(a&&!o){r.remove(),this.ctrl=null,this.setBusy(!1),this.open(m);return}p&&cancelAnimationFrame(p),v(!1),g(),this.finishAct(l,Math.round(performance.now()-s)),r.classList.remove("live"),l.childElementCount||l.append(this.errorCard("No reply came back.")),this.ctrl=null,this.setBusy(!1),this.session&&(this.session={...this.session,messages:this.session.messages+1},this.o.onChange?.(this.session)),h&&te.loadCore();const k=this.halted;this.halted=!1,this.queue.length&&!k&&window.setTimeout(()=>this.sendQueued(),400),WS(m).then(y=>{if(this.session?.id===m){this.messages=y.messages,this.session=y.session,this.setContext(y.context),this.o.onMessages?.();const w=[...y.messages].reverse().find(E=>E.role==="user"),A=this.log.querySelectorAll(".mn-u"),_=A[A.length-1];w&&_&&!_.dataset.mid&&(_.dataset.mid=String(w.id)),w&&(r.dataset.uid=String(w.id));const S=y.messages.filter(E=>E.meta?.compact===!0).pop(),T=Array.from(this.log.querySelectorAll(".mn-compact")).pop();S&&T&&!T.querySelector(".mn-compact-b")&&T.replaceWith(this.compactNote(Number(S.meta?.messages||0),S.content))}}).catch(()=>{})}}}function m3(t,e){t==="note"?te.openNote(e):t==="image"?up(b3(e),e.split("/").pop()||""):t==="upload"?up(`/api/assistant/uploads/${e}`,""):(te.go("vault"),nt.selectFolder(t==="folder"?e:""))}const jf={changed:0,shown:1,attached:2,read:3};function qz(t){const e=new Map,n=i=>{const o=i.kind+":"+i.path,s=e.get(o);(!s||jf[i.role]<jf[s.role])&&e.set(o,i)},a=i=>lt(i)||i.split("/").pop().replace(/\.md$/i,"");for(const i of t)if(i.role==="user")for(const o of i.meta?.attach||[])o.kind==="image"?n({kind:"upload",path:o.path,title:o.title,role:"attached"}):o.kind==="note"?n({kind:"note",path:o.path,title:a(o.path),role:"attached"}):n({kind:o.path?"folder":"vault",path:o.path,title:o.title,role:"attached"});else if(i.role==="assistant")for(const o of i.tool_calls||[]){if(o.name===oc)continue;const s=yp(o.name)?"changed":"read";for(const r of f3(o.arguments)){const l=Is(r)||r;n({kind:"note",path:l,title:a(l),role:s})}}else if(i.role==="tool"&&i.tool_name===oc)try{for(const o of JSON.parse(i.content).shown||[])n({...o,title:o.kind==="note"?a(o.path):o.title,role:"shown"})}catch{}return[...e.values()].sort((i,o)=>jf[i.role]-jf[o.role])}function Wz(t){const e=t.querySelector(":scope > .mn-act"),n=e?ic.get(e):void 0,a=[],i=new Set,o=(c,d,p,h,u)=>{const f=c+":"+d;i.has(f)||(i.add(f),a.push({kind:c,path:d,title:p,ic:h,cls:u}))},s=c=>lt(c)||c.split("/").pop().replace(/\.md$/i,"");for(const c of n?.changed||[])o("note",Is(c)||c,s(Is(c)||c),"edit"," w");t.querySelectorAll(".mn-cards [data-card]").forEach(c=>{const d=c.dataset.card||"note";o(d,c.dataset.path||"",c.querySelector("b")?.textContent||"",d==="image"?"image":d==="folder"?"folder":d==="vault"?"vault":"note","")});for(const c of n?.read||[])o("note",Is(c)||c,s(Is(c)||c),"note","");if(!a.length)return"";const r=12,l=a.slice(0,r).map(c=>`<span class="mn-att-c sm${c.cls}" data-card="${C(c.kind)}" data-path="${C(c.path)}" role="button" tabindex="0" title="${C(c.path||c.title)}">${V(c.ic)}<span>${x(c.title)}</span></span>`).join("");return`<div class="mn-rel"><span class="mn-rel-h">Related</span>${c0(l+(a.length>r?`<small class="mn-rel-more">+${a.length-r}</small>`:""))}</div>`}const Yf="ask_owner";function Gz(t){const e=t||{},n=typeof e.question=="string"?e.question.trim():"",a=(Array.isArray(e.options)?e.options:[]).map(i=>i).filter(i=>typeof i.label=="string"&&i.label.trim()).slice(0,5).map(i=>({label:String(i.label).trim(),description:typeof i.description=="string"?i.description:null,approve:i.approve===!0}));return n&&a.length>=2?{question:n,options:a,allow_other:e.allow_other!==!1}:null}function Vz(t,e){const n=t.find(i=>i.role==="user"&&i.meta?.answer?.to===e);if(n)return(n.meta?.answer).other?"":n.content;const a=t.findIndex(i=>i.role==="assistant"&&(i.tool_calls||[]).some(o=>o.id===e));return a>=0&&t.slice(a+1).some(i=>i.role==="user")?!1:null}function jz(t){t.classList.add("done","skipped"),t.querySelectorAll("button,input").forEach(e=>e.disabled=!0),t.querySelector(".mn-ask-f")?.setAttribute("hidden",""),t.querySelector(".mn-ask-q").insertAdjacentHTML("beforeend",'<em class="mn-ask-skip">Skipped</em>')}function g3(t,e){const n=e!==null,a=re("div","mn-ask"+(n?" done":"")+(e===!1?" skipped":""));a.dataset.ask=t.id;const i=n?" disabled":"";return a.innerHTML=`<div class="mn-ask-q">${V("help")}<span>${x(t.question)}</span>${e===!1?'<em class="mn-ask-skip">Skipped</em>':""}</div><div class="mn-ask-o">${t.options.map((o,s)=>`<button type="button" class="mn-ask-b${o.approve?" ok":""}${e===o.label?" on":""}" data-ask-opt="1" data-label="${C(o.label)}" data-approve="${o.approve?"1":""}"${i}><span class="mn-ask-n">${s+1}</span><span class="mn-ask-c"><b>${x(o.label)}</b>${o.description?`<small>${x(o.description)}</small>`:""}</span></button>`).join("")}${t.allow_other?`<button type="button" class="mn-ask-b other${e===""?" on":""}" data-ask-opt="other"${i}><span class="mn-ask-n">${V("edit")}</span><span class="mn-ask-c"><b>Other</b><small>Type your own answer</small></span></button><form class="mn-ask-f" hidden><input type="text" placeholder="Type your answer…" aria-label="Your answer" autocomplete="off"${i}><button type="submit" class="mn-ibtn" title="Send the answer (Enter)" aria-label="Send the answer"${i}>${V("enter")}</button></form>`:""}</div>`,a}function v3(t){const e=/<title[^>]*>([^<]*)<\/title>/i.exec(t)?.[1]?.trim();return t.replace(/<!doctype[\s\S]*?<\/html>/gi,e||"an HTML error page").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()}function Yz(t){const e={text:"The AI provider did not accept the key. Check it in Settings.",setup:!0},n={text:"The AI provider could not find this model or address. Check it in Settings.",setup:!0},a={text:"The AI provider is busy or out of quota. Try again in a moment.",setup:!1},i={text:"The AI provider is not answering right now. Try again in a moment.",setup:!1},o={text:"Could not reach the AI provider. Check the connection and try again.",setup:!1},s=Number(/answered (\d{3})/i.exec(t)?.[1]||0);if(s===401||s===403)return e;if(s===404)return n;if(s===429)return a;if(s>=500)return i;const r=v3(t).toLowerCase().slice(0,400),l=(...d)=>d.some(p=>r.includes(p));if(l("unauthori","forbidden","api key","invalid key"))return e;if(l("no such model","model_not_found","model not found"))return n;if(l("rate limit","quota","too many requests"))return a;if(l("overload","unavailable","bad gateway","gateway timeout"))return i;if(l("could not reach","timed out","timeout","failed to fetch","networkerror","connection refused","dns"))return o;if(!r.trim()||r.includes("no reply came back"))return{text:"No reply came back.",setup:!1};if(l("no provider","add a provider","no model"))return{text:t.trim(),setup:!0};const c=t.trim();return!s&&c.length<=160&&!/[{}<>]|\b\d{3}\b/.test(c)?{text:c.charAt(0).toUpperCase()+c.slice(1),setup:!1}:{text:"Something went wrong with this reply.",setup:!1}}const x3=4;function c0(t){return`<div class="mn-car"><button type="button" class="mn-car-a l" data-car="l" aria-label="Scroll left" tabindex="-1">${V("chev-left")}</button><div class="mn-car-row">${t}</div><button type="button" class="mn-car-a r" data-car="r" aria-label="Scroll right" tabindex="-1">${V("chev-right")}</button></div>`}function wp(t){const e=t.querySelector(".mn-car-row");if(!e)return;const n=e.scrollWidth-e.clientWidth;t.classList.toggle("more-l",e.scrollLeft>4),t.classList.toggle("more-r",n-e.scrollLeft>4),t.dataset.wired||(t.dataset.wired="1",e.addEventListener("scroll",()=>wp(t),{passive:!0}))}const oc="show_items",b3=t=>`/api/vault/file?path=${encodeURIComponent(t)}`;function y3(t){const e=re("div","mn-cards");return e.innerHTML=t.map(n=>{const a=n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"",i=n.kind==="vault"?"Every note":n.kind==="folder"?n.path?"Folder"+(a?` in ${a}`:""):"Folder":a||"Top level",o=n.kind==="note"&<(n.path)||n.title,s=n.kind==="image"?`<span class="mn-card-img"><img alt="" loading="lazy" src="${C(b3(n.path))}" onerror="this.parentElement.classList.add('broken')"></span>`:`<span class="mn-card-ic">${V(n.kind==="note"?"note":n.kind==="folder"?"folder":"vault")}</span>`;return`<button type="button" class="mn-card k-${n.kind}" data-card="${C(n.kind)}" data-path="${C(n.path)}" title="${C(n.kind==="vault"?"Open your notes":`Open ${n.path||"All notes"}`)}">${s}<span class="mn-card-t"><b>${x(o)}</b><small>${x(i)}</small></span>${V("chev","i mn-card-go")}</button>`}).join(""),e}function zr(){Cf("stMnemo"),te.go("settings")}function Xz(t,e=8){const n=re("div","mn-pick");n.innerHTML=`<label class="mn-pick-q">${V("search")}<input type="search" placeholder="Search notes" autocomplete="off" aria-label="Search notes"></label><div class="mn-pick-l" role="listbox" aria-multiselectable="true"></div>`;const a=n.querySelector("input"),i=n.querySelector(".mn-pick-l"),o=[],s=en().map(d=>({path:d.path,title:lt(d.path)||d.name,folder:d.folder})).sort((d,p)=>d.title.localeCompare(p.title));let r=null;const l=()=>{r&&(r.disabled=!o.length,r.textContent=o.length>1?`Attach ${o.length} notes`:"Attach")},c=()=>{const d=a.value.trim().toLowerCase(),p=s.filter(h=>!d||h.title.toLowerCase().includes(d)||h.path.toLowerCase().includes(d)).slice(0,60);i.innerHTML=p.length?p.map(h=>{const u=o.includes(h.path);return`<button type="button" class="mn-pick-i${u?" on":""}" role="option" aria-selected="${u}" data-p="${C(h.path)}">${V("note")}<span><b>${x(h.title)}</b><small>${x(h.folder||"Top level")}</small></span><i class="mn-pick-ck" aria-hidden="true">${V("check")}</i></button>`}).join(""):'<p class="mn-pick-none">No note matches.</p>'};a.oninput=c,i.onclick=d=>{const p=d.target.closest("[data-p]");if(!p)return;const h=p.dataset.p,u=o.indexOf(h);if(u>=0)o.splice(u,1);else if(o.length<e)o.push(h);else return ye(`Up to ${e} more this message`,"warn");p.classList.toggle("on",u<0),p.setAttribute("aria-selected",String(u<0)),l()},c(),ue.open({title:"Notes",body:n,actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Attach",cls:"primary",run:()=>{o.length&&(ue.close(),t(o))}}]}),r=document.querySelector(".modal-foot .btn.primary"),l(),window.setTimeout(()=>a.focus(),40)}function Kz(){return window.matchMedia("(hover: none) and (pointer: coarse)").matches}function Zz(t){return t.name==="TypeError"||/network|failed to fetch|load failed|connection|terminated|aborted/i.test(t.message||"")}let We=null,Pt=null,hn=[],Oa="",Dr=null,w3=0,d0=null,p0=null,h0=!1;function k3(t,e){d0=t,p0=e??null}function Jz(){Sp(!1)}async function Qz(){Ue("mnemo-css",Vf),Ue("mnemo-page-css",u8),Ue("vx-styles",ql);const t=H("#view-assistant");We||e8(),We.parentElement!==t&&t.replaceChildren(We),await Jf(),L3(),Ap();const e=d0,n=p0;d0=null,p0=null;const a=u0;u0=!1;const i=cL();if(i&&!e&&Pt.session?.id!==i){await m0(i),Zi(),$l(!0).catch(()=>{}),kp();return}i&&Pt.session?.id===i||(e?await m0(e):(e===""||a&&!Pt.working)&&Ns(),(a||n)&&rc(n?.view==="activity"),n?.scope&&Pt.attachScope(n.scope),n?.text&&Pt.prefill(n.text),Zi(),$l(!0).catch(()=>{}),window.matchMedia("(min-width: 761px)").matches&&Pt.focus(),kp())}function e8(){Nz(()=>Wn()),We=re("div","mnp"),We.innerHTML=`
|
|
4020
|
+
`).trim(),l=[n?Hx(za(),n):"",a||i?`${Ui(a)} in · ${Ui(i)} out`:""].filter(Boolean),c=re("div","mn-foot",`<span class="mn-foot-a">${r?`<button type="button" class="mn-ibtn" data-copy title="Copy the reply" aria-label="Copy the reply">${V("copy")}</button>`:""}<button type="button" class="mn-ibtn" data-regen title="Regenerate this reply" aria-label="Regenerate this reply">${V("refresh")}</button></span>${l.length?`<span class="mn-foot-m">${l.map(d=>`<span>${x(d)}</span>`).join("<i></i>")}</span>`:""}`);r&&(c.dataset.raw=r),o.append(c)}scrollEnd(e=!1){const n=this.log.scrollHeight-this.log.scrollTop-this.log.clientHeight;e||n<140?this.log.scrollTop=this.log.scrollHeight:this.paintDown(n)}paintDown(e){const n=e>220;this.downBtn.classList.toggle("on",n),this.downBtn.tabIndex=n?0:-1}onLogClick(e){const n=e.target,a=n.closest("[data-skill]");if(a){this.prefill(a.dataset.skill||"");return}const i=n.closest("[data-amaze]");if(i){this.amaze(i);return}if(n.closest("[data-own-sugs]")){this.editOwnSugs();return}const o=n.closest("[data-sug]");if(o){this.prefill(o.dataset.sug||"",!0);return}if(n.closest("[data-setup]")){zr();return}const s=n.closest(".mn-md a[href]");if(s&&!s.dataset.note){const m=s.getAttribute("href")||"",b=/^\/docs(?:\/([^#?]+))?(?:#(.+))?$/.exec(m);if(b){e.preventDefault(),bd(decodeURIComponent(b[1]||""),decodeURIComponent(b[2]||""));return}if(/^https?:\/\//i.test(m)){e.preventDefault(),window.open(m,"_blank","noopener");return}}const r=n.closest("[data-note]");if(r){e.preventDefault(),te.openNote(r.dataset.note);return}const l=n.closest("[data-ask-opt]");if(l&&!this.busy){const m=l.closest(".mn-ask");if(m.classList.contains("done"))return;const b=m.dataset.ask;if(l.dataset.askOpt==="other"){const k=m.querySelector(".mn-ask-f");k.hidden=!1,l.classList.add("on"),k.querySelector("input").focus();return}m.classList.add("done"),l.classList.add("on"),this.send(l.dataset.label||l.textContent||"",{to:b,approve:l.dataset.approve==="1"});return}const c=n.closest("[data-car]");if(c){const m=c.closest(".mn-car")?.querySelector(".mn-car-row");m?.scrollBy({left:(c.dataset.car==="l"?-1:1)*m.clientWidth*.8,behavior:"smooth"});return}const d=n.closest("[data-img]");if(d){const m=Array.from(d.closest(".mn-car-row")?.querySelectorAll("[data-img]:not(.gone)")||[d]),b=m.map(k=>({src:`/api/assistant/uploads/${k.dataset.img}`,caption:k.title}));up(`/api/assistant/uploads/${d.dataset.img}`,d.title,b,Math.max(0,m.indexOf(d)));return}const p=n.closest("[data-card]");if(p){m3(p.dataset.card||"",p.dataset.path||"");return}const h=n.closest(".mn-ub");if(h&&matchMedia("(hover: none)").matches){const m=h.closest(".mn-u"),b=!m.classList.contains("show-act");this.log.querySelectorAll(".mn-u.show-act").forEach(k=>k.classList.remove("show-act")),m.classList.toggle("show-act",b);return}const u=n.closest("[data-regen],[data-retry]");if(u){const m=u.closest(".mn-u");let b=Number(m?.dataset.mid||u.closest(".mn-turn")?.dataset.uid||0);b||(b=[...this.messages].reverse().find(k=>k.role==="user")?.id||0),this.rerun(b);return}const f=n.closest("[data-copy-u]");if(f){const m=f.closest(".mn-u")?.querySelector(".mn-ub")?.textContent||"";navigator.clipboard?.writeText(m).then(()=>ye("Message copied","ok"),()=>ye("Could not copy","err"));return}const v=n.closest("[data-copy]");if(v){const m=v.closest(".mn-foot")?.dataset.raw||"";navigator.clipboard?.writeText(m).then(()=>ye("Reply copied","ok"),()=>ye("Could not copy","err"));return}const g=n.closest("[data-copy-code]");if(g){const m=g.closest(".dc-code")?.querySelector("pre")?.textContent||"";navigator.clipboard?.writeText(m).then(()=>{g.textContent="Copied",window.setTimeout(()=>g.textContent="Copy",1500)})}}stop(){this.busy&&(this.halted=!0),this.busy&&this.session&&gP(this.session.id).catch(()=>{}),this.ctrl?.abort(),this.ctrl=null}reconnect(e){const n=()=>{document.hidden||!navigator.onLine||(document.removeEventListener("visibilitychange",n),window.removeEventListener("online",n),this.session?.id===e&&!this.ctrl&&this.open(e))};document.addEventListener("visibilitychange",n),window.addEventListener("online",n),window.setTimeout(n,600)}detach(){this.ctrl&&(this.run++,this.ctrl.abort(),this.ctrl=null,this.setBusy(!1))}setBusy(e){this.busy=e,this.o.onBusy?.(e),this.el.classList.toggle("busy",e),this.paintOpen(),this.paintQueue(),this.paintSend()}paintSend(){const e=this.busy&&!this.input.value.trim(),n=this.busy&&!e;this.sendBtn.innerHTML=V(e?"stop":"send"),this.sendBtn.classList.toggle("queue",n);const a=e?"Stop":n?"Add to the queue (Enter) · Ctrl+Enter steers this reply now":"Send (Enter)";this.sendBtn.title=a,this.sendBtn.setAttribute("aria-label",e?"Stop":n?"Add to the queue":"Send")}async send(e,n){const a=e.trim();if(!a||this.busy)return;const i=za()??await $l().catch(()=>null);if(!i||!No(i).length){ye(`Connect a model for ${tt} first`,"err"),zr();return}this.setBusy(!0);try{this.session||(this.model||(this.model=this.select?.value||Ul(i)),this.session=(await iP(this.newScope(),this.model,this.fleetingOn)).session,this.log.innerHTML="",this.o.onChange?.(this.session))}catch(r){this.setBusy(!1),ye(r.message,"err");return}const o=this.attach.slice();this.attach=[],this.paintAtt(),this.input.value="",this.grow(),this.log.querySelector(".mn-hello")?.remove(),this.log.append(this.userBubble(a,void 0,o)),this.paintRail(),requestAnimationFrame(()=>this.log.querySelectorAll(".mn-u:last-of-type .mn-car, .mn-car:not([data-wired])").forEach(wp));const s=this.session.id;n||this.log.querySelectorAll(".mn-ask:not(.done)").forEach(jz),await this.stream((r,l)=>fP(s,a,this.model||void 0,o,r,l,n))}async rerun(e){if(this.busy||!this.session||!e||this.messages.some(o=>o.role==="user"&&o.id>e)&&!await new Promise(s=>{ue.open({title:"Run this message again?",body:"<p>The messages that came after it in this chat are replaced by the new reply.</p>",actions:[{label:"Cancel",cls:"ghost",run:()=>(ue.close(),s(!1))},{label:"Run again",cls:"primary",run:()=>(ue.close(),s(!0))}]})}))return;const a=this.log.querySelector(`.mn-u[data-mid="${e}"]`);if(!a){ye("Open the chat again to run that message again","warn");return}for(;a.nextSibling;)a.nextSibling.remove();this.messages=this.messages.filter(o=>o.id<=e),this.setBusy(!0);const i=this.session.id;this.paintRail(),await this.stream((o,s)=>xP(i,e,this.model||void 0,o,s),e)}async stream(e,n=0,a=!1){const i=++this.run;let o=!1;const s=performance.now(),r=this.turnEl();r.classList.add("live"),n&&(r.dataset.uid=String(n));const l=r.querySelector(".mn-tb");l.innerHTML='<div class="mn-think"><i></i><i></i><i></i><span>Thinking</span></div>',this.log.append(r),this.scrollEnd(!0);let c=null,d="",p=0,h=!1,u="";const f=()=>{p=0,c&&(c.innerHTML=Hf(d,!0)+'<span class="mn-caret"></span>'),this.scrollEnd()},v=(k,y="Thinking")=>{let w=l.querySelector(".mn-think");k?(w||(w=re("div","mn-think","<i></i><i></i><i></i><span></span>"),l.append(w)),w.querySelector("span").textContent=y):w?.remove()},g=()=>{c&&(c.innerHTML=Hf(d),c.dataset.raw=d,Jb(c,!0)),c=null,d=""};this.ctrl=new AbortController;const m=this.session.id;let b=!1;try{await e(this.ctrl.signal,k=>{switch(o=!0,k.type){case"start":u=k.model,this.setContext(k.context);break;case"ask":g(),v(!1),l.append(g3(k,null)),this.scrollEnd();break;case"steered":g(),l.append(re("div","mn-steer",`${V("enter")}<span>${x(k.text)}</span>`)),this.scrollEnd();break;case"compacting":v(!1),r.before(this.compactLive()),this.scrollEnd();break;case"compacted":{const y=this.log.querySelector(".mn-compact.live"),w=this.compactNote(k.messages,"",y?Number(y.dataset.t0):0);y?y.replaceWith(w):r.before(w),v(!0);break}case"notice":l.insertAdjacentHTML("beforeend",`<div class="mn-notice">${V("info")}<span>${x(k.text)}</span></div>`);break;case"thinking":v(!1),this.thought(l,k.delta),this.scrollEnd();break;case"text":v(!1),c||(c=re("div","mn-md"),l.append(c)),d+=k.delta,p||(p=requestAnimationFrame(f));break;case"tool_start":{if(g(),v(!1),k.name===oc||k.name===Yf){v(!0);break}this.toolCard(l,k.id,k.name,k.args),v(!0,s0(k.name)+"…"),this.scrollEnd();break}case"tool_end":{if(k.name===Yf){v(!1);break}if(k.name===oc){k.shown?.length&&l.append(y3(k.shown)),this.scrollEnd();break}const y=l.querySelector(`.mn-tool[data-id="${CSS.escape(k.id)}"]`);y&&this.endTool(y,k.ok,k.summary,k.ms),k.ok&&yp(k.name)&&(h=!0),v(!0);break}case"error":g(),v(!1),l.append(this.errorCard(k.message));break;case"done":v(!1),g(),this.footer(r,u,k.input_tokens,k.output_tokens),this.setContext(k.context),this.session&&k.title&&(this.session={...this.session,title:k.title,updated_at:Date.now()/1e3});break}})}catch(k){const y=k;y.name==="AbortError"?i===this.run&&l.insertAdjacentHTML("beforeend",`<div class="mn-notice">${V("stop")}<span>Stopped.</span></div>`):Zz(y)?b=!0:l.append(this.errorCard(y.message))}finally{if(i!==this.run){p&&cancelAnimationFrame(p);return}if(b){p&&cancelAnimationFrame(p),this.ctrl=null,this.setBusy(!1),this.reconnect(m);return}if(a&&!o){r.remove(),this.ctrl=null,this.setBusy(!1),this.open(m);return}p&&cancelAnimationFrame(p),v(!1),g(),this.finishAct(l,Math.round(performance.now()-s)),r.classList.remove("live"),l.childElementCount||l.append(this.errorCard("No reply came back.")),this.ctrl=null,this.setBusy(!1),this.session&&(this.session={...this.session,messages:this.session.messages+1},this.o.onChange?.(this.session)),h&&te.loadCore();const k=this.halted;this.halted=!1,this.queue.length&&!k&&window.setTimeout(()=>this.sendQueued(),400),WS(m).then(y=>{if(this.session?.id===m){this.messages=y.messages,this.session=y.session,this.setContext(y.context),this.o.onMessages?.();const w=[...y.messages].reverse().find(E=>E.role==="user"),A=this.log.querySelectorAll(".mn-u"),_=A[A.length-1];w&&_&&!_.dataset.mid&&(_.dataset.mid=String(w.id)),w&&(r.dataset.uid=String(w.id));const S=y.messages.filter(E=>E.meta?.compact===!0).pop(),T=Array.from(this.log.querySelectorAll(".mn-compact")).pop();S&&T&&!T.querySelector(".mn-compact-b")&&T.replaceWith(this.compactNote(Number(S.meta?.messages||0),S.content))}}).catch(()=>{})}}}function m3(t,e){t==="note"?te.openNote(e):t==="image"?up(b3(e),e.split("/").pop()||""):t==="upload"?up(`/api/assistant/uploads/${e}`,""):(te.go("vault"),nt.selectFolder(t==="folder"?e:""))}const jf={changed:0,shown:1,attached:2,read:3};function qz(t){const e=new Map,n=i=>{const o=i.kind+":"+i.path,s=e.get(o);(!s||jf[i.role]<jf[s.role])&&e.set(o,i)},a=i=>lt(i)||i.split("/").pop().replace(/\.md$/i,"");for(const i of t)if(i.role==="user")for(const o of i.meta?.attach||[])o.kind==="image"?n({kind:"upload",path:o.path,title:o.title,role:"attached"}):o.kind==="note"?n({kind:"note",path:o.path,title:a(o.path),role:"attached"}):n({kind:o.path?"folder":"vault",path:o.path,title:o.title,role:"attached"});else if(i.role==="assistant")for(const o of i.tool_calls||[]){if(o.name===oc)continue;const s=yp(o.name)?"changed":"read";for(const r of f3(o.arguments)){const l=Is(r)||r;n({kind:"note",path:l,title:a(l),role:s})}}else if(i.role==="tool"&&i.tool_name===oc)try{for(const o of JSON.parse(i.content).shown||[])n({...o,title:o.kind==="note"?a(o.path):o.title,role:"shown"})}catch{}return[...e.values()].sort((i,o)=>jf[i.role]-jf[o.role])}function Wz(t){const e=t.querySelector(":scope > .mn-act"),n=e?ic.get(e):void 0,a=[],i=new Set,o=(c,d,p,h,u)=>{const f=c+":"+d;i.has(f)||(i.add(f),a.push({kind:c,path:d,title:p,ic:h,cls:u}))},s=c=>lt(c)||c.split("/").pop().replace(/\.md$/i,"");for(const c of n?.changed||[])o("note",Is(c)||c,s(Is(c)||c),"edit"," w");t.querySelectorAll(".mn-cards [data-card]").forEach(c=>{const d=c.dataset.card||"note";o(d,c.dataset.path||"",c.querySelector("b")?.textContent||"",d==="image"?"image":d==="folder"?"folder":d==="vault"?"vault":"note","")});for(const c of n?.read||[])o("note",Is(c)||c,s(Is(c)||c),"note","");if(!a.length)return"";const r=12,l=a.slice(0,r).map(c=>`<span class="mn-att-c sm${c.cls}" data-card="${C(c.kind)}" data-path="${C(c.path)}" role="button" tabindex="0" title="${C(c.path||c.title)}">${V(c.ic)}<span>${x(c.title)}</span></span>`).join("");return`<div class="mn-rel"><span class="mn-rel-h">Related</span>${c0(l+(a.length>r?`<small class="mn-rel-more">+${a.length-r}</small>`:""))}</div>`}const Yf="ask_owner";function Gz(t){const e=t||{},n=typeof e.question=="string"?e.question.trim():"",a=(Array.isArray(e.options)?e.options:[]).map(i=>i).filter(i=>typeof i.label=="string"&&i.label.trim()).slice(0,5).map(i=>({label:String(i.label).trim(),description:typeof i.description=="string"?i.description:null,approve:i.approve===!0}));return n&&a.length>=2?{question:n,options:a,allow_other:e.allow_other!==!1}:null}function Vz(t,e){const n=t.find(i=>i.role==="user"&&i.meta?.answer?.to===e);if(n)return(n.meta?.answer).other?"":n.content;const a=t.findIndex(i=>i.role==="assistant"&&(i.tool_calls||[]).some(o=>o.id===e));return a>=0&&t.slice(a+1).some(i=>i.role==="user")?!1:null}function jz(t){t.classList.add("done","skipped"),t.querySelectorAll("button,input").forEach(e=>e.disabled=!0),t.querySelector(".mn-ask-f")?.setAttribute("hidden",""),t.querySelector(".mn-ask-q").insertAdjacentHTML("beforeend",'<em class="mn-ask-skip">Skipped</em>')}function g3(t,e){const n=e!==null,a=re("div","mn-ask"+(n?" done":"")+(e===!1?" skipped":""));a.dataset.ask=t.id;const i=n?" disabled":"";return a.innerHTML=`<div class="mn-ask-q">${V("help")}<span>${x(t.question)}</span>${e===!1?'<em class="mn-ask-skip">Skipped</em>':""}</div><div class="mn-ask-o">${t.options.map((o,s)=>`<button type="button" class="mn-ask-b${o.approve?" ok":""}${e===o.label?" on":""}" data-ask-opt="1" data-label="${C(o.label)}" data-approve="${o.approve?"1":""}"${i}><span class="mn-ask-n">${s+1}</span><span class="mn-ask-c"><b>${x(o.label)}</b>${o.description?`<small>${x(o.description)}</small>`:""}</span></button>`).join("")}${t.allow_other?`<button type="button" class="mn-ask-b other${e===""?" on":""}" data-ask-opt="other"${i}><span class="mn-ask-n">${V("edit")}</span><span class="mn-ask-c"><b>Other</b><small>Type your own answer</small></span></button><form class="mn-ask-f" hidden><input type="text" placeholder="Type your answer…" aria-label="Your answer" autocomplete="off"${i}><button type="submit" class="mn-ibtn" title="Send the answer (Enter)" aria-label="Send the answer"${i}>${V("enter")}</button></form>`:""}</div>`,a}function v3(t){const e=/<title[^>]*>([^<]*)<\/title>/i.exec(t)?.[1]?.trim();return t.replace(/<!doctype[\s\S]*?<\/html>/gi,e||"an HTML error page").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()}function Yz(t){const e={text:"The AI provider did not accept the key. Check it in Settings.",setup:!0},n={text:"The AI provider could not find this model or address. Check it in Settings.",setup:!0},a={text:"The AI provider is busy or out of quota. Try again in a moment.",setup:!1},i={text:"The AI provider is not answering right now. Try again in a moment.",setup:!1},o={text:"Could not reach the AI provider. Check the connection and try again.",setup:!1},s=Number(/answered (\d{3})/i.exec(t)?.[1]||0);if(s===401||s===403)return e;if(s===404)return n;if(s===429)return a;if(s>=500)return i;const r=v3(t).toLowerCase().slice(0,400),l=(...d)=>d.some(p=>r.includes(p));if(l("unauthori","forbidden","api key","invalid key"))return e;if(l("no such model","model_not_found","model not found"))return n;if(l("rate limit","quota","too many requests"))return a;if(l("overload","unavailable","bad gateway","gateway timeout"))return i;if(l("could not reach","timed out","timeout","failed to fetch","networkerror","connection refused","dns"))return o;if(!r.trim()||r.includes("no reply came back"))return{text:"No reply came back.",setup:!1};if(l("no provider","add a provider","no model"))return{text:t.trim(),setup:!0};const c=t.trim();return!s&&c.length<=160&&!/[{}<>]|\b\d{3}\b/.test(c)?{text:c.charAt(0).toUpperCase()+c.slice(1),setup:!1}:{text:"Something went wrong with this reply.",setup:!1}}const x3=4;function c0(t){return`<div class="mn-car"><button type="button" class="mn-car-a l" data-car="l" aria-label="Scroll left" tabindex="-1">${V("chev-left")}</button><div class="mn-car-row">${t}</div><button type="button" class="mn-car-a r" data-car="r" aria-label="Scroll right" tabindex="-1">${V("chev-right")}</button></div>`}function wp(t){const e=t.querySelector(".mn-car-row");if(!e)return;const n=e.scrollWidth-e.clientWidth;t.classList.toggle("more-l",e.scrollLeft>4),t.classList.toggle("more-r",n-e.scrollLeft>4),t.dataset.wired||(t.dataset.wired="1",e.addEventListener("scroll",()=>wp(t),{passive:!0}))}const oc="show_items",b3=t=>`/api/vault/file?path=${encodeURIComponent(t)}`;function y3(t){const e=re("div","mn-cards");return e.innerHTML=t.map(n=>{const a=n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"",i=n.kind==="vault"?"Every note":n.kind==="folder"?n.path?"Folder"+(a?` in ${a}`:""):"Folder":a||"Top level",o=n.kind==="note"&<(n.path)||n.title,s=n.kind==="image"?`<span class="mn-card-img"><img alt="" loading="lazy" src="${C(b3(n.path))}" onerror="this.parentElement.classList.add('broken')"></span>`:`<span class="mn-card-ic">${V(n.kind==="note"?"note":n.kind==="folder"?"folder":"vault")}</span>`;return`<button type="button" class="mn-card k-${n.kind}" data-card="${C(n.kind)}" data-path="${C(n.path)}" title="${C(n.kind==="vault"?"Open your notes":`Open ${n.path||"All notes"}`)}">${s}<span class="mn-card-t"><b>${x(o)}</b><small>${x(i)}</small></span>${V("chev","i mn-card-go")}</button>`}).join(""),e}function zr(){Cf("stMnemo"),te.go("settings")}function Xz(t,e=8){const n=re("div","mn-pick");n.innerHTML=`<label class="mn-pick-q">${V("search")}<input type="search" placeholder="Search notes" autocomplete="off" aria-label="Search notes"></label><div class="mn-pick-l" role="listbox" aria-multiselectable="true"></div>`;const a=n.querySelector("input"),i=n.querySelector(".mn-pick-l"),o=[],s=en().map(d=>({path:d.path,title:lt(d.path)||d.name,folder:d.folder})).sort((d,p)=>d.title.localeCompare(p.title));let r=null;const l=()=>{r&&(r.disabled=!o.length,r.textContent=o.length>1?`Attach ${o.length} notes`:"Attach")},c=()=>{const d=a.value.trim().toLowerCase(),p=s.filter(h=>!d||h.title.toLowerCase().includes(d)||h.path.toLowerCase().includes(d)).slice(0,60);i.innerHTML=p.length?p.map(h=>{const u=o.includes(h.path);return`<button type="button" class="mn-pick-i${u?" on":""}" role="option" aria-selected="${u}" data-p="${C(h.path)}">${V("note")}<span><b>${x(h.title)}</b><small>${x(h.folder||"Top level")}</small></span><i class="mn-pick-ck" aria-hidden="true">${V("check")}</i></button>`}).join(""):'<p class="mn-pick-none">No note matches.</p>'};a.oninput=c,i.onclick=d=>{const p=d.target.closest("[data-p]");if(!p)return;const h=p.dataset.p,u=o.indexOf(h);if(u>=0)o.splice(u,1);else if(o.length<e)o.push(h);else return ye(`Up to ${e} more this message`,"warn");p.classList.toggle("on",u<0),p.setAttribute("aria-selected",String(u<0)),l()},c(),ue.open({title:"Notes",body:n,actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Attach",cls:"primary",run:()=>{o.length&&(ue.close(),t(o))}}]}),r=document.querySelector(".modal-foot .btn.primary"),l(),window.setTimeout(()=>a.focus(),40)}function Kz(){return window.matchMedia("(hover: none) and (pointer: coarse)").matches}function Zz(t){return t.name==="TypeError"||/network|failed to fetch|load failed|connection|terminated|aborted/i.test(t.message||"")}let He=null,Pt=null,sn=[],Oa="",Dr=null,w3=0,d0=null,p0=null,h0=!1;function k3(t,e){d0=t,p0=e??null}function Jz(){Sp(!1)}async function Qz(){Ue("mnemo-css",Vf),Ue("mnemo-page-css",u8),Ue("vx-styles",ql);const t=H("#view-assistant");He||e8(),He.parentElement!==t&&t.replaceChildren(He),await Jf(),L3(),Ap();const e=d0,n=p0;d0=null,p0=null;const a=u0;u0=!1;const i=cL();if(i&&!e&&Pt.session?.id!==i){await m0(i),Zi(),$l(!0).catch(()=>{}),kp();return}i&&Pt.session?.id===i||(e?await m0(e):(e===""||a&&!Pt.working)&&Ns(),(a||n)&&rc(n?.view==="activity"),n?.scope&&Pt.attachScope(n.scope),n?.text&&Pt.prefill(n.text),Zi(),$l(!0).catch(()=>{}),window.matchMedia("(min-width: 761px)").matches&&Pt.focus(),kp())}function e8(){Nz(()=>Wn()),He=re("div","mnp"),He.innerHTML=`
|
|
4007
4021
|
<aside class="mnp-side" id="mnpSide" aria-label="Chats">
|
|
4008
4022
|
<div class="mnp-brand">${bp("md")}<div class="mnp-bt"><b>${tt}</b><small>Your notes agent</small></div>
|
|
4009
4023
|
<button type="button" class="mnp-manage" id="mnpManage" title="Select or clean up chats" aria-label="Select or clean up chats">${V("more")}</button>
|
|
@@ -4039,24 +4053,24 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4039
4053
|
<div class="mnp-art-h"><b>In this chat</b><button type="button" class="mn-ibtn" id="mnpArtX" aria-label="Close" title="Close">${V("close")}</button></div>
|
|
4040
4054
|
<div class="mnp-art-b" id="mnpArtB"></div>
|
|
4041
4055
|
</aside>
|
|
4042
|
-
<div class="mnp-ascrim" id="mnpAScrim"></div>`,Pt=new Hz({scope:()=>"global",onChange:a=>{Pt?.fleeting||(xd(a.id),R3(a)),Zi()},onForget:a=>{
|
|
4056
|
+
<div class="mnp-ascrim" id="mnpAScrim"></div>`,Pt=new Hz({scope:()=>"global",onChange:a=>{Pt?.fleeting||(xd(a.id),R3(a)),Zi()},onForget:a=>{sn=sn.filter(i=>i.id!==a),Wn(),Zi()},onNew:()=>{xd(null),Wn(),Zi()},onMessages:()=>C3(),onBusy:a=>{const i=Pt?.session&&sn.find(o=>o.id===Pt.session.id);i&&(i.running=a),Wn(),a||Jf().then(Wn),L3()}}),He.querySelector("#mnpChat").append(Pt.el);const t=He.querySelector("#mnpQ");t.oninput=()=>{if(Oa=t.value.trim().toLowerCase(),window.clearTimeout(w3),Oa.length<2)Dr=null;else{const a=Oa;w3=window.setTimeout(()=>{sP(a).then(i=>{Oa===a&&(Dr={query:a,hits:i.hits},Wn())}).catch(()=>{})},220)}Wn()};const e=a=>{He.classList.toggle("side-open",a)};He.querySelector("#mnpLists").onclick=()=>{if(document.documentElement.classList.contains("mn-pv-split")&&!document.documentElement.classList.contains("mn-pv-roomy")){xp(),Ki("side",!0);return}sc()?e(!0):Ki("side",He.classList.contains("side-closed"))},He.querySelector("#mnpArtBtn").onclick=()=>Ki("art",!He.classList.contains("art-open")),He.querySelector("#mnpArtX").onclick=()=>Ki("art",!1),He.querySelector("#mnpAScrim").onclick=()=>Ki("art",!1),He.querySelector("#mnpArtB").addEventListener("click",a=>{const i=a.target.closest("[data-page-art]");if(i){const s=_3()[Number(i.dataset.pageArt)];if(!s)return;(sc()||window.innerWidth<1100)&&Ki("art",!1),vp(s.card);return}const o=a.target.closest("[data-card]");o&&((sc()||window.innerWidth<1100)&&Ki("art",!1),m3(o.dataset.card||"",o.dataset.path||""))});const n=E3();He.classList.toggle("side-closed",!n.side),He.classList.toggle("art-open",n.art&&window.innerWidth>=1100),He.querySelector("#mnpScrim").onclick=()=>e(!1),He.querySelector("#mnpNew").onclick=()=>{e(!1),Ns()},He.querySelector("#mnpNew2").onclick=()=>Ns(),He.querySelector("#mnpFleet").onclick=()=>{if(Pt.fleeting&&Pt.session){Ns(),ye("Fleeting chat left and deleted","ok");return}Pt.session&&Ns(),Pt.setFleeting(!Pt.fleeting),Zi(),Pt.focus()},He.querySelector("#mnpFold").onclick=()=>Ki("side",!1),He.querySelector("#mnpNewRow").onclick=()=>Ns(),He.querySelector("#mnpSet").onclick=()=>zr(),He.querySelector("#mnpHome").onclick=()=>Sp(!0),He.querySelector("#mnpLook").onclick=a=>A3(a.currentTarget),Ap(),He.querySelector("#mnpActBtn").onclick=()=>{e(!1),rc(!0)},He.querySelector("#mnpClose").onclick=()=>Sp(!1),document.addEventListener("keydown",a=>{if(a.key!=="Escape"||N.page!=="assistant"||a.defaultPrevented||document.querySelector(".ui-sel-pop,.vx-menu")||!H("#modalHost").classList.contains("hidden"))return;if(He.classList.contains("side-open")){He.classList.remove("side-open");return}const i=He.querySelector(".mn-comp textarea");i&&document.activeElement===i&&i.value.trim()||Sp(!1)}),He.querySelector("#mnpMore").onclick=a=>o8(a.currentTarget),He.querySelector("#mnpManage").onclick=a=>p8(a.currentTarget),He.querySelector("#mnpSelBar").onclick=a=>{const i=a.target.closest("[data-sel]");if(!i)return;const o=i.dataset.sel;if(o==="cancel")return Tp(null);if(o==="all"){const s=c8(),r=s.length>0&&s.every(l=>Fn.has(l));return Fn=new Set(r?[]:s),Wn()}o==="delete"&&h8([...Fn||[]])},He.querySelector("#mnpList").addEventListener("click",a=>{const i=a.target,o=i.closest("[data-more]"),s=i.closest("[data-id]");if(!s)return;const r=s.dataset.id;if(Fn){a.stopPropagation(),Fn.has(r)?Fn.delete(r):Fn.add(r),Wn();return}const l=sn.find(d=>d.id===r);if(o){a.stopPropagation(),l&&l8(l,o);return}e(!1);const c=Number(s.dataset.mid||0);m0(r).then(()=>{c&&Pt.reveal(c)})})}let Xf=null;function kp(){const t=window.visualViewport,e=document.documentElement;if(!t||N.page!=="assistant")return;e.style.setProperty("--mn-vvh",Math.round(t.height)+"px"),e.style.setProperty("--mn-vvtop",Math.round(t.offsetTop)+"px");const n=window.innerHeight-t.height-t.offsetTop>80;He?.classList.toggle("kb",n)}window.visualViewport?.addEventListener("resize",kp),window.visualViewport?.addEventListener("scroll",kp),qa(()=>window.setTimeout(kp,0)),te.mnemoActivity=()=>{k3(null,{view:"activity"}),N.page==="assistant"?rc(!0):te.go("assistant")};let u0=!0;qa(t=>{t!=="assistant"&&(Xf=t,u0=!0)});function Sp(t){Mp(),He?.classList.remove("side-open"),t||!Xf?te.go("home"):Xf==="vault"&&history.length>1?history.back():te.go(Xf)}function Ns(){rc(!1),xd(null),Pt.blank(),Wn(),Zi(),Pt.focus()}const f0=[{id:"glow",label:"Glow"},{id:"aurora",label:"Aurora"},{id:"mesh",label:"Mesh"},{id:"dusk",label:"Dusk"},{id:"dawn",label:"Dawn"},{id:"deep",label:"Deep"},{id:"dots",label:"Dots"},{id:"grid",label:"Grid"},{id:"lines",label:"Lines"},{id:"waves",label:"Waves"},{id:"grain",label:"Grain"},{id:"plain",label:"Plain"}],S3="memora.mnemo.bg.v1";function M3(){try{const t=localStorage.getItem(S3);return f0.some(e=>e.id===t)?t:"glow"}catch{return"glow"}}function t8(t){try{localStorage.setItem(S3,t)}catch{}Ap()}function A3(t){if(Mp())return;const e=M3(),n=sc(),a=re("div","mnp-lookscrim"+(n?" dim":"")),i=re("div","mnp-look"+(n?" sheet":""));if(i.setAttribute("role","dialog"),i.setAttribute("aria-label","Appearance"),i.innerHTML=`<div class="mnp-look-h"><b>Appearance</b><button type="button" class="mn-ibtn" data-look-x aria-label="Close" title="Close">${V("close")}</button></div>
|
|
4043
4057
|
<span class="mnp-look-l">Theme</span>
|
|
4044
4058
|
<div class="mnp-theme" role="radiogroup" aria-label="Theme">${["light","dark","system"].map(s=>`<button type="button" role="radio" data-theme-pick="${s}">${V(tM[s])}<span>${Vx[s]}</span></button>`).join("")}</div>
|
|
4045
4059
|
<span class="mnp-look-l">Chat background</span>
|
|
4046
4060
|
<div class="mnp-bgpop-g">${f0.map(s=>`<button type="button" class="mnp-bgopt${s.id===e?" on":""}" data-pick-bg="${s.id}" aria-pressed="${s.id===e}"><i class="mnp-bgsw big" data-bg="${s.id}"></i><span>${x(s.label)}</span></button>`).join("")}</div>
|
|
4047
4061
|
<span class="mnp-look-l">Text size</span>
|
|
4048
|
-
<div class="mnp-look-fs">${c3("look")}</div>`,document.body.append(a,i),!n){const s=t.getBoundingClientRect(),r=Math.min(320,window.innerWidth-24);i.style.width=r+"px",i.style.left=Math.max(12,Math.min(window.innerWidth-r-12,s.left))+"px",s.top>420?i.style.bottom=window.innerHeight-s.top+8+"px":i.style.top=s.bottom+8+"px"}t.setAttribute("aria-expanded","true"),d3(i.querySelector(".mnp-look-fs")),i.querySelectorAll("[data-theme-pick]").forEach(s=>{s.onclick=()=>{Hl(s.dataset.themePick),Ap()}}),i.querySelectorAll("[data-pick-bg]").forEach(s=>{s.onclick=()=>t8(s.dataset.pickBg)}),i.querySelector("[data-look-x]").onclick=()=>Mp(),a.onclick=()=>Mp();const o=s=>{s.key==="Escape"&&(s.stopPropagation(),s.preventDefault(),Mp())};document.addEventListener("keydown",o,!0),Kf=()=>{document.removeEventListener("keydown",o,!0),t.setAttribute("aria-expanded","false"),i.classList.remove("on"),a.classList.remove("on"),window.setTimeout(()=>{i.remove(),a.remove()},200),t.focus({preventScroll:!0})},Ap(),i.offsetHeight,requestAnimationFrame(()=>{i.classList.add("on"),a.classList.add("on")})}let Kf=null;function Mp(){if(!Kf)return!1;const t=Kf;return Kf=null,t(),!0}function Ap(){if(!
|
|
4062
|
+
<div class="mnp-look-fs">${c3("look")}</div>`,document.body.append(a,i),!n){const s=t.getBoundingClientRect(),r=Math.min(320,window.innerWidth-24);i.style.width=r+"px",i.style.left=Math.max(12,Math.min(window.innerWidth-r-12,s.left))+"px",s.top>420?i.style.bottom=window.innerHeight-s.top+8+"px":i.style.top=s.bottom+8+"px"}t.setAttribute("aria-expanded","true"),d3(i.querySelector(".mnp-look-fs")),i.querySelectorAll("[data-theme-pick]").forEach(s=>{s.onclick=()=>{Hl(s.dataset.themePick),Ap()}}),i.querySelectorAll("[data-pick-bg]").forEach(s=>{s.onclick=()=>t8(s.dataset.pickBg)}),i.querySelector("[data-look-x]").onclick=()=>Mp(),a.onclick=()=>Mp();const o=s=>{s.key==="Escape"&&(s.stopPropagation(),s.preventDefault(),Mp())};document.addEventListener("keydown",o,!0),Kf=()=>{document.removeEventListener("keydown",o,!0),t.setAttribute("aria-expanded","false"),i.classList.remove("on"),a.classList.remove("on"),window.setTimeout(()=>{i.remove(),a.remove()},200),t.focus({preventScroll:!0})},Ap(),i.offsetHeight,requestAnimationFrame(()=>{i.classList.add("on"),a.classList.add("on")})}let Kf=null;function Mp(){if(!Kf)return!1;const t=Kf;return Kf=null,t(),!0}function Ap(){if(!He)return;const t=Bl();document.querySelectorAll(".mnp-look [data-theme-pick]").forEach(a=>{const i=a.dataset.themePick===t;a.classList.toggle("on",i),a.setAttribute("aria-checked",String(i))});const e=M3();He.dataset.bg=e;const n=He.querySelector("#mnpLookSub");n&&(n.textContent=`${Vx[t]} · ${f0.find(a=>a.id===e)?.label||"Glow"} background`),document.querySelectorAll(".mnp-look [data-pick-bg]").forEach(a=>{const i=a.dataset.pickBg===e;a.classList.toggle("on",i),a.setAttribute("aria-pressed",String(i))})}const T3="memora.mnemo.panes.v1",sc=()=>window.matchMedia("(max-width: 760px)").matches;function E3(){try{return{side:!0,art:!1,...JSON.parse(localStorage.getItem(T3)||"{}")}}catch{return{side:!0,art:!1}}}function Ki(t,e){if(He){t==="side"?He.classList.toggle("side-closed",!e):He.classList.toggle("art-open",e),t==="art"&&e&&C3();try{localStorage.setItem(T3,JSON.stringify({...E3(),[t]:e}))}catch{}}}const n8=[{role:"changed",label:"Changed"},{role:"shown",label:"Shown to you"},{role:"attached",label:"You attached"},{role:"read",label:"Read"}];function _3(){const t=Array.from(He?.querySelectorAll("#mnpChat .mn-log .mn-file")||[]),e=new Map;for(const n of t){const a=`${n.dataset.art}\0${n.dataset.title}`;e.set(a,{card:n,versions:(e.get(a)?.versions||0)+1})}return[...e.values()].reverse()}function C3(){if(!He||!Pt)return;const t=Pt.artifacts(),e=_3(),n=He.querySelector(".mnp-artn"),a=t.length+e.length;n.hidden=!a,n.textContent=String(a);const i=He.querySelector("#mnpArtB");if(!a){i.innerHTML=`<p class="mnp-art-none">Pages ${tt} writes, and the notes, folders and images this chat attaches, reads, changes or shows you collect here.</p>`;return}const o=e.length?`<section><h4>Pages<span>${e.length}</span></h4>${e.map((s,r)=>`<button type="button" class="mnp-art-i" data-page-art="${r}" title="${C(s.card.dataset.title||"Page")}"><span class="mnp-art-ic k-page">${V("code")}</span><span class="mnp-art-t"><b>${x(s.card.dataset.title||"Page")}</b><small>${s.card.dataset.art==="svg"?"SVG image":"HTML page"}${s.versions>1?` · ${s.versions} versions`:""}</small></span></button>`).join("")}</section>`:"";i.innerHTML=o+n8.map(s=>{const r=t.filter(l=>l.role===s.role);return r.length?`<section><h4>${x(s.label)}<span>${r.length}</span></h4>${r.map(l=>{const c=l.kind==="note"||l.kind==="image"?l.path.includes("/")?l.path.slice(0,l.path.lastIndexOf("/")):"Top level":l.kind==="upload"?"Image you attached":l.kind==="vault"?"Every note":"Folder",d=l.kind==="image"||l.kind==="upload"?`<span class="mnp-art-img"><img alt="" loading="lazy" src="${C(l.kind==="upload"?`/api/assistant/uploads/${l.path}`:`/api/vault/file?path=${encodeURIComponent(l.path)}`)}" onerror="this.remove()"></span>`:`<span class="mnp-art-ic k-${l.kind}">${V(l.kind==="note"?l.role==="changed"?"edit":"note":l.kind==="folder"?"folder":"vault")}</span>`;return`<button type="button" class="mnp-art-i" data-card="${C(l.kind)}" data-path="${C(l.path)}" title="${C(l.path||l.title)}">${d}<span class="mnp-art-t"><b>${x(l.title||"Untitled")}</b><small>${x(c)}</small></span></button>`}).join("")}</section>`:""}).join("")}function rc(t){if(!He)return;const e=He.querySelector("#mnpAct");t===h0&&(t?!e.hidden:e.hidden)||(h0=t,He.querySelector("#mnpChat").hidden=t,e.hidden=!t,He.querySelector("#mnpActBtn")?.classList.toggle("on",t),t&&(Ib(),Ll()),t?DM(e.querySelector(".mnp-ap"),e,{id:"mnemo",name:tt,used:!0},{top:()=>0,setup:()=>zr()}):sb(),Zi())}async function m0(t){rc(!1),xd(t);const e=sn.find(n=>n.id===t);He&&e&&(He.querySelector("#mnpTitle").textContent=e.title,He.querySelector("#mnpSub").textContent="Opening…"),await Pt.open(t),Pt.session?.id!==t&&xd(null),Wn(),Zi()}let Zf=0;function L3(){Zf||!sn.some(t=>t.running)||(Zf=window.setInterval(()=>{N.page!=="assistant"||document.hidden||Jf().then(()=>{Wn(),sn.some(t=>t.running)||(window.clearInterval(Zf),Zf=0)})},4e3))}async function Jf(){try{sn=(await qS()).sessions,e0(sn)}catch(t){sn=[];const e=He?.querySelector("#mnpList");e&&(e.innerHTML=`<p class="mnp-none">${x(t.message)}</p>`);return}Wn()}function R3(t){const e=sn.findIndex(n=>n.id===t.id);e>=0?sn[e]={...sn[e],...t}:sn.unshift(t),e0(sn),Wn()}function a8(t){if(t.pinned)return"Pinned";const e=new Date(t.updated_at*1e3),n=new Date,a=o=>new Date(o.getFullYear(),o.getMonth(),o.getDate()).getTime(),i=(a(n)-a(e))/864e5;return i<1?"Today":i<2?"Yesterday":i<7?"This week":i<31?"This month":"Older"}function g0(t,e){let n=x(t);for(const a of e.split(/\s+/).filter(i=>i.length>1).slice(0,6)){const i=new RegExp(x(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");n=n.replace(i,o=>`<mark>${o}</mark>`)}return n}function P3(t,e=""){return t.startsWith(Ud)?`<span class="mnp-tag" title="Asked with @mnemo in a note">@ note</span>${g0(t.slice(Ud.length),e)}`:g0(t,e)}function i8(t){if(!Dr||Dr.query!==Oa)return!1;const e=new Map;for(const i of Dr.hits)e.has(i.chat)||e.set(i.chat,[]),i.message_id!=null&&e.get(i.chat).push(i);if(!e.size)return t.innerHTML=`<p class="mnp-none">Nothing in your chats says “${x(Oa)}”.</p>`,!0;const n=Dr.hits.filter(i=>i.message_id!=null).length;let a=`<div class="mnp-g">${n?`${n} message${n===1?"":"s"} in ${e.size} chat${e.size===1?"":"s"}`:`${e.size} chat${e.size===1?"":"s"}`}</div>`;for(const[i,o]of e){const s=sn.find(l=>l.id===i),r=Dr.hits.find(l=>l.chat===i);a+=`<div class="mnp-row mnp-res" data-id="${C(i)}" role="button" tabindex="0">
|
|
4049
4063
|
<span class="mnp-row-ic">${V(r.scope.startsWith("note:")?"note":"chat")}</span>
|
|
4050
|
-
<span class="mnp-row-t"><b>${P3(s?.title||r.title,Oa)}</b><small>${x(kn(s?.updated_at||r.at))}</small></span></div>`;for(const l of o.slice(0,3))a+=`<button type="button" class="mnp-hit" data-id="${C(i)}" data-mid="${l.message_id}"><em>${l.role==="user"?"You":tt}</em>${g0(l.snippet,Oa)}</button>`;o.length>3&&(a+=`<div class="mnp-hit-more">+${o.length-3} more in this chat</div>`)}return t.innerHTML=a,!0}function Wn(){const t=
|
|
4064
|
+
<span class="mnp-row-t"><b>${P3(s?.title||r.title,Oa)}</b><small>${x(kn(s?.updated_at||r.at))}</small></span></div>`;for(const l of o.slice(0,3))a+=`<button type="button" class="mnp-hit" data-id="${C(i)}" data-mid="${l.message_id}"><em>${l.role==="user"?"You":tt}</em>${g0(l.snippet,Oa)}</button>`;o.length>3&&(a+=`<div class="mnp-hit-more">+${o.length-3} more in this chat</div>`)}return t.innerHTML=a,!0}function Wn(){const t=He?.querySelector("#mnpList");if(!t||(d8(),Oa.length>=2&&i8(t)))return;const e=sn.filter(o=>!Oa||o.title.toLowerCase().includes(Oa)||ui(o.scope).toLowerCase().includes(Oa)).sort((o,s)=>Number(s.pinned)-Number(o.pinned)||s.updated_at-o.updated_at);if(!e.length){t.innerHTML=`<p class="mnp-none">${Oa?"No chat matches.":`No chats yet. Ask ${tt} something to start one.`}</p>`;return}const n=Pt?.session?.id;let a="",i="";for(const o of e){const s=a8(o);s!==i&&(a+=`<div class="mnp-g">${x(s)}</div>`,i=s);const r=o.scope.startsWith("note:")?"note":o.scope.startsWith("folder:")?"folder":"chat",l=o.running||o.id===n?0:o3(o),c=Fn?Fn.has(o.id):!1;a+=`<div class="mnp-row${o.id===n&&!Fn?" on":""}${o.running?" run":""}${l?" unread":""}${c?" sel":""}" data-id="${C(o.id)}" role="${Fn?"checkbox":"button"}" tabindex="0"${Fn?` aria-checked="${c}"`:` aria-current="${o.id===n}"`}>
|
|
4051
4065
|
${Fn?`<span class="mnp-check" aria-hidden="true">${c?V("check"):""}</span>`:""}<span class="mnp-row-ic">${o.running?`<i class="mnp-spin" title="${tt} is working on this"></i>`:V(r)}</span>
|
|
4052
4066
|
<span class="mnp-row-t"><b>${P3(o.title)}</b><small>${x(ui(o.scope))} · ${x(kn(o.updated_at))}</small></span>
|
|
4053
4067
|
${l?`<span class="mnp-newn" title="${l} new message${l===1?"":"s"}" aria-label="${l} new message${l===1?"":"s"}">${l>99?"99+":l}</span>`:""}
|
|
4054
|
-
${Fn?"":`<button type="button" class="mn-ibtn mnp-row-more" data-more aria-label="Chat actions">${V("more")}</button>`}</div>`}t.innerHTML=a,t.querySelectorAll(".mnp-row").forEach(o=>{o.onkeydown=s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),o.click())}})}function Zi(){if(!
|
|
4068
|
+
${Fn?"":`<button type="button" class="mn-ibtn mnp-row-more" data-more aria-label="Chat actions">${V("more")}</button>`}</div>`}t.innerHTML=a,t.querySelectorAll(".mnp-row").forEach(o=>{o.onkeydown=s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),o.click())}})}function Zi(){if(!He)return;if(h0){He.querySelector("#mnpTitle").textContent=`${tt} activity`,He.querySelector("#mnpSub").textContent="Everything it did, and who it was for";return}const t=Pt?.session,e=!!Pt?.fleeting;He.classList.toggle("fleeting",e);const n=He.querySelector("#mnpFleet");if(n.setAttribute("aria-pressed",String(e)),n.title=e?t?"Leave this fleeting chat (it is deleted)":"Turn fleeting off":"Fleeting chat: not kept, gone when you leave it",e){He.querySelector("#mnpTitle").textContent="Fleeting chat",He.querySelector("#mnpTitle").classList.remove("task"),He.querySelector("#mnpSub").textContent="Not kept · gone when you leave it";return}He.querySelector("#mnpTitle").textContent=t?.title||"New chat",He.querySelector("#mnpTitle").classList.toggle("task",!!t?.title.startsWith(Ud)),He.querySelector("#mnpSub").textContent=t?`${ui(t.scope)} · ${t.messages} message${t.messages===1?"":"s"}`:"A chat about your whole vault"}function o8(t){const e=Pt?.session;Do([...e?[]:[{label:"New chat: these work once you send a message",icon:V("info","vx-i"),disabled:!0},{sep:!0,label:""}],{label:"Rename",icon:V("edit","vx-i"),disabled:!e,run:()=>e&&N3(e)},{label:e?.pinned?"Unpin":"Pin to the top",icon:V("pin","vx-i"),disabled:!e,run:()=>e&&void Gu(e.id,{pinned:!e.pinned}).then(n=>v0(n.session),Or)},...I3(e),{label:"Delete chat",icon:V("trash","vx-i"),danger:!!e,disabled:!e,run:()=>e&&D3(e)},{sep:!0,label:""},{label:"All chats",icon:V("chat","vx-i"),run:()=>{sc()?He?.classList.add("side-open"):Ki("side",!0),He?.querySelector("#mnpQ")?.focus()}},{label:"Select chats",icon:V("check","vx-i"),run:()=>Tp(new Set)},{label:"Clean up chats…",icon:V("trash","vx-i"),run:()=>x0()},{label:`${tt} activity`,icon:V("activity","vx-i"),run:()=>rc(!0)},{label:"Appearance",icon:V("sun","vx-i"),run:()=>A3(t)},{label:`${tt} settings: models and keys`,icon:V("settings","vx-i"),run:()=>zr()},{label:"Back to Memora",icon:V("overview","vx-i"),run:()=>Sp(!0)}],t)}function s8(t){const e=document.createElement("a");e.href=VS(t.id),e.download="",document.body.append(e),e.click(),e.remove()}async function r8(t){try{const e=await fetch(VS(t.id),{credentials:"same-origin",cache:"no-store"});if(!e.ok)throw new Error(`HTTP ${e.status}`);const n=await e.text(),a=t.title.startsWith(Ud)?t.title.slice(Ud.length):t.title,i=await Ve("/api/create",{title:`Chat - ${a}`.slice(0,100),folder:"Mnemo chats",content:n});te.loadCore(),Xn("Saved as a note in Mnemo chats","ok",6e3,{label:"Open",run:()=>te.openNote(i.path)})}catch(e){Or(e)}}function I3(t){return[{label:"Download as Markdown",icon:V("download","vx-i"),disabled:!t,run:()=>t&&s8(t)},{label:"Save as a note",icon:V("note","vx-i"),disabled:!t,run:()=>t&&void r8(t)}]}function l8(t,e){Do([{label:"Rename",icon:V("edit","vx-i"),run:()=>N3(t)},{label:t.pinned?"Unpin":"Pin to the top",icon:V("pin","vx-i"),run:()=>{Gu(t.id,{pinned:!t.pinned}).then(n=>v0(n.session),Or)}},...I3(t),{label:"Select",icon:V("check","vx-i"),run:()=>Tp(new Set([t.id]))},{sep:!0,label:""},{label:"Delete chat",icon:V("trash","vx-i"),danger:!0,run:()=>D3(t)}],e)}function Or(t){ye(t.message,"err")}function v0(t){R3(t),Pt?.session?.id===t.id&&(Pt.session={...Pt.session,...t}),Zi()}function N3(t){const e=re("div","mnp-ren",`<label class="mnp-ren-l">Name<input type="text" maxlength="80" value="${C(t.title)}"></label>`),n=e.querySelector("input"),a=async()=>{const i=n.value.trim();if(i)try{v0((await Gu(t.id,{title:i})).session),ue.close()}catch(o){Or(o)}};n.onkeydown=i=>{i.key==="Enter"&&a()},ue.open({title:"Rename chat",body:e,actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Save",cls:"primary",run:a}]}),window.setTimeout(()=>n.select(),30)}let Fn=null;function Tp(t){Fn=t,He?.classList.toggle("selecting",!!t),t&&(sc()?He?.classList.add("side-open"):Ki("side",!0)),Wn()}function c8(){return Array.from(He?.querySelectorAll("#mnpList .mnp-row[data-id]")||[]).map(t=>t.dataset.id)}function d8(){const t=He?.querySelector("#mnpSelBar");if(!t||(t.hidden=!Fn,!Fn))return;const e=Fn.size;t.innerHTML=`<span class="mnp-seln">${e?`${e} selected`:"Pick chats"}</span>
|
|
4055
4069
|
<button type="button" class="mnp-selb" data-sel="all">All</button>
|
|
4056
4070
|
<button type="button" class="mnp-selb danger" data-sel="delete"${e?"":" disabled"}>${V("trash")}<span>Delete</span></button>
|
|
4057
|
-
<button type="button" class="mn-ibtn" data-sel="cancel" aria-label="Stop selecting" title="Done">${V("close")}</button>`}function p8(t){Do([{label:"Select chats",icon:V("check","vx-i"),run:()=>Tp(new Set)},{label:"Clean up chats…",icon:V("refresh","vx-i"),run:()=>x0()},{sep:!0,label:""},{label:"Delete all chats…",icon:V("trash","vx-i"),danger:!0,disabled:!
|
|
4071
|
+
<button type="button" class="mn-ibtn" data-sel="cancel" aria-label="Stop selecting" title="Done">${V("close")}</button>`}function p8(t){Do([{label:"Select chats",icon:V("check","vx-i"),run:()=>Tp(new Set)},{label:"Clean up chats…",icon:V("refresh","vx-i"),run:()=>x0()},{sep:!0,label:""},{label:"Delete all chats…",icon:V("trash","vx-i"),danger:!0,disabled:!sn.length,run:()=>x0(!0)}],t)}function z3(t){const e=Pt?.session?.id;Jf().then(()=>{e&&!sn.some(n=>n.id===e)&&Ns(),Wn()}),ue.close(),ye(`${t.deleted} chat${t.deleted===1?"":"s"} deleted${t.skipped?`, ${t.skipped} still answering left as they are`:""}`,t.deleted?"ok":"info")}function h8(t){t.length&&ue.confirm(`Delete ${t.length} chat${t.length===1?"":"s"}?`,"They and their messages are removed for good. Your notes are not touched.",`Delete ${t.length}`,async()=>{try{z3(await GS({ids:t})),Tp(null)}catch(e){Or(e)}})}function x0(t=!1){const n=Date.now()/1e3,i=re("div","mnp-clean",`<div class="mnp-clean-o" role="radiogroup" aria-label="Which chats">${[{v:"7",label:"Older than 7 days"},{v:"30",label:"Older than 30 days"},{v:"90",label:"Older than 90 days"},{v:"all",label:"All chats"}].map(r=>`<label class="mnp-clean-r"><input type="radio" name="mnpClean" value="${r.v}"${(t?r.v==="all":r.v==="30")?" checked":""}><span>${r.label}</span><em data-n="${r.v}"></em></label>`).join("")}</div>
|
|
4058
4072
|
<label class="mnp-clean-k"><input type="checkbox" checked data-keep><span>Keep pinned chats</span></label>
|
|
4059
|
-
<p class="mnp-clean-p">Deleted chats and their messages are gone for good. Your notes are not touched, and a chat that is answering right now is left alone.</p>`),o=(r,l)=>
|
|
4073
|
+
<p class="mnp-clean-p">Deleted chats and their messages are gone for good. Your notes are not touched, and a chat that is answering right now is left alone.</p>`),o=(r,l)=>sn.filter(c=>!(l&&c.pinned)&&!c.running&&(r==="all"||c.updated_at<n-Number(r)*86400)).length,s=()=>{const r=i.querySelector("[data-keep]").checked;i.querySelectorAll("[data-n]").forEach(p=>p.textContent=String(o(p.dataset.n,r)));const l=i.querySelector("input[name=mnpClean]:checked").value,c=o(l,r),d=document.querySelector(".mnp-clean-go");d&&(d.disabled=!c,d.textContent=c?`Delete ${c} chat${c===1?"":"s"}`:"Nothing to delete")};i.onchange=s,ue.open({title:t?"Delete all chats":"Clean up chats",sub:`${sn.length} chat${sn.length===1?"":"s"} in ${tt}`,body:i,onOpen:()=>s(),actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Delete",cls:"danger mnp-clean-go",run:async()=>{const r=i.querySelector("input[name=mnpClean]:checked").value,l=i.querySelector("[data-keep]").checked;try{z3(await GS(r==="all"?{all:!0,keep_pinned:l}:{older_than_days:Number(r),keep_pinned:l}))}catch(c){Or(c)}}}]})}function D3(t){ue.confirm("Delete this chat?",`“${t.title}” and its messages are removed. Your notes are not touched.`,"Delete chat",async()=>{try{await uP(t.id),sn=sn.filter(e=>e.id!==t.id),Pt?.session?.id===t.id?Ns():Wn(),ue.close(),ye("Chat deleted","ok")}catch(e){Or(e)}})}const u8=`
|
|
4060
4074
|
/* Mnemo is a full-screen place of its own: no Memora header, sidebar or tab bar. */
|
|
4061
4075
|
:root[data-page=assistant] :is(#sidebar,#topbar,#tabbar,#sideScrim){display:none!important}
|
|
4062
4076
|
:root[data-page=assistant] #view-assistant{position:fixed;inset:0;z-index:40;background:var(--bg);padding:var(--safe-t,0px) 0 var(--safe-b,0px)!important}
|
|
@@ -4359,7 +4373,7 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4359
4373
|
.mnf-dock{right:14px;bottom:calc(var(--dock-space,76px) + 6px);width:48px;height:48px}
|
|
4360
4374
|
.mnf-tip{display:none}
|
|
4361
4375
|
}
|
|
4362
|
-
`,W3=4*6e4,y8=10*6e4;let G3=Date.now(),k0=Date.now();function V3(){k0=Date.now(),Oe("/api/auth/me").catch(()=>{})}function w8(){const t=()=>{G3=Date.now()};for(const e of["pointerdown","keydown","wheel","touchstart","scroll"])window.addEventListener(e,t,{passive:!0,capture:!0});window.setInterval(()=>{document.visibilityState==="visible"&&(Date.now()-G3>y8||Date.now()-k0<W3||V3())},6e4),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Date.now()-k0>W3&&(t(),V3())})}const em=new Set;function j3(t){return em.add(t),()=>em.delete(t)}const tm=new Map,S0=new Set;function $r(t){return t?tm.has(t):tm.size>0}function k8(t){return S0.add(t),()=>S0.delete(t)}function bi(t,e){e?tm.set(t,e):tm.delete(t),S0.forEach(n=>n(t,e))}function M0(t,e){N.note===t&&zi(),Fd(t,e)}async function Aa(){try{await te.loadCore()}catch{}em.forEach(t=>{try{t()}catch(e){console.error(e)}})}function A0(t){return t.replace(/[\\/:*?"<>|#^[\]]/g," ").replace(/\s+/g," ").replace(/^\.+/,"").trim()}async function Y3(t,e){bi(t,"Moving");try{const n=await Ve("/api/move",{path:t,folder:Px(e)}),a=n&&n.path||(e?e+"/":"")+ct(t);return bi(a,"Moving"),M0(t,a),{from:t,to:a}}finally{setTimeout(()=>bi(t,null),0)}}async function T0(t,e,n=!0){const a=[],i=[];for(const o of t)if(Be(o)!==e)try{a.push(await Y3(o,e))}catch(s){i.push(
|
|
4376
|
+
`,W3=4*6e4,y8=10*6e4;let G3=Date.now(),k0=Date.now();function V3(){k0=Date.now(),Oe("/api/auth/me").catch(()=>{})}function w8(){const t=()=>{G3=Date.now()};for(const e of["pointerdown","keydown","wheel","touchstart","scroll"])window.addEventListener(e,t,{passive:!0,capture:!0});window.setInterval(()=>{document.visibilityState==="visible"&&(Date.now()-G3>y8||Date.now()-k0<W3||V3())},6e4),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Date.now()-k0>W3&&(t(),V3())})}const em=new Set;function j3(t){return em.add(t),()=>em.delete(t)}const tm=new Map,S0=new Set;function $r(t){return t?tm.has(t):tm.size>0}function k8(t){return S0.add(t),()=>S0.delete(t)}function bi(t,e){e?tm.set(t,e):tm.delete(t),S0.forEach(n=>n(t,e))}function M0(t,e){N.note===t&&zi(),Fd(t,e)}async function Aa(){try{await te.loadCore()}catch{}em.forEach(t=>{try{t()}catch(e){console.error(e)}})}function A0(t){return t.replace(/[\\/:*?"<>|#^[\]]/g," ").replace(/\s+/g," ").replace(/^\.+/,"").trim()}async function Y3(t,e){bi(t,"Moving");try{const n=await Ve("/api/move",{path:t,folder:Px(e)}),a=n&&n.path||(e?e+"/":"")+ct(t);return bi(a,"Moving"),M0(t,a),{from:t,to:a}}finally{setTimeout(()=>bi(t,null),0)}}async function T0(t,e,n=!0){const a=[],i=[];for(const o of t)if(Be(o)!==e)try{a.push(await Y3(o,e))}catch(s){i.push(pn(o)+": "+s.message)}if(await Aa(),a.forEach(o=>bi(o.to,null)),i.length&>(`${i.length} could not be moved. ${i[0]}`,null,"err"),a.length&&n){const o=a.length===1?`"${lt(a[0].from)}"`:`${a.length} notes`;gt(`Moved ${o} to ${e||Tt}`,async()=>{for(const s of a.slice().reverse())try{await Y3(s.to,Be(s.from))}catch{}await Aa(),a.forEach(s=>bi(s.from,null))})}return a}async function E0(t,e,n,a=!0){if(!t||t===e||Fi(e,t))return!1;const i=async(s,r)=>{let l=s;if(Be(r)!==Be(s)){const c=await Ve("/api/folder/move",{folder:l,into:Be(r)});l=c&&c.to||(Be(r)?Be(r)+"/":"")+ct(s)}ct(r)!==ct(l)&&await Ve("/api/folder/rename",{folder:l,name:ct(r)})};try{await i(t,e)}catch(s){return gt(`Could not ${n.toLowerCase()} "${ct(t)}": ${s.message}`,null,"err"),!1}Hu(t,e),hn.add(e);let o=Be(e);for(;o;)hn.add(o),o=Be(o);return Po(),await Aa(),a&>(`${n} "${ct(t)}" → ${e}`,async()=>{try{await i(e,t),Hu(e,t)}catch(s){gt("Undo failed: "+s.message,null,"err")}await Aa()}),!0}async function S8(t,e){try{const n=await Ve("/api/folder/move-contents",{folder:t,into:e});Hu(t,e),e&&hn.add(e),Po(),await Aa();const a=n&&n.moved&&n.moved.length||0;return gt(`Moved ${a} item${a===1?"":"s"} from "${ct(t)}" to ${e||Tt}`,null,"info"),!0}catch(n){return gt("Could not move the contents: "+n.message,null,"err"),!1}}async function nm(t,e){const n=A0(e);if(!n||n===pn(t)||n===or(pn(t)))return null;bi(t,"Renaming");try{const a=await Ve("/api/rename",{path:t,name:n}),i=a&&a.path||t;return bi(i,"Renaming"),M0(t,i),await Aa(),bi(i,null),gt(`Renamed to "${n}"`,async()=>{bi(i,"Renaming");try{const o=await Ve("/api/rename",{path:i,name:pn(t)});M0(i,o&&o.path||t)}catch(o){gt("Undo failed: "+o.message,null,"err")}await Aa(),bi(i,null)}),i}catch(a){return gt("Rename failed: "+a.message,null,"err"),null}finally{bi(t,null)}}async function X3(t,e){const n=A0(e);if(!n||n===ct(t))return!1;const a=Be(t),i=a?a+"/"+n:n;return E0(t,i,"Renamed")}async function K3(t,e){const n=e.replace(/[\\/]/g," ").replace(/\s+/g," ").trim();if(!n)return null;try{const a=await Ve("/api/create",{title:n,folder:Px(t)});return await Aa(),a&&a.path||null}catch(a){return gt("Could not create the note: "+a.message,null,"err"),null}}async function M8(t,e){const n=A0(e);if(!n)return null;try{const a=t?t+"/"+n:n,i=await Ve("/api/folder",{name:a}),o=i&&i.path||a;return t&&hn.add(t),hn.add(o),Po(),await Aa(),o}catch(a){return gt("Could not create the folder: "+a.message,null,"err"),null}}async function Z3(t){const e=[];for(const n of t)try{const a=await Ve("/api/delete",{path:n,mode:"trash"});Fd(n,null),e.push({path:n,name:ct(a.to||n)})}catch(a){gt(`Could not move "${lt(n)}" to the Trash: ${a.message}`,null,"err")}return await Aa(),e}async function J3(t,e){return(await Ve("/api/trash/restore",e==null?{name:t}:{name:t,into:e})).path||""}async function Q3(t,e){const n=fr(t).map(i=>i.path),a={folder:t};e.mode==="trash"?a.mode="trash":a.into=e.into||"Root";try{const i=await Ve("/api/delete-folder",a),o=new Set(i.moved||[]);for(const s of n){const r=e.mode==="move"?A8(e.into,s.slice(t.length+1)):"";Fd(s,o.has(r)?r:null)}return Hu(t,null),await Aa(),e.mode==="trash"?i.count??n.length:o.size}catch(i){return gt("Could not delete the folder: "+i.message,null,"err"),await Aa(),null}}function A8(t,e){return t?t+"/"+e:e}async function T8(t,e){try{await Ve("/api/folder-meta",{folder:t,...e});const n={...N.folderMeta[t]||{},...e};for(const a of Object.keys(n))n[a]||delete n[a];N.folderMeta[t]=n,em.forEach(a=>a()),te.renderTree()}catch(n){gt("Failed: "+n.message,null,"err")}}async function E8(t,e){await Ve("/api/save",{path:t,content:e})}const qo=(t,e=1.9)=>`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${e}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${t}</svg>`,lc=qo('<rect x="5" y="10.5" width="14" height="10" rx="2.4"/><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7"/>'),_8=qo('<circle cx="9" cy="8" r="3.2"/><path d="M3.5 19.5c.6-3.2 2.8-5 5.5-5s4.9 1.8 5.5 5"/><circle cx="17" cy="9" r="2.5"/><path d="M16 14.6c2.4-.3 4.1 1.2 4.6 4.4"/>'),C8=qo('<path d="M3 3l18 18"/><path d="M10.6 5.1A9.7 9.7 0 0 1 12 5c6.4 0 10 7 10 7a17 17 0 0 1-2.6 3.5M6.6 6.6A17 17 0 0 0 2 12s3.6 7 10 7a9.6 9.6 0 0 0 4.4-1.1"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/>'),L8=lc,R8=qo('<path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>'),P8=qo('<circle cx="12" cy="12" r="9"/><path d="M12 11v5"/><path d="M12 7.6v.4"/>',2),I8=qo('<path d="M5 12.5l4.2 4.2L19 7"/>',2.6),N8=qo('<circle cx="11" cy="11" r="6.5"/><path d="M20 20l-4.2-4.2"/>'),z8=qo('<path d="M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v8a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5z"/>',1.8),D8=qo('<path d="M7 3h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M14 3v5h5"/>',1.8),_0=lc.replace("<svg ",'<svg class="vx-i" '),O8=`
|
|
4363
4377
|
.pv-lock{display:inline-grid;place-items:center;flex:none;width:15px;height:15px;color:var(--warn);opacity:.9;margin-left:4px}
|
|
4364
4378
|
.pv-lock svg{width:13px;height:13px}
|
|
4365
4379
|
|
|
@@ -4489,7 +4503,7 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4489
4503
|
<span class="fd-opt-d">Subfolders are kept inside the destination and links to the moved notes are updated. If a name is already taken there, a number is added to it.</span></span></label>
|
|
4490
4504
|
<div class="fd-dest" data-fd-dest><span class="fd-dest-l">Move the notes to</span></div></div>
|
|
4491
4505
|
<label class="fd-opt fd-opt-l danger"><input type="radio" name="fdMode" value="trash"><span class="fd-opt-b"><span class="fd-opt-t">Move everything in this folder to the Trash</span>
|
|
4492
|
-
<span class="fd-opt-d">All ${x(i)} go to the Trash, where you can restore them to their old places. Other files in the folder (such as images) are deleted for good.</span></span></label>`,actions:[{label:"Back",cls:"ghost",run:()=>{ue.close(),_p(t)}},{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:d,cls:"primary",run:async()=>{const h=c.value??"";if(r==="move"&&c.value==null)return;ue.close();const u=await Q3(t,r==="trash"?{mode:r}:{mode:r,into:h});u!=null&>(r==="trash"?`Folder "${a}" deleted, ${Wo(u,"note")} moved to the Trash`:`Folder "${a}" deleted, ${Wo(u,"note")} moved to ${h||Tt}`,null,"info")}}],onOpen:h=>{h.querySelector("[data-fd-dest]")?.appendChild(c.el),l=h.parentElement?.querySelector(".modal-foot .btn:last-child")||null,h.querySelectorAll("input[name=fdMode]").forEach(f=>f.addEventListener("change",()=>{f.checked&&(r=f.value==="trash"?"trash":"move",l&&(l.textContent=r==="trash"?p:d,l.classList.toggle("primary",r==="move"),l.classList.toggle("danger",r==="trash"),l.disabled=r==="move"&&c.value==null))}));const u=()=>{const f=h.querySelector("input[value=move]");f&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change")))};h.querySelector("[data-fd-move]")?.addEventListener("click",u),c.el.addEventListener("focusin",u)}})}function N0(t){ya(t,"Path copied")}function nT(t){ya(`[[${t.replace(/\.md$/i,"")}]]`,"Wikilink copied")}function z0(t){AP(t,En(t),Io(t),e=>{T8(t,e)})}function zs(t,e,n,a=[]){const i=t==="";Do([{label:"New note here",icon:me.newNote,hint:"N",run:()=>nt.newNote(t)},{label:"New folder here",icon:me.newFolder,run:()=>nt.newFolder(t)},{label:i?"Ask Mnemo about the vault":"Ask Mnemo about this folder",icon:me.mnemo,run:()=>te.askMnemo(i?"global":"folder:"+t)},{sep:!0,label:""},{label:"Rename",icon:me.rename,hint:"F2",disabled:i,run:()=>n?n():Xx("Rename folder","Folder name",ct(t),o=>{X3(t,o)})},{label:"Move to…",icon:me.move,disabled:i,run:()=>I0(t)},...Be(t)?[{label:"Move out to top level",icon:me.move,run:()=>P0(t,"")}]:[],{label:"Move contents to…",icon:me.move,disabled:i,run:()=>Df({title:`Move everything in "${ct(t)}" into`,folders:Ms(),value:Be(t),exclude:[t],verb:"Move contents here",run:o=>ue.confirm("Move contents",`Every note and subfolder in "${t}" moves into ${o||Tt}; "${ct(t)}" is then removed. If a name is already taken there, a number is added to it.`,"Move contents",async()=>{ue.close(),await S8(t,o)},!1)})},{label:"Copy path",icon:me.copy,disabled:i,run:()=>N0(t)},{label:"Color and icon…",icon:me.palette,disabled:i,run:()=>z0(t)},{label:"Privacy…",icon:_0,disabled:i,run:()=>{sm("folder",t)}},{label:pi("folder",t)?"Unpin":"Pin",icon:pi("folder",t)?me.pinOff:me.pin,disabled:i,run:()=>Fr("folder",t)},{sep:!0,label:""},{label:"Delete folder…",icon:me.trash,danger:!0,disabled:i,hint:"Del",run:()=>_p(t)},...a],e)}function Go(t,e,n){const a=t.length===1?t[0]:null;Do([...a?[{label:"Open",icon:me.eye,hint:"Enter",run:()=>nt.openNote(a)}]:[],{label:"Rename",icon:me.rename,hint:"F2",disabled:!a,run:()=>a&&(n?n():Xx("Rename note","Note name",or(
|
|
4506
|
+
<span class="fd-opt-d">All ${x(i)} go to the Trash, where you can restore them to their old places. Other files in the folder (such as images) are deleted for good.</span></span></label>`,actions:[{label:"Back",cls:"ghost",run:()=>{ue.close(),_p(t)}},{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:d,cls:"primary",run:async()=>{const h=c.value??"";if(r==="move"&&c.value==null)return;ue.close();const u=await Q3(t,r==="trash"?{mode:r}:{mode:r,into:h});u!=null&>(r==="trash"?`Folder "${a}" deleted, ${Wo(u,"note")} moved to the Trash`:`Folder "${a}" deleted, ${Wo(u,"note")} moved to ${h||Tt}`,null,"info")}}],onOpen:h=>{h.querySelector("[data-fd-dest]")?.appendChild(c.el),l=h.parentElement?.querySelector(".modal-foot .btn:last-child")||null,h.querySelectorAll("input[name=fdMode]").forEach(f=>f.addEventListener("change",()=>{f.checked&&(r=f.value==="trash"?"trash":"move",l&&(l.textContent=r==="trash"?p:d,l.classList.toggle("primary",r==="move"),l.classList.toggle("danger",r==="trash"),l.disabled=r==="move"&&c.value==null))}));const u=()=>{const f=h.querySelector("input[value=move]");f&&!f.checked&&(f.checked=!0,f.dispatchEvent(new Event("change")))};h.querySelector("[data-fd-move]")?.addEventListener("click",u),c.el.addEventListener("focusin",u)}})}function N0(t){ya(t,"Path copied")}function nT(t){ya(`[[${t.replace(/\.md$/i,"")}]]`,"Wikilink copied")}function z0(t){AP(t,En(t),Io(t),e=>{T8(t,e)})}function zs(t,e,n,a=[]){const i=t==="";Do([{label:"New note here",icon:me.newNote,hint:"N",run:()=>nt.newNote(t)},{label:"New folder here",icon:me.newFolder,run:()=>nt.newFolder(t)},{label:i?"Ask Mnemo about the vault":"Ask Mnemo about this folder",icon:me.mnemo,run:()=>te.askMnemo(i?"global":"folder:"+t)},{sep:!0,label:""},{label:"Rename",icon:me.rename,hint:"F2",disabled:i,run:()=>n?n():Xx("Rename folder","Folder name",ct(t),o=>{X3(t,o)})},{label:"Move to…",icon:me.move,disabled:i,run:()=>I0(t)},...Be(t)?[{label:"Move out to top level",icon:me.move,run:()=>P0(t,"")}]:[],{label:"Move contents to…",icon:me.move,disabled:i,run:()=>Df({title:`Move everything in "${ct(t)}" into`,folders:Ms(),value:Be(t),exclude:[t],verb:"Move contents here",run:o=>ue.confirm("Move contents",`Every note and subfolder in "${t}" moves into ${o||Tt}; "${ct(t)}" is then removed. If a name is already taken there, a number is added to it.`,"Move contents",async()=>{ue.close(),await S8(t,o)},!1)})},{label:"Copy path",icon:me.copy,disabled:i,run:()=>N0(t)},{label:"Color and icon…",icon:me.palette,disabled:i,run:()=>z0(t)},{label:"Privacy…",icon:_0,disabled:i,run:()=>{sm("folder",t)}},{label:pi("folder",t)?"Unpin":"Pin",icon:pi("folder",t)?me.pinOff:me.pin,disabled:i,run:()=>Fr("folder",t)},{sep:!0,label:""},{label:"Delete folder…",icon:me.trash,danger:!0,disabled:i,hint:"Del",run:()=>_p(t)},...a],e)}function Go(t,e,n){const a=t.length===1?t[0]:null;Do([...a?[{label:"Open",icon:me.eye,hint:"Enter",run:()=>nt.openNote(a)}]:[],{label:"Rename",icon:me.rename,hint:"F2",disabled:!a,run:()=>a&&(n?n():Xx("Rename note","Note name",or(pn(a)),i=>{nm(a,i)}))},{label:t.length>1?`Move ${t.length} notes to…`:"Move to…",icon:me.move,run:()=>Ur(t)},...a?[{label:pi("note",a)?"Unpin":"Pin",icon:pi("note",a)?me.pinOff:me.pin,run:()=>Fr("note",a)},{label:"Privacy…",icon:_0,run:()=>{sm("node",a)}},{label:"Copy path",icon:me.copy,run:()=>N0(a)},{label:"Copy wikilink",icon:me.link,run:()=>nT(a)}]:[],{label:"New note in this folder",icon:me.newNote,run:()=>nt.newNote(Be(t[0]))},{sep:!0,label:""},{label:t.length>1?`Move ${t.length} notes to Trash`:"Move to Trash",icon:me.trash,hint:"Del",danger:!0,run:()=>{dc(t)}}],e)}const H8=/\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i,aT="memora.vault.excerpts.v2",q8=3,Cp=new Map,Br=[],rm=new Set,D0=new Set;let iT=0;try{const t=sessionStorage.getItem(aT);if(t)for(const[e,n]of Object.entries(JSON.parse(t)))Cp.set(e,n)}catch{}function W8(){clearTimeout(iT),iT=window.setTimeout(()=>{try{const t={};let e=0;for(const[n,a]of Cp){if(e++>3e3)break;t[n]=a}sessionStorage.setItem(aT,JSON.stringify(t))}catch{}},800)}function G8(t){return String(t||"").replace(/^---[\s\S]*?\n---\s*/,"").replace(/^#\s+.*$/m,"").replace(/```[\s\S]*?```/g," ").replace(/<[^>]+>/g," ").replace(/!\[\[[^\]]*\]\]/g," ").replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\bhttps?:\/\/\S+\.(png|jpe?g|gif|webp|avif|svg|bmp)(\?\S*)?/gi," ").replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/\bhttps?:\/\/\S+/g," ").replace(/(^|\s)#[\w/-]+/g," ").replace(/^\s*([-*+]|\d+\.)\s+\[[ xX]\]/gm," ").replace(/^\s*\|?\s*:?-{3,}.*$/gm," ").replace(/[#>*_`~|=]+|(^|\s)-+(?=\s)/g," ").replace(/\s+/g," ").trim().slice(0,200)}function V8(t,e){let n=e.trim().split(/[|#?]/)[0];try{n=decodeURIComponent(n)}catch{}if(!n||/^[a-z]+:/i.test(n)||!H8.test(n))return null;const a=(n.startsWith("/")?n.slice(1):(t.includes("/")?t.slice(0,t.lastIndexOf("/")+1):"")+n).split("/"),i=[];for(const o of a)!o||o==="."||(o===".."?i.pop():i.push(o));return i.length?i.join("/"):null}function j8(t,e,n){const a=/<img[^>]+src="([^"]+)"/i.exec(n||"")?.[1]?.replace(/&/g,"&");if(a&&a.startsWith("/api/"))return a;const i=/!\[\[([^\]]+)\]\]|!\[[^\]]*\]\(\s*<?([^)\s>]+)/.exec(e||""),o=i?V8(t,i[1]||i[2]||""):null;return o?"/api/vault/file?path="+encodeURIComponent(o):""}function Lp(t,e){const n=Cp.get(t);return n&&n.m>=Math.floor(e||0)?n:void 0}function Y8(t){return D0.add(t),()=>D0.delete(t)}function X8(t,e){Lp(t,e)||rm.has(t)||Br.some(n=>n.path===t)||(Br.push({path:t,mtime:Math.floor(e||0)}),oT())}function K8(t){for(let e=Br.length-1;e>=0;e--)t.has(Br[e].path)||Br.splice(e,1)}function oT(){for(;rm.size<q8&&Br.length;){const t=Br.shift();rm.add(t.path),Oe("/api/note?path="+encodeURIComponent(t.path)).then(e=>{const n=(e.tags&&e.tags.length?e.tags:o2(e.content)).slice(0,6);Cp.set(t.path,{m:Math.max(t.mtime,Math.floor(Number(e.mtime)||0)),text:G8(e.content),tags:n,img:j8(t.path,e.content,e.html||"")}),W8()}).catch(()=>{Cp.set(t.path,{m:t.mtime,text:"",tags:[]})}).finally(()=>{rm.delete(t.path),D0.forEach(e=>e(t.path)),oT()})}}function Qi(t,e){const n=t.toLowerCase();if(!e)return 1;if(n===e)return 100;if(n.startsWith(e))return 60-Math.min(20,n.length/4);const a=n.indexOf(e);return a>=0?(/[\s/_-]/.test(n[a-1]||"")?45:30)-Math.min(15,a/3):0}function lm(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;let a=Array.from({length:e.length+1},(i,o)=>o);for(let i=1;i<=t.length;i++){const o=[i];let s=i;for(let r=1;r<=e.length;r++)o[r]=Math.min(a[r]+1,o[r-1]+1,a[r-1]+(t[i-1]===e[r-1]?0:1)),s=Math.min(s,o[r]);if(s>n)return n+1;a=o}return a[e.length]}function O0(t,e){if(e.length<3)return null;if(e.includes(" "))return Z8(t,e);const n=e.length<=4?1:2;let a=null;for(const i of t.split(/[^\p{L}\p{N}]+/u)){if(!i)continue;const o=i.toLowerCase(),s=lm(o,e,n),r=o.length>e.length?lm(o.slice(0,e.length),e,n):n+1,l=Math.min(s,r);if(l>n)continue;const c=10-l*3-Math.abs(o.length-e.length)*.2;if(a&&a.s>=c)continue;const d=s<=r?`${l} letter${l===1?"":"s"} off from “${i}”`:`“${i}” starts almost like “${e}”`;a={s:c,word:i,why:d}}return a}function Rp(t,e){if(!e)return null;const n=t.toLowerCase().indexOf(e);return n<0?null:[n,n+e.length]}function cm(t){return t.trim().toLowerCase().replace(/\s+/g," ")}function Z8(t,e){const n=e.split(" ").filter(Boolean),a=t.split(/[^\p{L}\p{N}]+/u).filter(Boolean);if(n.length>a.length)return null;let i=0,o=0,s="";for(let r=0;r<n.length;r++){const l=n[r],c=l.length<=2?0:l.length<=4?1:2,d=r===n.length-1;let p=-1,h=0;for(let u=i;u<a.length;u++){const f=a[u].toLowerCase(),v=lm(f,l,c),g=d&&f.length>l.length?lm(f.slice(0,l.length),l,c):c+1,m=Math.min(v,g);if(m<=c){p=u,h=m;break}}if(p<0)return null;s||(s=a[p]),o+=h,i=p+1}return o?{s:10-o*2,word:s,why:`${o} letter${o===1?"":"s"} off from “${t}”`}:null}const J8="image/png,image/jpeg,image/webp,image/gif";let Pp=null,sT=()=>{};function Q8(t){sT=t}function eD(t){if(!Pp||Pp.note!==t)return null;const e=Pp.name;return Pp=null,e}function tD(t,e){Pp={note:t,name:e},ue.close(!0),sT(t)}function rT(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(t<10240?1:0)} KB`:`${(t/1048576).toFixed(1)} MB`}async function nD(t,e,n){const a=e instanceof File&&e.name?e.name:"pasted-image.png",i=await fetch(`/api/vault/image?note=${encodeURIComponent(t)}&name=${encodeURIComponent(a)}`,{method:"POST",credentials:"same-origin",headers:{accept:"application/json","content-type":e.type||"application/octet-stream"},body:e}),o=await i.json().catch(()=>({}));if(!i.ok)throw new Error(o.error||`could not upload (HTTP ${i.status})`);return o}function aD(t){return Oe(`/api/vault/images?folder=${encodeURIComponent(Px(t))}`)}function iD(t){return Oe(`/api/vault/images?note=${encodeURIComponent(t)}`)}function oD(t){const e=t.used_in.length;return e===0?"Not shown in a note":e===1?"In 1 note":`In ${e} notes`}function lT(t,e,n){Ue("vx-gallery",cT);const a=re("div","vx-gal");return t.length?(a.innerHTML=t.map((i,o)=>`<button type="button" class="vx-gal-i" data-i="${o}" style="--i:${Math.min(o,16)}" title="${C(i.name)}">
|
|
4493
4507
|
<span class="vx-gal-th"><img loading="lazy" decoding="async" alt="${C(i.name)}" src="${C(i.url)}"></span>
|
|
4494
4508
|
<span class="vx-gal-cap"><b>${x(i.name)}</b><small>${x(rT(i.bytes))} · ${x(oD(i))}</small></span>
|
|
4495
4509
|
</button>`).join(""),a.onclick=i=>{const o=i.target.closest(".vx-gal-i"),s=o&&t[Number(o.dataset.i)];s&&sD(s,n)},a):(a.classList.add("empty"),a.innerHTML=`<p class="vx-gal-empty">${me.image}<span>${x(e)}</span></p>`,a)}function sD(t,e){Ue("vx-gallery",cT);const n=re("div","vx-iv"),a=`![${t.name.replace(/\.[^.]+$/,"")}](path:${t.name})`;n.innerHTML=`<figure class="vx-iv-fig"><img alt="${C(t.name)}" src="${C(t.url)}"></figure>
|
|
@@ -4760,7 +4774,7 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4760
4774
|
<div class="vx-igroup">${q("Updated",w)}${ne?q("Created",`<span title="${C(ne.full)}">${x(ne.short)}</span>`):""}</div>
|
|
4761
4775
|
<div class="vx-igroup">${q("Words",`<span>${l.toLocaleString()} · ${A}</span>`)}${q("Links",`<span>${B.length}</span>`)}${q("Backlinks",`<span>${s.length}</span>`)}</div>
|
|
4762
4776
|
<div class="vx-igroup">${q("Pinned",`<span>${d?"Yes":"No"}</span>`)}${_?q("Last agent",_):""}</div>
|
|
4763
|
-
</dl>`;m.prepend(ae),g.appendChild(m),P&&t.appendChild(P),t.appendChild(g),p&&(g.scrollTop=p),u.querySelector("[data-back]").onclick=()=>{fc().then(()=>document.dispatchEvent(new CustomEvent("vx-back")))},t.querySelectorAll(".vx-crumb[data-f],.vx-meta-folder:not(.vx-ct *)").forEach(be=>{be.onclick=()=>nt.selectFolder(be.dataset.f||"")});const Re=u.querySelector("[data-mode]");Re&&(Re.onclick=()=>ym(!0)),u.querySelector("[data-save]")?.addEventListener("click",()=>{wm()}),u.querySelector("[data-cancel]")?.addEventListener("click",()=>Q0()),u.querySelector("[data-more]").onclick=be=>rO(n,be.currentTarget),u.querySelector("[data-aa]")?.addEventListener("click",be=>ID(be.currentTarget,()=>_T(g,N.editing)));const ot=G.length?sO(g,G,t):null,Qe=be=>{const ft=G.indexOf(be);ft>=0&&ot?.pick(ft),be.scrollIntoView({behavior:oO(),block:ft>=0?"start":"center"}),be.classList.remove("vx-hit"),be.offsetWidth,be.classList.add("vx-hit"),be.tagName==="A"&&be.focus({preventScroll:!0})},st=E?E.querySelectorAll('img[src^="/api/vault/file"]').length:0,de={heads:G,backlinks:s,outs:B,links:O,details:we,path:n,images:st},Z={open:be=>nt.openNote(be),create:(be,ft)=>Z0(be,ft),jump:Qe,current:()=>ot?.current()??-1,folder:be=>nt.selectFolder(be),tag:be=>{N.tags.active=be||null,fc().then(()=>te.go("tags"))}},Ne=u.querySelector("[data-contents]");if(Ne&&!N.editing){const be=re("section","vx-icard vx-toc");be.setAttribute("aria-label","Contents"),be.innerHTML=`<header class="vx-toc-head"><button type="button" class="vx-icon-btn" data-toc-x aria-label="Close the panel" title="Close">${me.close}</button></header>`;const ft=bT(de,Z,!1);be.querySelector(".vx-toc-head").prepend(ft.querySelector(".vx-ct-main")),be.appendChild(ft),ae.prepend(be);const rt=()=>t.clientWidth>=JD,vt=()=>{const Rt=q0();m.classList.toggle("toc-open",Rt),rt()?(Ne.setAttribute("aria-pressed",String(Rt)),Ne.removeAttribute("aria-haspopup")):(Ne.removeAttribute("aria-pressed"),Ne.setAttribute("aria-haspopup","dialog"),Ne.setAttribute("aria-expanded","false"))};vt(),Ne.onclick=()=>{if(!rt()){TD(Ne,de,Z);return}xT(!q0()),vt(),q0()&&Dp(be,ot?.current()??-1,!0)},be.querySelector("[data-toc-x]").onclick=()=>{xT(!1),vt(),Ne.focus()}}const Xe=u.querySelector("[data-mnemo]");Xe&&(Xe.onclick=()=>te.askMnemo("note:"+n));const De=u.querySelector("[data-hist]");De&&(De.setAttribute("aria-haspopup","dialog"),De.onclick=()=>X0()),k.querySelector(".vx-doc-title").ondblclick=()=>J0(),t.querySelectorAll(".vx-tag:not(.vx-ct *)").forEach(be=>{be.onclick=()=>{N.tags.active=be.dataset.tag||null,fc().then(()=>te.go("tags"))}}),b.querySelector("[data-start]")?.addEventListener("click",()=>ym(!0)),t.querySelectorAll(".vx-rfoot [data-open]").forEach(be=>be.onclick=()=>nt.openNote(be.dataset.open||"")),t.querySelectorAll(".vx-rfoot [data-create]").forEach(be=>be.onclick=()=>Z0(be.dataset.create||"",be)),qr(),t.onkeydown=hO}const JD=820;function QD(t){return{path:t,viewing:()=>wt.v?.rev||"",preview:e=>{tO(e)},latest:()=>K0()}}function X0(){const t=Se.path,e=pt?.querySelector("[data-hist]");!t||!e||GD(e,QD(t),()=>pa())}async function eO(){if(N.editing){if(!await mc())return;N.editing=!1,Se.path&&pt&&await Os(pt,Se.path,jo,!0)}X0()}function bm(){wt.v=null,wt.content=wt.html="",wt.diff=null,wt.mode="read",wt.seq++}async function tO(t){const e=Se.path;if(!e)return;const n=++wt.seq;try{const a=await BD(e,t.rev);if(n!==wt.seq||Se.path!==e)return;const i=wt.mode;wt.v=t,wt.content=a.content||"",wt.html=a.html||"",wt.diff=null,wt.mode=i,ha(),pt?.querySelector(".vx-note-scroll")?.scrollTo({top:0}),wt.mode==="changes"&&zT(),pt?.querySelector(".vh-banner [data-restore]")?.focus({preventScroll:!0})}catch(a){n===wt.seq&>(`Could not open version ${t.version}: ${a.message}`,null,"err")}}function K0(){wt.v&&(bm(),ha(),pt?.querySelector("[data-hist]")?.focus({preventScroll:!0}))}function nO(t){!wt.v||wt.mode===t||(wt.mode=t,ha(),pt?.querySelector(`.vh-seg [data-m=${t}]`)?.focus({preventScroll:!0}),t==="changes"&&wt.diff==null&&zT())}async function zT(){const t=wt.v,e=Se.path;if(!t||!e)return;const n=wt.seq;try{const i=await HD(e,t.rev);if(n!==wt.seq||wt.v!==t)return;wt.diff=i}catch(i){if(n!==wt.seq)return;wt.diff="",gt(`Could not compare the versions: ${i.message}`,null,"err")}if(wt.mode!=="changes")return;const a=document.activeElement?.closest(".vh-seg")?".vh-seg [data-m=changes]":"";ha(),a&&pt?.querySelector(a)?.focus({preventScroll:!0})}function aO(){const t=wt.v,e=Se.path;!t||!e||YD(e,t,async()=>{bm(),pt&&Se.path===e&&await Os(pt,e,jo,!0),pt?.querySelector(".vx-prose")?.classList.add("vx-flash")})}function iO(t){const e=t.frontmatter||{},n=e.created??e.date;if(typeof n!="string"&&typeof n!="number")return null;const a=typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n.trim()),i=new Date(typeof n=="number"&&n<1e11?n*1e3:a?n.trim()+"T00:00":n);return Number.isNaN(i.getTime())?null:{short:i.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),full:i.toLocaleString()}}const oO=()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";function Z0(t,e){const n=Be(Se.path||"");Do([{label:`Create “${t}”`,icon:me.newNote,hint:n?ct(n):Tt,run:()=>{dO(t)}}],e)}function sO(t,e,n){let a=-1,i=0,o=-1;const s=(d,p)=>{o=d,Dp(n,d,p);const h=document.querySelector(".vx-sheet.vx-pop-ct");h&&Dp(h,d,!1)},r=()=>{const d=t.getBoundingClientRect(),p=d.top+d.height*.3;let h=0;return e.forEach((u,f)=>{u.getBoundingClientRect().top<=p&&(h=f)}),t.scrollTop+t.clientHeight>=t.scrollHeight-4&&e.forEach((u,f)=>{u.getBoundingClientRect().top<d.bottom&&(h=Math.max(h,f))}),h},l=()=>{if(a>=0||!t.isConnected)return;const d=r();d!==o&&s(d,!0)};let c=0;return t.addEventListener("scroll",()=>{if(a>=0){clearTimeout(i),i=window.setTimeout(()=>{a=-1},160);return}cancelAnimationFrame(c),c=requestAnimationFrame(l)},{passive:!0}),requestAnimationFrame(l),{pick:d=>{a=d,s(d,!1),clearTimeout(i),i=window.setTimeout(()=>{a=-1},900)},current:()=>o>=0?o:r()}}function rO(t,e){const n=pi("note",t);Do([{label:"Rename",icon:me.rename,hint:"F2",run:()=>J0()},{label:"Move to…",icon:me.move,hint:"M",run:()=>Ur([t])},{label:n?"Unpin":"Pin",icon:n?me.pinOff:me.pin,hint:"P",run:()=>{Fr("note",t),ha()}},{label:"Privacy…",icon:_0,run:()=>{sm("node",t)}},{label:"Version history",icon:me.history,run:()=>{eO()}},{label:"Ask Mnemo about this note",icon:me.mnemo,run:()=>te.askMnemo("note:"+t)},{sep:!0,label:""},{label:"Copy link",icon:me.link,run:()=>lO(location.origin+k2(t),"Link copied")},{label:"Copy path",icon:me.copy,run:()=>N0(t)},{label:"Copy wikilink",icon:me.wiki,run:()=>nT(t)},{label:"New note in this folder",icon:me.newNote,run:()=>nt.newNote(Be(t))},{sep:!0,label:""},{label:"Move to Trash",icon:me.trash,hint:"Del",danger:!0,run:()=>{dc([t],()=>nt.selectFolder(Be(t)),!0)}}],e)}function lO(t,e){navigator.clipboard?.writeText(t).then(()=>gt(e,null,"info",2500),()=>gt("Clipboard is not available",null,"err",2500))}function cO(t){const e=t.toLowerCase();return en().find(n=>n.name.toLowerCase()===e||n.path.toLowerCase()===e+".md"||n.path.toLowerCase()===e)}async function dO(t){const e=await K3(Be(Se.path||""),t);e&&nt.openNote(e)}function DT(t){const e=t.firstElementChild,n=[
|
|
4777
|
+
</dl>`;m.prepend(ae),g.appendChild(m),P&&t.appendChild(P),t.appendChild(g),p&&(g.scrollTop=p),u.querySelector("[data-back]").onclick=()=>{fc().then(()=>document.dispatchEvent(new CustomEvent("vx-back")))},t.querySelectorAll(".vx-crumb[data-f],.vx-meta-folder:not(.vx-ct *)").forEach(be=>{be.onclick=()=>nt.selectFolder(be.dataset.f||"")});const Re=u.querySelector("[data-mode]");Re&&(Re.onclick=()=>ym(!0)),u.querySelector("[data-save]")?.addEventListener("click",()=>{wm()}),u.querySelector("[data-cancel]")?.addEventListener("click",()=>Q0()),u.querySelector("[data-more]").onclick=be=>rO(n,be.currentTarget),u.querySelector("[data-aa]")?.addEventListener("click",be=>ID(be.currentTarget,()=>_T(g,N.editing)));const ot=G.length?sO(g,G,t):null,Qe=be=>{const ft=G.indexOf(be);ft>=0&&ot?.pick(ft),be.scrollIntoView({behavior:oO(),block:ft>=0?"start":"center"}),be.classList.remove("vx-hit"),be.offsetWidth,be.classList.add("vx-hit"),be.tagName==="A"&&be.focus({preventScroll:!0})},st=E?E.querySelectorAll('img[src^="/api/vault/file"]').length:0,de={heads:G,backlinks:s,outs:B,links:O,details:we,path:n,images:st},Z={open:be=>nt.openNote(be),create:(be,ft)=>Z0(be,ft),jump:Qe,current:()=>ot?.current()??-1,folder:be=>nt.selectFolder(be),tag:be=>{N.tags.active=be||null,fc().then(()=>te.go("tags"))}},Ne=u.querySelector("[data-contents]");if(Ne&&!N.editing){const be=re("section","vx-icard vx-toc");be.setAttribute("aria-label","Contents"),be.innerHTML=`<header class="vx-toc-head"><button type="button" class="vx-icon-btn" data-toc-x aria-label="Close the panel" title="Close">${me.close}</button></header>`;const ft=bT(de,Z,!1);be.querySelector(".vx-toc-head").prepend(ft.querySelector(".vx-ct-main")),be.appendChild(ft),ae.prepend(be);const rt=()=>t.clientWidth>=JD,vt=()=>{const Rt=q0();m.classList.toggle("toc-open",Rt),rt()?(Ne.setAttribute("aria-pressed",String(Rt)),Ne.removeAttribute("aria-haspopup")):(Ne.removeAttribute("aria-pressed"),Ne.setAttribute("aria-haspopup","dialog"),Ne.setAttribute("aria-expanded","false"))};vt(),Ne.onclick=()=>{if(!rt()){TD(Ne,de,Z);return}xT(!q0()),vt(),q0()&&Dp(be,ot?.current()??-1,!0)},be.querySelector("[data-toc-x]").onclick=()=>{xT(!1),vt(),Ne.focus()}}const Xe=u.querySelector("[data-mnemo]");Xe&&(Xe.onclick=()=>te.askMnemo("note:"+n));const De=u.querySelector("[data-hist]");De&&(De.setAttribute("aria-haspopup","dialog"),De.onclick=()=>X0()),k.querySelector(".vx-doc-title").ondblclick=()=>J0(),t.querySelectorAll(".vx-tag:not(.vx-ct *)").forEach(be=>{be.onclick=()=>{N.tags.active=be.dataset.tag||null,fc().then(()=>te.go("tags"))}}),b.querySelector("[data-start]")?.addEventListener("click",()=>ym(!0)),t.querySelectorAll(".vx-rfoot [data-open]").forEach(be=>be.onclick=()=>nt.openNote(be.dataset.open||"")),t.querySelectorAll(".vx-rfoot [data-create]").forEach(be=>be.onclick=()=>Z0(be.dataset.create||"",be)),qr(),t.onkeydown=hO}const JD=820;function QD(t){return{path:t,viewing:()=>wt.v?.rev||"",preview:e=>{tO(e)},latest:()=>K0()}}function X0(){const t=Se.path,e=pt?.querySelector("[data-hist]");!t||!e||GD(e,QD(t),()=>pa())}async function eO(){if(N.editing){if(!await mc())return;N.editing=!1,Se.path&&pt&&await Os(pt,Se.path,jo,!0)}X0()}function bm(){wt.v=null,wt.content=wt.html="",wt.diff=null,wt.mode="read",wt.seq++}async function tO(t){const e=Se.path;if(!e)return;const n=++wt.seq;try{const a=await BD(e,t.rev);if(n!==wt.seq||Se.path!==e)return;const i=wt.mode;wt.v=t,wt.content=a.content||"",wt.html=a.html||"",wt.diff=null,wt.mode=i,ha(),pt?.querySelector(".vx-note-scroll")?.scrollTo({top:0}),wt.mode==="changes"&&zT(),pt?.querySelector(".vh-banner [data-restore]")?.focus({preventScroll:!0})}catch(a){n===wt.seq&>(`Could not open version ${t.version}: ${a.message}`,null,"err")}}function K0(){wt.v&&(bm(),ha(),pt?.querySelector("[data-hist]")?.focus({preventScroll:!0}))}function nO(t){!wt.v||wt.mode===t||(wt.mode=t,ha(),pt?.querySelector(`.vh-seg [data-m=${t}]`)?.focus({preventScroll:!0}),t==="changes"&&wt.diff==null&&zT())}async function zT(){const t=wt.v,e=Se.path;if(!t||!e)return;const n=wt.seq;try{const i=await HD(e,t.rev);if(n!==wt.seq||wt.v!==t)return;wt.diff=i}catch(i){if(n!==wt.seq)return;wt.diff="",gt(`Could not compare the versions: ${i.message}`,null,"err")}if(wt.mode!=="changes")return;const a=document.activeElement?.closest(".vh-seg")?".vh-seg [data-m=changes]":"";ha(),a&&pt?.querySelector(a)?.focus({preventScroll:!0})}function aO(){const t=wt.v,e=Se.path;!t||!e||YD(e,t,async()=>{bm(),pt&&Se.path===e&&await Os(pt,e,jo,!0),pt?.querySelector(".vx-prose")?.classList.add("vx-flash")})}function iO(t){const e=t.frontmatter||{},n=e.created??e.date;if(typeof n!="string"&&typeof n!="number")return null;const a=typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n.trim()),i=new Date(typeof n=="number"&&n<1e11?n*1e3:a?n.trim()+"T00:00":n);return Number.isNaN(i.getTime())?null:{short:i.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),full:i.toLocaleString()}}const oO=()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";function Z0(t,e){const n=Be(Se.path||"");Do([{label:`Create “${t}”`,icon:me.newNote,hint:n?ct(n):Tt,run:()=>{dO(t)}}],e)}function sO(t,e,n){let a=-1,i=0,o=-1;const s=(d,p)=>{o=d,Dp(n,d,p);const h=document.querySelector(".vx-sheet.vx-pop-ct");h&&Dp(h,d,!1)},r=()=>{const d=t.getBoundingClientRect(),p=d.top+d.height*.3;let h=0;return e.forEach((u,f)=>{u.getBoundingClientRect().top<=p&&(h=f)}),t.scrollTop+t.clientHeight>=t.scrollHeight-4&&e.forEach((u,f)=>{u.getBoundingClientRect().top<d.bottom&&(h=Math.max(h,f))}),h},l=()=>{if(a>=0||!t.isConnected)return;const d=r();d!==o&&s(d,!0)};let c=0;return t.addEventListener("scroll",()=>{if(a>=0){clearTimeout(i),i=window.setTimeout(()=>{a=-1},160);return}cancelAnimationFrame(c),c=requestAnimationFrame(l)},{passive:!0}),requestAnimationFrame(l),{pick:d=>{a=d,s(d,!1),clearTimeout(i),i=window.setTimeout(()=>{a=-1},900)},current:()=>o>=0?o:r()}}function rO(t,e){const n=pi("note",t);Do([{label:"Rename",icon:me.rename,hint:"F2",run:()=>J0()},{label:"Move to…",icon:me.move,hint:"M",run:()=>Ur([t])},{label:n?"Unpin":"Pin",icon:n?me.pinOff:me.pin,hint:"P",run:()=>{Fr("note",t),ha()}},{label:"Privacy…",icon:_0,run:()=>{sm("node",t)}},{label:"Version history",icon:me.history,run:()=>{eO()}},{label:"Ask Mnemo about this note",icon:me.mnemo,run:()=>te.askMnemo("note:"+t)},{sep:!0,label:""},{label:"Copy link",icon:me.link,run:()=>lO(location.origin+k2(t),"Link copied")},{label:"Copy path",icon:me.copy,run:()=>N0(t)},{label:"Copy wikilink",icon:me.wiki,run:()=>nT(t)},{label:"New note in this folder",icon:me.newNote,run:()=>nt.newNote(Be(t))},{sep:!0,label:""},{label:"Move to Trash",icon:me.trash,hint:"Del",danger:!0,run:()=>{dc([t],()=>nt.selectFolder(Be(t)),!0)}}],e)}function lO(t,e){navigator.clipboard?.writeText(t).then(()=>gt(e,null,"info",2500),()=>gt("Clipboard is not available",null,"err",2500))}function cO(t){const e=t.toLowerCase();return en().find(n=>n.name.toLowerCase()===e||n.path.toLowerCase()===e+".md"||n.path.toLowerCase()===e)}async function dO(t){const e=await K3(Be(Se.path||""),t);e&&nt.openNote(e)}function DT(t){const e=t.firstElementChild,n=[pn(Se.path||""),lt(Se.path||"")].map(a=>a.toLowerCase());e&&e.tagName==="H1"&&n.includes(e.textContent?.trim().toLowerCase()||"")&&e.remove(),t.querySelectorAll("a.wl").forEach(a=>{a.setAttribute("role","link"),a.tabIndex=0;const i=()=>{const o=a.dataset.path;o&&!a.classList.contains("broken")?nt.openNote(o):Z0(a.textContent||"",a)};a.onclick=o=>{o.preventDefault(),i()},a.onkeydown=o=>{o.key==="Enter"&&i()},a.classList.contains("broken")?(a.title="Not created yet. Click to create it.",a.setAttribute("aria-label",`${a.textContent||""} (not created yet, create it)`)):a.dataset.path&&(a.title=`${lt(a.dataset.path)} · ${Be(a.dataset.path)||Tt}`)}),t.querySelectorAll("li").forEach(a=>{const i=a.firstChild,o=i&&i.nodeType===Node.TEXT_NODE?/^\s*\[([ xX])\]\s/.exec(i.textContent||""):null;if(!i||!o)return;i.textContent=(i.textContent||"").slice(o[0].length);const s=document.createElement("input");s.type="checkbox",s.checked=o[1]!==" ",a.prepend(s),a.classList.add("task"),s.checked&&a.classList.add("done")}),t.querySelectorAll("input[type=checkbox]").forEach(a=>a.disabled=!0)}function J0(){const t=pt?.querySelector(".vx-doc-title");if(!t||!Se.path)return;const e=Se.path;Yu(t,or(pn(e))).then(async n=>{if(!n)return;await fc();const a=await nm(e,n);a&&pt&&(N.note!==a||Se.path!==a)&&(N.note=a,await Os(pt,a,jo,!0))})}function ym(t){if(N.editing!==t){if(!t){wm();return}bm(),N.editing=!0,ha(),pt?.querySelector(".vx-editor")?.focus()}}async function wm(){await mc()&&(N.editing=!1,Se.path&&pt&&await Os(pt,Se.path,jo,!0))}function Q0(){const t=async()=>{N.editing=!1,Se.status="saved",Se.theirs=null,Se.path&&pt&&await Os(pt,Se.path,jo,!0)};if(!vm()){t();return}const e=Se.path,n=xm(),a=Se.base;ue.open({title:"Save your changes?",body:'<p style="margin:0">This note has changes that are not saved yet.</p>',actions:[{label:"Keep editing",cls:"ghost",run:()=>ue.close()},{label:"Discard",cls:"danger",run:async()=>{ue.close(),e&&Fp(e),await t(),gt("Changes discarded",()=>{e&&(Se.path===e&&N.note===e&&pt?.isConnected?OT(n):uc(e,n,a))},"info",9e3)}},{label:"Save",cls:"primary",run:async()=>{ue.close(),await wm()}}]})}function OT(t){N.editing=!0,ha();const e=pt?.querySelector(".vx-editor");e&&(e.value=t,e.dispatchEvent(new Event("input")),e.focus())}function pO(t,e){const n=ND(t);if(!n)return null;if(n.text===e)return Fp(t),null;if(N.editing)return null;const a=re("div","vx-conflict vx-draft");return a.setAttribute("role","status"),a.innerHTML=`<div class="vx-conflict-head">${me.edit}<div><b>You have unsaved changes from ${x(kn(n.at/1e3))} on this device.</b>
|
|
4764
4778
|
<p>${n.base!==e?"The note has changed since then. Restoring puts your version in the editor; nothing is saved until you press Save.":"Restore them to keep editing, or discard them."}</p></div></div>
|
|
4765
4779
|
<div class="vx-conflict-acts"><button class="btn sm" data-dr="drop">Discard</button><button class="btn sm primary" data-dr="restore">Restore</button></div>`,a.querySelector("[data-dr=restore]").onclick=()=>OT(n.text),a.querySelector("[data-dr=drop]").onclick=()=>{Fp(t),ha(),gt("Unsaved changes discarded",()=>{uc(t,n.text,n.base),Se.path===t&&ha()},"info",9e3)},a}const $T="memora.reader.focus";let ey=(()=>{try{return localStorage.getItem($T)==="1"}catch{return!1}})();function FT(){const t=pt;if(!t)return;const e=ey&&!N.editing;t.classList.toggle("vx-focus",e)}function ty(t){ey=t;try{localStorage.setItem($T,t?"1":"0")}catch{}FT();const e=pt?.querySelector(t?".vx-unfocus":"[data-focus]");window.setTimeout(()=>e?.focus({preventScroll:!0}),260)}function hO(t){const e=t.target.tagName,n=e==="INPUT"||e==="TEXTAREA"||e==="SELECT";if((t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="e"){t.preventDefault(),ym(!N.editing);return}if(!(n||t.ctrlKey||t.metaKey||t.altKey)){if(t.key==="Escape"&&wt.v&&!N.editing&&!document.querySelector(".vx-sheet,.vx-pop,#modalHost:not(.hidden)")){t.preventDefault(),K0();return}if(t.key==="e"||t.key==="E")t.preventDefault(),ym(!0);else if((t.key==="p"||t.key==="P")&&Se.path)Fr("note",Se.path),ha();else if(t.key==="F2")t.preventDefault(),J0();else if((t.key==="m"||t.key==="M")&&Se.path)t.preventDefault(),Ur([Se.path]);else if((t.key==="f"||t.key==="F")&&!N.editing)t.preventDefault(),ty(!ey);else if(t.key==="Delete"&&Se.path){const a=Se.path;dc([a],()=>nt.selectFolder(Be(a)),!0)}}}const uO=[{k:"h",icon:me.heading,label:"Heading",key:"Ctrl+Alt+H"},{k:"b",icon:me.bold,label:"Bold",key:"Ctrl+B"},{k:"i",icon:me.italic,label:"Italic",key:"Ctrl+I"},{k:"ul",icon:me.list,label:"Bulleted list",key:"Ctrl+Shift+8"},{k:"task",icon:me.task,label:"Task",key:"Ctrl+Shift+9"},{k:"quote",icon:me.quote,label:"Quote"},{k:"code",icon:me.code,label:"Code",key:"Ctrl+`"},{k:"link",icon:me.link,label:"Link",key:"Ctrl+K"},{k:"wiki",icon:me.wiki,label:"Wikilink",key:"[["},{k:"img",icon:me.image,label:"Image (or paste or drop one)"}];function fO(){const t=re("div","vx-edit");t.innerHTML=`<div class="vx-toolbar" role="toolbar" aria-label="Formatting">${uO.map(i=>`${i.k==="ul"||i.k==="link"||i.k==="img"?'<span class="vx-tsep" aria-hidden="true"></span>':""}<button data-t="${i.k}" title="${C(i.label+(i.key?" ("+i.key+")":""))}" aria-label="${C(i.label)}">${i.icon}</button>`).join("")}<span class="vx-grow"></span><span class="vx-edit-hint"><kbd>Ctrl</kbd><kbd>S</kbd> save · <kbd>Esc</kbd> close</span></div>
|
|
4766
4780
|
<textarea class="vx-editor note-editor" spellcheck="true" aria-label="Note text"></textarea>
|
|
@@ -4785,7 +4799,7 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4785
4799
|
`,o,t.selectionEnd,"end"),t.dispatchEvent(new Event("input")),t.focus()}function xO(t,e){const n=encodeURIComponent(e),a=Array.from(t.querySelectorAll("img")).find(o=>{const s=decodeURIComponent(o.getAttribute("src")||"");return s.endsWith("/"+e)||s.endsWith("="+e)||(o.getAttribute("src")||"").endsWith(n)});if(!a)return;const i=a.closest("figure")||a;requestAnimationFrame(()=>{i.scrollIntoView({block:"center",behavior:"smooth"}),i.classList.add("vx-hit"),setTimeout(()=>i.classList.remove("vx-hit"),1800)})}function bO(t,e){if(SO(t,e))return;const n=t.ctrlKey||t.metaKey,a=t.key.toLowerCase();if(n&&a==="s")t.preventDefault(),mc();else if(n&&a==="b")t.preventDefault(),$s(e,"b");else if(n&&a==="i")t.preventDefault(),$s(e,"i");else if(n&&a==="k")t.preventDefault(),$s(e,"link");else if(n&&t.key==="`")t.preventDefault(),$s(e,"code");else if(n&&t.altKey&&a==="h")t.preventDefault(),$s(e,"h");else if(n&&t.shiftKey&&(t.key==="*"||t.code==="Digit8"))t.preventDefault(),$s(e,"ul");else if(n&&t.shiftKey&&(t.key==="("||t.code==="Digit9"))t.preventDefault(),$s(e,"task");else if(t.key==="Escape")t.preventDefault(),t.stopPropagation(),Q0();else if(t.key==="Tab"){t.preventDefault();const{selectionStart:i,value:o}=e,s=o.lastIndexOf(`
|
|
4786
4800
|
`,i-1)+1;if(t.shiftKey)o.slice(s,s+2)===" "&&(e.setRangeText("",s,s+2,"preserve"),e.setSelectionRange(Math.max(s,i-2),Math.max(s,i-2)));else if(e.selectionStart!==e.selectionEnd){Hp(e," ");return}else e.setRangeText(" ",i,i,"end");e.dispatchEvent(new Event("input"))}else if(t.key==="Enter"&&!t.shiftKey&&!n){const{selectionStart:i,value:o}=e,s=o.lastIndexOf(`
|
|
4787
4801
|
`,i-1)+1,r=o.slice(s,i),l=/^(\s*)([-*+] \[[ xX]\] |[-*+] |> |(\d+)\. )/.exec(r);if(!l)return;if(t.preventDefault(),r.trim()===l[2].trim())e.setRangeText("",s,i,"end");else{let c=l[2];l[3]&&(c=Number(l[3])+1+". "),c=c.replace(/\[[xX]\]/,"[ ]"),e.setRangeText(`
|
|
4788
|
-
`+l[1]+c,i,e.selectionEnd,"end")}e.dispatchEvent(new Event("input"))}}const yO=/(^|[\s>(])([@/])([a-z]{0,5})$/i;let It=null;function wO(t,e){const n=
|
|
4802
|
+
`+l[1]+c,i,e.selectionEnd,"end")}e.dispatchEvent(new Event("input"))}}const yO=/(^|[\s>(])([@/])([a-z]{0,5})$/i;let It=null;function wO(t,e){const n=pn(t);return en().filter(i=>i.name.toLowerCase()===n.toLowerCase()).length<2||Be(t)===e?n:t.replace(/\.md$/i,"")}function Fs(){It?.box.remove(),It=null}function kO(t){const e=t.selectionStart,n=t.value.slice(Math.max(0,e-80),e),a=yO.exec(n);if(a&&"mnemo".startsWith(a[3].toLowerCase())&&(a[2]==="@"||a[3].length>0)){const d=e-a[3].length-1,p={name:"@mnemo:",folder:"Ask Mnemo here; it answers under the line",text:"@mnemo: ",mention:!0};if(!It){const f=re("div","vx-suggest");f.setAttribute("role","listbox"),t.parentElement?.appendChild(f),It={box:f,items:[p],i:0,from:d}}It.items=[p],It.i=0,It.from=d;const h=t.value.slice(0,e).split(`
|
|
4789
4803
|
`).length,u=parseFloat(getComputedStyle(t).lineHeight)||22;It.box.style.top=Math.min(t.offsetTop+h*u+8-t.scrollTop,t.offsetTop+t.offsetHeight-40)+"px",ay(t);return}const i=/\[\[([^\]\n|]*)$/.exec(n);if(!i){Fs();return}const o=i[1].toLowerCase(),s=Be(Se.path||""),r=en().filter(d=>d.name.toLowerCase().includes(o)||d.path.toLowerCase().includes(o)).sort((d,p)=>(d.name.toLowerCase().startsWith(o)?0:1)-(p.name.toLowerCase().startsWith(o)?0:1)||d.name.localeCompare(p.name)||d.path.localeCompare(p.path)).slice(0,8).map(d=>({name:lt(d.path),folder:Be(d.path),text:wO(d.path,s)}));if(!r.length){Fs();return}if(!It){const d=re("div","vx-suggest");d.setAttribute("role","listbox"),t.parentElement?.appendChild(d),It={box:d,items:r,i:0,from:e-i[1].length}}It.items=r,It.from=e-i[1].length,It.i=Math.min(It.i,r.length-1);const l=t.value.slice(0,e).split(`
|
|
4790
4804
|
`).length,c=parseFloat(getComputedStyle(t).lineHeight)||22;It.box.style.top=Math.min(t.offsetTop+l*c+8-t.scrollTop,t.offsetTop+t.offsetHeight-40)+"px",ay(t)}function ay(t){if(!It)return;const e=It;e.box.innerHTML=e.items.map((n,a)=>`<button role="option" aria-selected="${a===e.i}" class="${a===e.i?"on":""}" data-i="${a}">${n.mention?me.mnemo:me.note}<span>${x(n.name)}</span><small style="margin-left:auto;padding-left:10px;color:var(--muted);font-size:11.5px">${x(n.folder||Tt)}</small></button>`).join(""),e.box.querySelectorAll("button").forEach(n=>{n.onmousedown=a=>{a.preventDefault(),BT(t,Number(n.dataset.i))}})}function BT(t,e){if(!It)return;const n=It.items[e].text,a=t.selectionStart;if(It.items[e].mention){t.setRangeText(n,It.from,a,"end"),Fs(),t.dispatchEvent(new Event("input"));return}const i=t.value.slice(a,a+2)==="]]"?"":"]]";t.setRangeText(n+i,It.from,a,"end"),i||t.setSelectionRange(It.from+n.length+2,It.from+n.length+2),Fs(),t.dispatchEvent(new Event("input"))}function SO(t,e){return It?t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),It.i=(It.i+(t.key==="ArrowDown"?1:-1)+It.items.length)%It.items.length,ay(e),!0):t.key==="Enter"&&It.items[It.i]?.mention&&e.selectionStart-It.from<=1?(Fs(),!1):t.key==="Enter"||t.key==="Tab"?(t.preventDefault(),BT(e,It.i),!0):t.key==="Escape"?(t.preventDefault(),t.stopPropagation(),Fs(),!0):!1:!1}k8((t,e)=>{if(!pt||t!==Se.path&&t!==N.note||!e&&Se.path!==N.note)return;pt.classList.toggle("vx-busy",!!e);const n=pt.querySelector(".vx-save");n&&e?(n.dataset.state="saving",n.innerHTML=`<i></i>${x(e)}…`):qr()});function MO(){gm||(gm=Hn("mutation",t=>{if(N.page!=="vault"||!pt||!pt.isConnected){gm?.(),gm=null;return}const e=OS(t),n=Se.path;if(n){if(e.type==="node_renamed"&&e.oldPath===n&&e.path){zD(n,e.path),Se.path=e.path,N.note!==e.path&&zi(),N.note=e.path,!$r(n)&&!$r(e.path)&>(`${e.actor||"An agent"} moved this note to ${e.path}`,null,"info"),N.editing?ha():Os(pt,e.path,jo,!0);return}if(e.type==="node_deleted"&&e.path===n&&!$r(n)){N.editing&&uc(n,xm(),Se.base);const a=t.trashed;gt(`${e.actor||"An agent"} ${a?"moved this note to the Trash":"deleted this note"}`,null,"err",9e3);return}e.path!==n||e.type!=="node_updated"&&e.type!=="node_created"||(N.editing?Oe("/api/note?path="+encodeURIComponent(n)).then(a=>{if(Se.path!==n||!N.editing)return;const i=a.content||"",o=pt?.querySelector(".vx-editor"),s=o?o.value:Se.base;if(!(i===Se.base||i===s)){if(s===Se.base){Se.base=i,o&&(o.value=i),Se.doc&&(Se.doc.content=i),gt(`${e.actor||"An agent"} updated this note`,null,"info",3e3);return}UT(i,e.actor||"An agent")}}).catch(()=>{}):Os(pt,n,jo,!0).then(()=>{pt?.querySelector(".vx-prose")?.classList.add("vx-flash")}))}}))}const AO=`
|
|
4791
4805
|
.vx-coins{display:inline-flex;flex-direction:row-reverse;align-items:center;flex:none;margin-left:auto;padding-left:4px;--cs:18px;--step:11px}
|
|
@@ -4811,16 +4825,16 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4811
4825
|
`;function HT(t,e=!1){if(!t.length)return"";Ue("vx-coins-css",AO);const n=t.slice(0,3),a=t.length-n.length,i=t.map(o=>o.actor).join(", ");return`<span class="vx-coins${e?" sm":""}${t.length>1?" many":""}" title="${C(`Working here now: ${i}`)}" aria-label="${C(`${t.length} agent${t.length===1?"":"s"} working here`)}">${n.map((o,s)=>`<span class="vx-coin" style="--c:${C(An(o.actor,o.id))};--k:${s}">${x(Md(o.actor))}</span>`).join("")}${a>0?`<span class="vx-coin-more">+${a}</span>`:""}</span>`}const qp=new Set,qT="memora.vault.sections.v1",Zn=(()=>{try{return{pins:!0,folders:!0,...JSON.parse(localStorage.getItem(qT)||"{}")}}catch{return{pins:!0,folders:!0}}})();function iy(t){Object.assign(Zn,t);try{localStorage.setItem(qT,JSON.stringify(Zn))}catch{}TO(),WT()}function TO(){for(const[t,e]of[[".vx-pins",Zn.pins],[".vx-folders",Zn.folders]])document.querySelectorAll(t).forEach(n=>{n.classList.toggle("folded",!e),n.querySelector(".vx-fold")?.setAttribute("aria-expanded",String(e));const a=n.querySelector(".vx-sec-body");a&&(a.inert=!e)})}function WT(){window.dispatchEvent(new CustomEvent("memora:sections",{detail:{anyOpen:Zn.pins||Zn.folders}}))}window.addEventListener("memora:sections-toggle",()=>{const t=Zn.pins||Zn.folders;iy({pins:!t,folders:!t})}),window.addEventListener("memora:sections-ask",()=>WT());function GT(t){const e=`More actions for ${t}`;return`<button class="vx-row-more" type="button" tabindex="-1" aria-label="${C(e)}" title="More actions">${me.more}</button>`}function VT(t){const e=re("div","vx-kids-inner");return e.style.setProperty("--gx",Rf(t)*14+"px"),Pf(t)&&e.classList.add("capped"),e}function oy(t){return Pf(t)?`<span class="vx-lvl" title="Level ${t}" aria-hidden="true">${t}</span>`:""}function EO(t,e){const{count:n,folder:a}=Bb(t),i=t.kind==="notes"?t.paths:t.kind==="folder"?[t.path]:[t.item.key],o=Array.from(new Set(i.map(d=>a?d:Be(d)))),s=d=>d===""?Tt:d,r=a?s(i[0]):o.length===1?s(o[0]):`${o.length} folders`,l=s(a?(e?e+"/":"")+ct(i[0]):e),c=a?"The folder moves with everything in it; links to its notes are updated and pins follow.":`${n>1?"They move":"It moves"}; links to ${n>1?"them":"it"} are updated and pins follow.`;return`<div class="vx-mv">
|
|
4812
4826
|
<div class="vx-mv-row"><span class="vx-mv-k">From</span><span class="vx-mv-p mono" title="${C(r)}">${x(r)}</span></div>
|
|
4813
4827
|
<div class="vx-mv-row"><span class="vx-mv-k">To</span><span class="vx-mv-p mono to" title="${C(l)}">${x(l)}</span></div>
|
|
4814
|
-
</div><p class="panel-sub" style="margin:10px 0 0">${c}</p>`}const _O='<svg class="vx-i" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="m7 4 5 5 5-5M7 20l5-5 5 5"/></svg>';function jT(t,e){const n=re("div","vx-sec-body"),a=re("div","vx-sec-inner");return a.appendChild(t),n.appendChild(a),n.inert=!e,n}function YT(t,e,n){t.setAttribute("role","button"),t.tabIndex=0,t.setAttribute("aria-expanded",String(e)),t.onclick=a=>{a.target.closest(".vx-sec-acts")||n()},t.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),n())}}window.addEventListener("memora:collapse-folders",()=>{pn.size&&(pn.clear(),Po(),Ja())});function XT(t){return Array.from(t.querySelectorAll("[data-key]")).filter(e=>e.offsetParent!==null&&e.offsetHeight>0)}function CO(t){const e=new Map;for(const n of XT(t)){const a=n.getBoundingClientRect();e.set(n.dataset.key,{top:a.top,height:a.height,el:n})}return e}const gc="cubic-bezier(.2,.8,.2,1)";function LO(t,e){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches||!e.size)return;const n=XT(t),a=new Set(n.map(l=>l.dataset.key)),i=n.filter(l=>!e.has(l.dataset.key)&&!l.dataset.key.startsWith("pin:")),o=Array.from(e.entries()).filter(([l])=>!a.has(l));if(i.length>12||o.length>12)return;const s=window.innerHeight;for(const l of n){const c=e.get(l.dataset.key);if(!c)continue;const d=l.getBoundingClientRect().top;if((d>s||d+c.height<0)&&(c.top>s||c.top+c.height<0))continue;const p=c.top-d;Math.abs(p)>1&&l.animate([{transform:`translateY(${p}px)`},{transform:"none"}],{duration:280,easing:gc})}for(const l of i)l.animate([{opacity:0,transform:"translateX(-10px)",backgroundColor:"var(--accent-soft)"},{opacity:1,transform:"none",backgroundColor:"var(--accent-soft)",offset:.45},{opacity:1,transform:"none",backgroundColor:"transparent"}],{duration:900,easing:gc});if(!o.length)return;getComputedStyle(t).position==="static"&&(t.style.position="relative");const r=t.getBoundingClientRect();for(const[,l]of o){const c=l.el;c.removeAttribute("data-key"),c.setAttribute("aria-hidden","true"),Object.assign(c.style,{position:"absolute",left:"0",right:"0",top:l.top-r.top+t.scrollTop+"px",height:l.height+"px",pointerEvents:"none",zIndex:"1"}),t.appendChild(c);const d=c.animate([{opacity:1,transform:"none"},{opacity:0,transform:"translateX(-24px)"}],{duration:320,easing:"ease-in",fill:"forwards"});d.onfinish=()=>c.remove()}}const Wp=t=>`color-mix(in srgb, var(--accent) ${t}%, transparent)`,Gp="inset 3px 0 0 var(--accent)";function RO(t,e,n){const a=n?[{backgroundColor:Wp(20),boxShadow:Gp},{backgroundColor:Wp(14),boxShadow:Gp,offset:.6}]:[{opacity:0,transform:"translateY(-8px) scale(.97)",backgroundColor:Wp(26),boxShadow:Gp},{opacity:1,transform:"none",backgroundColor:Wp(22),boxShadow:Gp,offset:.2},{backgroundColor:Wp(14),boxShadow:Gp,offset:.62}];if(t.animate(a,{duration:zx,easing:gc}).currentTime=e,n)return;const i=t.querySelector(".vx-pin-ico");i&&(i.animate([{opacity:0,transform:"translateY(-9px) rotate(-28deg) scale(.6)"},{opacity:0,transform:"translateY(-9px) rotate(-28deg) scale(.6)",offset:.15},{opacity:1,transform:"translateY(1px) rotate(6deg) scale(1.12)",offset:.6},{opacity:1,transform:"none"}],{duration:700,easing:"cubic-bezier(.3,1.4,.5,1)"}).currentTime=Math.min(e,700))}function PO(t){t.querySelector(".vx-pins .vx-sec-count")?.animate([{transform:"none"},{transform:"scale(1.35)",color:"var(--accent)",offset:.35},{transform:"none"}],{duration:520,easing:gc})}let KT=0,ZT=0;function Ja(){const t=KT-performance.now();if(t>0){clearTimeout(ZT),ZT=window.setTimeout(Ja,t+20);return}for(const e of Array.from(qp))e.host.isConnected?e.render():qp.delete(e)}class JT{constructor(e,n){this.hoverTimer=0,this.hoverPath=null,this.focusKey=null,this.drawn=!1,this.shownNote=null,this.dragKeys=[],this.pinCount=-1,this.pinGhosts=[],this.host=e,this.opts=n,e.classList.add("vx-treehost"),qp.add(this),e.addEventListener("pointerdown",a=>this.onPress(a)),this.render()}render(){const e=this.host.scrollTop,n=Hb(this.host,!0),a=n?n.scrollTop:0,i=document.activeElement;i&&this.host.contains(i)&&i.dataset.key&&(this.focusKey=i.dataset.key);const o=this.drawn?CO(this.host):null;this.host.innerHTML="",this.opts.showPins&&this.host.appendChild(this.pinSection()),this.host.appendChild(this.folderSection()),this.host.scrollTop=e,n&&(n.scrollTop=a),o&&this.opts.showPins&&this.pinDepartures(o),o&&LO(this.host,o),this.opts.showPins&&this.pinArrivals(),this.drawn=!0;const s=this.focusKey?this.host.querySelector(`[data-key="${CSS.escape(this.focusKey)}"]`):null;if(s&&i&&!this.host.contains(i)&&document.activeElement===document.body&&s.focus(),this.roving(),GN()&&this.dragKeys.length)for(const r of this.dragKeys)this.host.querySelector(`[data-key="${CSS.escape(r)}"]`)?.classList.add("vx-dragsrc");if(N.note&&N.note!==this.shownNote&&this.opts.showNotes){const r=this.host.querySelector(`.vx-nrow[data-path="${CSS.escape(N.note)}"]`);r&&r.offsetParent!==null&&(this.shownNote=N.note,requestAnimationFrame(()=>this.reveal(r,!1)))}}reveal(e,n){const a=Hb(e);if(a){const i=a.getBoundingClientRect(),o=e.getBoundingClientRect(),s=48;o.top<i.top+s?a.scrollTop-=i.top+s-o.top:o.bottom>i.bottom-s&&(a.scrollTop+=o.bottom-(i.bottom-s))}n&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches&&e.animate([{backgroundColor:"color-mix(in srgb, var(--accent) 30%, transparent)"},{backgroundColor:"color-mix(in srgb, var(--accent) 30%, transparent)",offset:.4},{backgroundColor:"transparent"}],{duration:1200,easing:gc})}pinDepartures(e){const n=this.host.querySelector(".vx-pin-list"),a=window.matchMedia("(prefers-reduced-motion: reduce)").matches;for(const[i,o]of Array.from(e)){if(!i.startsWith("pin:")||this.host.querySelector(`[data-key="${CSS.escape(i)}"]`)||(e.delete(i),a||!n||this.pinGhosts.length>=6))continue;const s=o.el,r=s.parentElement?Array.from(s.parentElement.children).indexOf(s):-1;s.removeAttribute("data-key"),s.removeAttribute("role"),s.setAttribute("aria-hidden","true"),s.inert=!0,s.classList.remove("active"),Object.assign(s.style,{overflow:"hidden",pointerEvents:"none"});const l=o.height+"px",c={el:s,at:r<0?1e9:r};this.pinGhosts.push(c);const d=s.animate([{opacity:1,transform:"none",height:l,minHeight:l},{opacity:0,transform:"translateX(-14px)",height:l,minHeight:l,offset:.55},{opacity:0,transform:"translateX(-14px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px"}],{duration:420,easing:"ease-in-out",fill:"forwards"});d.onfinish=()=>{s.remove(),this.pinGhosts=this.pinGhosts.filter(p=>p!==c)}}if(n)for(const i of this.pinGhosts.slice().sort((o,s)=>o.at-s.at))n.insertBefore(i.el,n.children[i.at]||null)}pinArrivals(){const e=Ol(),n=this.pinCount>=0&&e.length>this.pinCount;this.pinCount=e.length;const a=window.matchMedia("(prefers-reduced-motion: reduce)").matches;n&&!a&&PO(this.host);for(const i of e){const o=BR(i);if(o<0)continue;const s=this.host.querySelector(`.vx-pin[data-key="${CSS.escape("pin:"+i.kind+":"+i.key)}"]`);s&&RO(s,o,a)}}pinSection(){const e=Ol(),n=re("section","vx-sec vx-pins");n.classList.toggle("folded",!Zn.pins),n.innerHTML=`<header class="vx-sec-head vx-fold"><span class="vx-sec-title">${me.pin}<span>Pinned</span><span class="vx-sec-count">${e.length}</span></span><span class="vx-fold-caret">${me.caret}</span></header>`,YT(n.querySelector("header"),Zn.pins,()=>iy({pins:!Zn.pins}));const a=re("div","vx-pin-list");a.setAttribute("role","list"),e.forEach((s,r)=>a.appendChild(this.pinRow(s,r))),n.appendChild(jT(a,Zn.pins)),n.appendChild(re("div","vx-pin-empty"+(e.length?" slim":""),e.length?`${me.pin}Drag a note here to pin it`:"Drag notes or folders here to pin them"));const i=s=>{const r=Array.from(a.querySelectorAll(".vx-pin"));for(let l=0;l<r.length;l++){const c=r[l].getBoundingClientRect();if(s<c.top+c.height/2)return l}return r.length},o=s=>{const r=Array.from(a.querySelectorAll(".vx-pin"));r.forEach(c=>c.classList.remove("vx-drop-before","vx-drop-after"));const l=i(s);r.length&&(l<r.length?r[l].classList.add("vx-drop-before"):r[r.length-1].classList.add("vx-drop-after"))};return n.ondragover=s=>{Yi.cur&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect=Yi.cur.kind==="pin"?"move":"link"),n.classList.add("vx-drop-zone"),o(s.clientY))},n.ondragleave=s=>{n.contains(s.relatedTarget)||(n.classList.remove("vx-drop-zone"),n.querySelectorAll(".vx-drop-before,.vx-drop-after").forEach(r=>r.classList.remove("vx-drop-before","vx-drop-after")))},n.ondrop=s=>{const r=Yi.cur;if(!r)return;s.preventDefault();const l=i(s.clientY);hp(),this.dropOnPins(r,l)},n}pinRow(e,n){const a=e.kind==="note",i=!!e.missing,o=re("div","vx-pin"+(i?" missing":""));o.setAttribute("role","listitem"),o.tabIndex=-1,o.dataset.key="pin:"+e.kind+":"+e.key,o.dataset.nav="1",o.dataset.pin=String(n);const s=En(a?Be(e.key):e.key);(a?N.note===e.key:Ge.folder===e.key&&N.page==="vault"&&!N.note)&&o.classList.add("active");const l=a?lt(e.key):ct(e.key),c=i?'<span class="vx-pin-sub vx-pin-miss">Not found</span>':a?"":`<span class="vx-pin-sub">${x(Be(e.key)||"")}</span>`;o.innerHTML=`<span class="vx-pin-ico" style="color:${C(s)}">${a?me.note:Bi(Io(e.key),!1)}</span><span class="vx-pin-name" title="${C(i?e.key+" (not found)":e.key)}">${x(l)}</span>${c}<button class="vx-pin-x" aria-label="${i?"Remove pin":"Unpin"} ${C(l)}" title="${i?"Remove pin":"Unpin"}">${me.close}</button>`;const d=()=>{i||(a?nt.openNote(e.key):nt.selectFolder(e.key))};o.onclick=h=>{h.target.closest(".vx-pin-x")||d()};const p=()=>{if(!i){tT(e,()=>{});return}Uu(e),gt(`Removed the pin of "${l}"`,()=>mr(e,n),"info",4e3)};return o.querySelector(".vx-pin-x").onclick=h=>{h.stopPropagation(),p()},o.onkeydown=h=>{h.key==="Enter"?d():h.key==="Delete"||h.key==="Backspace"?p():(h.key==="ArrowUp"||h.key==="ArrowDown")&&h.altKey&&(h.preventDefault(),h.stopPropagation(),this.focusKey=o.dataset.key||null,mr(e,n+(h.key==="ArrowUp"?-1:1)),this.host.querySelector(`[data-key="${CSS.escape(o.dataset.key||"")}"]`)?.focus())},o.oncontextmenu=h=>{h.preventDefault(),a?Go([e.key],{x:h.clientX,y:h.clientY}):zs(e.key,{x:h.clientX,y:h.clientY})},o}folderSection(){const e=re("section","vx-sec vx-folders");e.classList.toggle("folded",!Zn.folders),e.innerHTML=`<header class="vx-sec-head vx-fold"><span class="vx-sec-title">${me.folder}<span>Folders</span></span>
|
|
4828
|
+
</div><p class="panel-sub" style="margin:10px 0 0">${c}</p>`}const _O='<svg class="vx-i" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="m7 4 5 5 5-5M7 20l5-5 5 5"/></svg>';function jT(t,e){const n=re("div","vx-sec-body"),a=re("div","vx-sec-inner");return a.appendChild(t),n.appendChild(a),n.inert=!e,n}function YT(t,e,n){t.setAttribute("role","button"),t.tabIndex=0,t.setAttribute("aria-expanded",String(e)),t.onclick=a=>{a.target.closest(".vx-sec-acts")||n()},t.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),n())}}window.addEventListener("memora:collapse-folders",()=>{hn.size&&(hn.clear(),Po(),Ja())});function XT(t){return Array.from(t.querySelectorAll("[data-key]")).filter(e=>e.offsetParent!==null&&e.offsetHeight>0)}function CO(t){const e=new Map;for(const n of XT(t)){const a=n.getBoundingClientRect();e.set(n.dataset.key,{top:a.top,height:a.height,el:n})}return e}const gc="cubic-bezier(.2,.8,.2,1)";function LO(t,e){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches||!e.size)return;const n=XT(t),a=new Set(n.map(l=>l.dataset.key)),i=n.filter(l=>!e.has(l.dataset.key)&&!l.dataset.key.startsWith("pin:")),o=Array.from(e.entries()).filter(([l])=>!a.has(l));if(i.length>12||o.length>12)return;const s=window.innerHeight;for(const l of n){const c=e.get(l.dataset.key);if(!c)continue;const d=l.getBoundingClientRect().top;if((d>s||d+c.height<0)&&(c.top>s||c.top+c.height<0))continue;const p=c.top-d;Math.abs(p)>1&&l.animate([{transform:`translateY(${p}px)`},{transform:"none"}],{duration:280,easing:gc})}for(const l of i)l.animate([{opacity:0,transform:"translateX(-10px)",backgroundColor:"var(--accent-soft)"},{opacity:1,transform:"none",backgroundColor:"var(--accent-soft)",offset:.45},{opacity:1,transform:"none",backgroundColor:"transparent"}],{duration:900,easing:gc});if(!o.length)return;getComputedStyle(t).position==="static"&&(t.style.position="relative");const r=t.getBoundingClientRect();for(const[,l]of o){const c=l.el;c.removeAttribute("data-key"),c.setAttribute("aria-hidden","true"),Object.assign(c.style,{position:"absolute",left:"0",right:"0",top:l.top-r.top+t.scrollTop+"px",height:l.height+"px",pointerEvents:"none",zIndex:"1"}),t.appendChild(c);const d=c.animate([{opacity:1,transform:"none"},{opacity:0,transform:"translateX(-24px)"}],{duration:320,easing:"ease-in",fill:"forwards"});d.onfinish=()=>c.remove()}}const Wp=t=>`color-mix(in srgb, var(--accent) ${t}%, transparent)`,Gp="inset 3px 0 0 var(--accent)";function RO(t,e,n){const a=n?[{backgroundColor:Wp(20),boxShadow:Gp},{backgroundColor:Wp(14),boxShadow:Gp,offset:.6}]:[{opacity:0,transform:"translateY(-8px) scale(.97)",backgroundColor:Wp(26),boxShadow:Gp},{opacity:1,transform:"none",backgroundColor:Wp(22),boxShadow:Gp,offset:.2},{backgroundColor:Wp(14),boxShadow:Gp,offset:.62}];if(t.animate(a,{duration:zx,easing:gc}).currentTime=e,n)return;const i=t.querySelector(".vx-pin-ico");i&&(i.animate([{opacity:0,transform:"translateY(-9px) rotate(-28deg) scale(.6)"},{opacity:0,transform:"translateY(-9px) rotate(-28deg) scale(.6)",offset:.15},{opacity:1,transform:"translateY(1px) rotate(6deg) scale(1.12)",offset:.6},{opacity:1,transform:"none"}],{duration:700,easing:"cubic-bezier(.3,1.4,.5,1)"}).currentTime=Math.min(e,700))}function PO(t){t.querySelector(".vx-pins .vx-sec-count")?.animate([{transform:"none"},{transform:"scale(1.35)",color:"var(--accent)",offset:.35},{transform:"none"}],{duration:520,easing:gc})}let KT=0,ZT=0;function Ja(){const t=KT-performance.now();if(t>0){clearTimeout(ZT),ZT=window.setTimeout(Ja,t+20);return}for(const e of Array.from(qp))e.host.isConnected?e.render():qp.delete(e)}class JT{constructor(e,n){this.hoverTimer=0,this.hoverPath=null,this.focusKey=null,this.drawn=!1,this.shownNote=null,this.dragKeys=[],this.pinCount=-1,this.pinGhosts=[],this.host=e,this.opts=n,e.classList.add("vx-treehost"),qp.add(this),e.addEventListener("pointerdown",a=>this.onPress(a)),this.render()}render(){const e=this.host.scrollTop,n=Hb(this.host,!0),a=n?n.scrollTop:0,i=document.activeElement;i&&this.host.contains(i)&&i.dataset.key&&(this.focusKey=i.dataset.key);const o=this.drawn?CO(this.host):null;this.host.innerHTML="",this.opts.showPins&&this.host.appendChild(this.pinSection()),this.host.appendChild(this.folderSection()),this.host.scrollTop=e,n&&(n.scrollTop=a),o&&this.opts.showPins&&this.pinDepartures(o),o&&LO(this.host,o),this.opts.showPins&&this.pinArrivals(),this.drawn=!0;const s=this.focusKey?this.host.querySelector(`[data-key="${CSS.escape(this.focusKey)}"]`):null;if(s&&i&&!this.host.contains(i)&&document.activeElement===document.body&&s.focus(),this.roving(),GN()&&this.dragKeys.length)for(const r of this.dragKeys)this.host.querySelector(`[data-key="${CSS.escape(r)}"]`)?.classList.add("vx-dragsrc");if(N.note&&N.note!==this.shownNote&&this.opts.showNotes){const r=this.host.querySelector(`.vx-nrow[data-path="${CSS.escape(N.note)}"]`);r&&r.offsetParent!==null&&(this.shownNote=N.note,requestAnimationFrame(()=>this.reveal(r,!1)))}}reveal(e,n){const a=Hb(e);if(a){const i=a.getBoundingClientRect(),o=e.getBoundingClientRect(),s=48;o.top<i.top+s?a.scrollTop-=i.top+s-o.top:o.bottom>i.bottom-s&&(a.scrollTop+=o.bottom-(i.bottom-s))}n&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches&&e.animate([{backgroundColor:"color-mix(in srgb, var(--accent) 30%, transparent)"},{backgroundColor:"color-mix(in srgb, var(--accent) 30%, transparent)",offset:.4},{backgroundColor:"transparent"}],{duration:1200,easing:gc})}pinDepartures(e){const n=this.host.querySelector(".vx-pin-list"),a=window.matchMedia("(prefers-reduced-motion: reduce)").matches;for(const[i,o]of Array.from(e)){if(!i.startsWith("pin:")||this.host.querySelector(`[data-key="${CSS.escape(i)}"]`)||(e.delete(i),a||!n||this.pinGhosts.length>=6))continue;const s=o.el,r=s.parentElement?Array.from(s.parentElement.children).indexOf(s):-1;s.removeAttribute("data-key"),s.removeAttribute("role"),s.setAttribute("aria-hidden","true"),s.inert=!0,s.classList.remove("active"),Object.assign(s.style,{overflow:"hidden",pointerEvents:"none"});const l=o.height+"px",c={el:s,at:r<0?1e9:r};this.pinGhosts.push(c);const d=s.animate([{opacity:1,transform:"none",height:l,minHeight:l},{opacity:0,transform:"translateX(-14px)",height:l,minHeight:l,offset:.55},{opacity:0,transform:"translateX(-14px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px"}],{duration:420,easing:"ease-in-out",fill:"forwards"});d.onfinish=()=>{s.remove(),this.pinGhosts=this.pinGhosts.filter(p=>p!==c)}}if(n)for(const i of this.pinGhosts.slice().sort((o,s)=>o.at-s.at))n.insertBefore(i.el,n.children[i.at]||null)}pinArrivals(){const e=Ol(),n=this.pinCount>=0&&e.length>this.pinCount;this.pinCount=e.length;const a=window.matchMedia("(prefers-reduced-motion: reduce)").matches;n&&!a&&PO(this.host);for(const i of e){const o=BR(i);if(o<0)continue;const s=this.host.querySelector(`.vx-pin[data-key="${CSS.escape("pin:"+i.kind+":"+i.key)}"]`);s&&RO(s,o,a)}}pinSection(){const e=Ol(),n=re("section","vx-sec vx-pins");n.classList.toggle("folded",!Zn.pins),n.innerHTML=`<header class="vx-sec-head vx-fold"><span class="vx-sec-title">${me.pin}<span>Pinned</span><span class="vx-sec-count">${e.length}</span></span><span class="vx-fold-caret">${me.caret}</span></header>`,YT(n.querySelector("header"),Zn.pins,()=>iy({pins:!Zn.pins}));const a=re("div","vx-pin-list");a.setAttribute("role","list"),e.forEach((s,r)=>a.appendChild(this.pinRow(s,r))),n.appendChild(jT(a,Zn.pins)),n.appendChild(re("div","vx-pin-empty"+(e.length?" slim":""),e.length?`${me.pin}Drag a note here to pin it`:"Drag notes or folders here to pin them"));const i=s=>{const r=Array.from(a.querySelectorAll(".vx-pin"));for(let l=0;l<r.length;l++){const c=r[l].getBoundingClientRect();if(s<c.top+c.height/2)return l}return r.length},o=s=>{const r=Array.from(a.querySelectorAll(".vx-pin"));r.forEach(c=>c.classList.remove("vx-drop-before","vx-drop-after"));const l=i(s);r.length&&(l<r.length?r[l].classList.add("vx-drop-before"):r[r.length-1].classList.add("vx-drop-after"))};return n.ondragover=s=>{Yi.cur&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect=Yi.cur.kind==="pin"?"move":"link"),n.classList.add("vx-drop-zone"),o(s.clientY))},n.ondragleave=s=>{n.contains(s.relatedTarget)||(n.classList.remove("vx-drop-zone"),n.querySelectorAll(".vx-drop-before,.vx-drop-after").forEach(r=>r.classList.remove("vx-drop-before","vx-drop-after")))},n.ondrop=s=>{const r=Yi.cur;if(!r)return;s.preventDefault();const l=i(s.clientY);hp(),this.dropOnPins(r,l)},n}pinRow(e,n){const a=e.kind==="note",i=!!e.missing,o=re("div","vx-pin"+(i?" missing":""));o.setAttribute("role","listitem"),o.tabIndex=-1,o.dataset.key="pin:"+e.kind+":"+e.key,o.dataset.nav="1",o.dataset.pin=String(n);const s=En(a?Be(e.key):e.key);(a?N.note===e.key:Ge.folder===e.key&&N.page==="vault"&&!N.note)&&o.classList.add("active");const l=a?lt(e.key):ct(e.key),c=i?'<span class="vx-pin-sub vx-pin-miss">Not found</span>':a?"":`<span class="vx-pin-sub">${x(Be(e.key)||"")}</span>`;o.innerHTML=`<span class="vx-pin-ico" style="color:${C(s)}">${a?me.note:Bi(Io(e.key),!1)}</span><span class="vx-pin-name" title="${C(i?e.key+" (not found)":e.key)}">${x(l)}</span>${c}<button class="vx-pin-x" aria-label="${i?"Remove pin":"Unpin"} ${C(l)}" title="${i?"Remove pin":"Unpin"}">${me.close}</button>`;const d=()=>{i||(a?nt.openNote(e.key):nt.selectFolder(e.key))};o.onclick=h=>{h.target.closest(".vx-pin-x")||d()};const p=()=>{if(!i){tT(e,()=>{});return}Uu(e),gt(`Removed the pin of "${l}"`,()=>mr(e,n),"info",4e3)};return o.querySelector(".vx-pin-x").onclick=h=>{h.stopPropagation(),p()},o.onkeydown=h=>{h.key==="Enter"?d():h.key==="Delete"||h.key==="Backspace"?p():(h.key==="ArrowUp"||h.key==="ArrowDown")&&h.altKey&&(h.preventDefault(),h.stopPropagation(),this.focusKey=o.dataset.key||null,mr(e,n+(h.key==="ArrowUp"?-1:1)),this.host.querySelector(`[data-key="${CSS.escape(o.dataset.key||"")}"]`)?.focus())},o.oncontextmenu=h=>{h.preventDefault(),a?Go([e.key],{x:h.clientX,y:h.clientY}):zs(e.key,{x:h.clientX,y:h.clientY})},o}folderSection(){const e=re("section","vx-sec vx-folders");e.classList.toggle("folded",!Zn.folders),e.innerHTML=`<header class="vx-sec-head vx-fold"><span class="vx-sec-title">${me.folder}<span>Folders</span></span>
|
|
4815
4829
|
<span class="vx-sec-acts">
|
|
4816
4830
|
<button class="vx-icon-btn" data-act="note" title="New note" aria-label="New note">${me.newNote}</button>
|
|
4817
4831
|
<button class="vx-icon-btn" data-act="folder" title="New folder" aria-label="New folder">${me.newFolder}</button>
|
|
4818
4832
|
<button class="vx-icon-btn" data-act="collapse" title="Close all subfolders" aria-label="Close all subfolders">${_O}</button>
|
|
4819
|
-
</span><span class="vx-fold-caret">${me.caret}</span></header>`,e.querySelector("[data-act=note]").onclick=()=>nt.newNote(""),e.querySelector("[data-act=folder]").onclick=()=>nt.newFolder(""),e.querySelector("[data-act=collapse]").onclick=()=>this.collapseAll(),YT(e.querySelector("header"),Zn.folders,()=>iy({folders:!Zn.folders}));const n=re("div","vx-tree");n.setAttribute("role","tree"),n.setAttribute("aria-label","Folders"),n.setAttribute("aria-multiselectable","true");const a=Du();n.appendChild(this.folderRow(a));const i=re("div","vx-kids open");i.setAttribute("role","group");const o=VT(1);for(const s of a.children)o.appendChild(this.folderBranch(s));if(this.opts.showNotes)for(const s of a.notes)o.appendChild(this.noteRow(s,1));return i.appendChild(o),n.appendChild(i),n.onkeydown=s=>this.onKey(s),e.appendChild(jT(n,Zn.folders)),e}folderBranch(e){const n=re("div","vx-branch");n.appendChild(this.folderRow(e));const a=
|
|
4833
|
+
</span><span class="vx-fold-caret">${me.caret}</span></header>`,e.querySelector("[data-act=note]").onclick=()=>nt.newNote(""),e.querySelector("[data-act=folder]").onclick=()=>nt.newFolder(""),e.querySelector("[data-act=collapse]").onclick=()=>this.collapseAll(),YT(e.querySelector("header"),Zn.folders,()=>iy({folders:!Zn.folders}));const n=re("div","vx-tree");n.setAttribute("role","tree"),n.setAttribute("aria-label","Folders"),n.setAttribute("aria-multiselectable","true");const a=Du();n.appendChild(this.folderRow(a));const i=re("div","vx-kids open");i.setAttribute("role","group");const o=VT(1);for(const s of a.children)o.appendChild(this.folderBranch(s));if(this.opts.showNotes)for(const s of a.notes)o.appendChild(this.noteRow(s,1));return i.appendChild(o),n.appendChild(i),n.onkeydown=s=>this.onKey(s),e.appendChild(jT(n,Zn.folders)),e}folderBranch(e){const n=re("div","vx-branch");n.appendChild(this.folderRow(e));const a=hn.has(e.path),i=re("div","vx-kids"+(a?" open":""));return i.setAttribute("role","group"),a&&this.fillKids(i,e),n.appendChild(i),n}fillKids(e,n){const a=VT(n.depth+1);for(const i of n.children)a.appendChild(this.folderBranch(i));if(this.opts.showNotes)for(const i of n.notes)a.appendChild(this.noteRow(i,n.depth+1));if(!a.childElementCount){const i=n.notes.length?"No subfolders":"Empty folder",o=re("div","vx-row vx-tempty",`<span class="vx-twist none"></span>${oy(n.depth+1)}<span class="vx-fname">${i}</span>`);o.style.setProperty("--depth",String(Rf(n.depth+1))),a.appendChild(o)}e.innerHTML="",e.appendChild(a)}folderRow(e){const n=e.path==="",a=n||hn.has(e.path),i=e.children.length>0||this.opts.showNotes&&e.notes.length>0,o=re("div","vx-row vx-frow"+(n?" root":""));o.setAttribute("role","treeitem"),o.setAttribute("aria-level",String(e.depth+1)),n||o.setAttribute("aria-expanded",String(a)),o.tabIndex=-1,o.dataset.key="f:"+e.path,o.dataset.folder=e.path,o.dataset.nav="1",o.style.setProperty("--depth",String(Rf(e.depth))),o.classList.toggle("deep",Pf(e.depth));const s=En(e.path);o.style.setProperty("--fc",s);const r=N.page==="vault"&&(Ge.folder||"")===e.path;o.classList.toggle("sel",r),o.setAttribute("aria-selected",String(r));const l=e.total?NS(e.path,!0):[];return o.innerHTML=`<span class="vx-twist${n?" none":""}" aria-hidden="true">${me.caret}</span>
|
|
4820
4834
|
${oy(e.depth)}<span class="vx-fico">${n?me.vault:Bi(Io(e.path),a)}</span>
|
|
4821
4835
|
<span class="vx-fname"${n?"":` title="${C(e.path)}"`}>${x(n?Tt:e.name)}</span>${n?"":am("folder",e.path)}
|
|
4822
4836
|
${HT(l)}
|
|
4823
|
-
<span class="vx-end"><span class="vx-count">${e.total}</span>${GT(n?Tt:e.name)}</span>`,o.onclick=c=>{const d=c.target;if(d.closest(".vx-row-more")){c.stopPropagation(),zs(e.path,d.closest(".vx-row-more"),()=>this.renameFolderInline(o,e.path));return}if(d.closest(".vx-twist")){this.toggle(e.path);return}n||this.toggle(e.path),nt.selectFolder(e.path)},o.ondblclick=c=>{n||c.target.closest(".vx-twist,.vx-row-more")||(c.preventDefault(),this.renameFolderInline(o,e.path))},o.oncontextmenu=c=>{c.preventDefault(),zs(e.path,{x:c.clientX,y:c.clientY},()=>this.renameFolderInline(o,e.path))},this.wireDrop(o,e.path,i&&!n),o}wireDrop(e,n,a){const i=()=>{const o=Yi.cur;return o?o.kind==="notes"?o.paths.some(s=>Be(s)!==n):o.kind==="folder"?!Fi(n,o.path)&&Be(o.path)!==n:o.kind==="pin"?(o.item.kind==="note"||!Fi(n,o.item.key))&&Be(o.item.key)!==n:!1:!1};e.ondragover=o=>{if(!i()){o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}o.preventDefault(),o.stopPropagation(),o.dataTransfer&&(o.dataTransfer.dropEffect="move"),e.classList.contains("vx-drop-into")||(this.host.querySelectorAll(".vx-drop-into").forEach(s=>s.classList.remove("vx-drop-into")),e.classList.add("vx-drop-into")),a&&!pn.has(n)&&this.hoverPath!==n&&(this.hoverPath=n,clearTimeout(this.hoverTimer),this.hoverTimer=window.setTimeout(()=>{this.hoverPath===n&&Yi.cur&&this.toggle(n,!0)},650))},e.ondragleave=o=>{e.contains(o.relatedTarget)||(e.classList.remove("vx-drop-into"),this.hoverPath===n&&(this.hoverPath=null,clearTimeout(this.hoverTimer)))},e.ondrop=o=>{const s=Yi.cur;!s||!i()||(o.preventDefault(),o.stopPropagation(),hp(),this.hoverPath=null,clearTimeout(this.hoverTimer),this.confirmMove(s,n))}}noteRow(e,n){const a=re("div","vx-row vx-nrow");a.setAttribute("role","treeitem"),a.setAttribute("aria-level",String(n+1)),a.tabIndex=-1,a.dataset.key="n:"+e.path,a.dataset.path=e.path,a.dataset.nav="1",a.style.setProperty("--depth",String(Rf(n))),a.classList.toggle("deep",Pf(n)),a.style.setProperty("--fc",En(Be(e.path)));const i=N.note===e.path;return a.classList.toggle("active",i),a.classList.toggle("sel",Je.has(e.path)),a.setAttribute("aria-selected",String(i||Je.has(e.path))),a.innerHTML=`<span class="vx-twist none"></span>${oy(n)}<span class="vx-nico">${me.note}</span><span class="vx-fname" title="${C(e.path)}">${x(lt(e.path))}</span>${am("node",e.path)}${HT(NS(e.path),!0)}<span class="vx-end">${GT(lt(e.path))}</span>`,a.onclick=o=>{const s=o.target.closest(".vx-row-more");if(s){o.stopPropagation();const r=Je.has(e.path)&&Je.size>1?Array.from(Je):[e.path];Go(r,s,()=>this.renameNoteInline(a,e.path));return}if(o.metaKey||o.ctrlKey){Je.has(e.path)?Je.delete(e.path):Je.add(e.path),a.classList.toggle("sel",Je.has(e.path));return}Je.clear(),nt.openNote(e.path)},a.ondblclick=o=>{o.target.closest(".vx-row-more")||(o.preventDefault(),this.renameNoteInline(a,e.path))},a.oncontextmenu=o=>{o.preventDefault();const s=Je.has(e.path)&&Je.size>1?Array.from(Je):[e.path];Go(s,{x:o.clientX,y:o.clientY},()=>this.renameNoteInline(a,e.path))},a}onPress(e){const n=e.target;if(n.closest(".vx-row-more,.vx-pin-x,input,textarea,button"))return;const a=n.closest(".vx-frow[data-folder],.vx-nrow[data-path],.vx-pin[data-pin]");!a||!this.host.contains(a)||a.dataset.folder===""||a.classList.contains("missing")||VN(e,()=>this.dragSpec(a))}dragSpec(e){let n,a;if(e.dataset.folder)n={kind:"folder",path:e.dataset.folder},a=Bi(Io(e.dataset.folder),!1);else if(e.dataset.path){const i=e.dataset.path;n={kind:"notes",paths:Je.has(i)&&Je.size>1?Array.from(Je):[i]},a=me.note}else{const i=Ol()[Number(e.dataset.pin)];if(!i||i.missing)return null;n={kind:"pin",id:e.dataset.key||"",item:{kind:i.kind,key:i.key}},a=i.kind==="note"?me.note:Bi(Io(i.key),!1)}this.dragKeys=n.kind==="notes"?n.paths.map(i=>"n:"+i):[e.dataset.key||""];for(const i of this.dragKeys)this.host.querySelector(`[data-key="${CSS.escape(i)}"]`)?.classList.add("vx-dragsrc");return{payload:n,source:e,icon:a,scroller:()=>Hb(this.host,!0),targetAt:(i,o)=>this.targetAt(i,o),canOpen:i=>{if(i.kind!=="folder"||pn.has(i.path))return null;const o=Nl(i.path);return o&&(o.children.length||this.opts.showNotes&&o.notes.length)?i.path:null},open:i=>this.toggle(i,!0),drop:(i,o)=>{i.kind==="pins"?this.dropOnPins(n,i.index):this.confirmMove(n,o.dest)},held:(i,o)=>e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:i,clientY:o}))}}targetAt(e,n){const a=document.elementFromPoint(e,n);if(!a)return null;const i=a.closest(".vx-treehost .vx-pins");if(i){const c=Array.from(i.querySelectorAll(".vx-pin[data-pin]"));let d=c.length;for(let p=0;p<c.length;p++){const h=c[p].getBoundingClientRect();if(n<h.top+h.height/2){d=p;break}}return{target:{kind:"pins",index:d},el:i}}const o=a.closest(".vx-treehost .vx-frow[data-folder]");if(o){const c=o.dataset.folder||"";return{target:c?{kind:"folder",path:c}:{kind:"root"},el:o}}const s=a.closest(".vx-treehost .vx-nrow[data-path]");if(s)return{target:{kind:"note",path:s.dataset.path},el:s};const r=a.closest("[data-drop-folder]");if(r){const c=r.dataset.dropFolder||"";return{target:c?{kind:"folder",path:c}:{kind:"root"},el:r}}const l=a.closest(".vx-treehost .vx-folders");return l?{target:{kind:"root"},el:l.querySelector(".vx-frow.root")}:null}dropOnPins(e,n){if(e.kind==="pin"){const a=Ol().findIndex(i=>i.kind===e.item.kind&&i.key===e.item.key);mr(e.item,a>=0&&a<n?n-1:n)}else e.kind==="notes"?e.paths.forEach((a,i)=>mr({kind:"note",key:a},n+i)):mr({kind:"folder",key:e.path},n)}confirmMove(e,n){EA(e,n===""?{kind:"root"}:{kind:"folder",path:n}).ok&&ue.open({title:ON(e,n),body:EO(e,n),actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Move",cls:"primary",run:async()=>{ue.close(),await this.doMove(e,n)}}]})}async doMove(e,n){const a=e.kind==="notes"?e.paths:e.kind==="pin"&&e.item.kind==="note"?[e.item.key]:null;for(let s=n;s;s=Be(s))pn.add(s);if(Po(),a){const s=await T0(a,n);if(!s.length)return;Je.clear(),s.forEach(r=>Je.add(r.to)),Ja(),this.revealLater("n:"+s[0].to);return}const i=e.kind==="folder"?e.path:e.kind==="pin"?e.item.key:"",o=(n?n+"/":"")+ct(i);await E0(i,o,"Moved")&&this.revealLater("f:"+o)}revealLater(e){setTimeout(()=>{for(const n of Array.from(qp)){const a=n.host.querySelector(`[data-key="${CSS.escape(e)}"]`);a&&a.offsetParent!==null&&n.reveal(a,!0)}},380)}collapseAll(){const e=Array.from(this.host.querySelectorAll(".vx-frow[aria-expanded=true][data-folder]")).filter(i=>i.dataset.folder&&pn.has(i.dataset.folder)&&i.offsetParent!==null).reverse(),n=new Set(e.map(i=>i.dataset.folder));for(const i of Array.from(pn))n.has(i)||pn.delete(i);Po();const a=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;e.forEach((i,o)=>{const s=()=>{this.toggle(i.dataset.folder,!1),i.classList.remove("vx-zoop"),i.offsetWidth,i.classList.add("vx-zoop"),setTimeout(()=>i.classList.remove("vx-zoop"),420)};a?s():setTimeout(s,o*75)})}toggle(e,n){const a=n??!pn.has(e);a?pn.add(e):pn.delete(e),Po(),KT=performance.now()+340;for(const i of Array.from(qp))i.animate(e,a)}animate(e,n){const a=this.host.querySelector(`.vx-frow[data-folder="${CSS.escape(e)}"]`);if(!a)return;const i=a.nextElementSibling;if(!i||!i.classList.contains("vx-kids"))return;const o=Nl(e);a.setAttribute("aria-expanded",String(n));const s=a.querySelector(".vx-fico");s&&o&&(s.innerHTML=Bi(Io(e),n));const r=()=>{i.style.height="",i.removeEventListener("transitionend",r)};if(n){!i.firstElementChild&&o&&this.fillKids(i,o),i.style.height="0px",i.classList.add("open");const l=i.scrollHeight;requestAnimationFrame(()=>{i.style.height=l+"px"}),i.addEventListener("transitionend",r),setTimeout(r,320),window.matchMedia("(prefers-reduced-motion: reduce)").matches||Array.from(i.firstElementChild?.children||[]).slice(0,12).forEach((d,p)=>d.animate([{opacity:0,transform:"translateY(-6px)"},{opacity:1,transform:"none"}],{duration:260,delay:30+p*22,easing:gc,fill:"backwards"}))}else i.style.height=i.scrollHeight+"px",requestAnimationFrame(()=>{i.style.height="0px",i.classList.remove("open")}),i.addEventListener("transitionend",r),setTimeout(r,320);this.roving()}async renameFolderInline(e,n){const a=e.querySelector(".vx-fname");if(!a)return;const i=await Yu(a,ct(n));i&&await X3(n,i)}async renameNoteInline(e,n){const a=e.querySelector(".vx-fname");if(!a)return;const i=await Yu(a,or(ct(n).replace(/\.md$/i,"")));i&&await nm(n,i)}visibleRows(){return Array.from(this.host.querySelectorAll("[data-nav]")).filter(e=>!e.closest(".vx-kids:not(.open)"))}roving(){const e=this.visibleRows();if(!e.length)return;const n=e.find(a=>a.dataset.key===this.focusKey)||e.find(a=>a.classList.contains("sel")||a.classList.contains("active"))||e.find(a=>a.classList.contains("vx-frow"))||e[0];e.forEach(a=>a.tabIndex=a===n?0:-1)}onKey(e){const n=e.target.closest("[data-nav]");if(!n||e.target.tagName==="INPUT")return;const a=this.visibleRows(),i=a.indexOf(n),o=n.dataset.folder,s=n.dataset.path,r=l=>{l&&(a.forEach(c=>c.tabIndex=-1),l.tabIndex=0,this.focusKey=l.dataset.key||null,l.focus())};switch(e.key){case"ArrowDown":e.preventDefault(),r(a[i+1]);return;case"ArrowUp":e.preventDefault(),r(a[i-1]);return;case"Home":e.preventDefault(),r(a[0]);return;case"End":e.preventDefault(),r(a[a.length-1]);return;case"ArrowRight":o!=null&&o!==""&&(e.preventDefault(),n.getAttribute("aria-expanded")==="false"?this.toggle(o,!0):r(a[i+1]));return;case"ArrowLeft":{if(e.preventDefault(),o&&n.getAttribute("aria-expanded")==="true"){this.toggle(o,!1);return}const l=o!=null?Be(o):Be(s||"");if(o==="")return;r(this.host.querySelector(`.vx-frow[data-folder="${CSS.escape(l)}"]`)||void 0);return}case"Enter":case" ":e.preventDefault(),o!=null?nt.selectFolder(o):s&&nt.openNote(s);return;case"F2":e.preventDefault(),o?this.renameFolderInline(n,o):s&&this.renameNoteInline(n,s);return;case"Delete":e.preventDefault(),o?_p(o):s&&dc(Je.size>1&&Je.has(s)?Array.from(Je):[s]);return;case"p":case"P":if(e.ctrlKey||e.metaKey||e.altKey)return;e.preventDefault(),o?Fr("folder",o):s&&Fr("note",s);return;case"n":case"N":if(e.ctrlKey||e.metaKey||e.altKey)return;e.preventDefault(),nt.newNote(o??Be(s||""));return;case"ContextMenu":e.preventDefault(),o!=null?zs(o,n,()=>{this.renameFolderInline(n,o)}):s&&Go([s],n,()=>{this.renameNoteInline(n,s)});return;case"F10":e.shiftKey&&(e.preventDefault(),o!=null?zs(o,n,()=>{this.renameFolderInline(n,o)}):s&&Go([s],n,()=>{this.renameNoteInline(n,s)}));return;default:return}}}ES(()=>Ja());function IO(t,e={}){return new JT(t,{showNotes:e.showNotes??!0,showPins:e.showPins??!0})}const NO=480,zO=2200,DO=`
|
|
4837
|
+
<span class="vx-end"><span class="vx-count">${e.total}</span>${GT(n?Tt:e.name)}</span>`,o.onclick=c=>{const d=c.target;if(d.closest(".vx-row-more")){c.stopPropagation(),zs(e.path,d.closest(".vx-row-more"),()=>this.renameFolderInline(o,e.path));return}if(d.closest(".vx-twist")){this.toggle(e.path);return}n||this.toggle(e.path),nt.selectFolder(e.path)},o.ondblclick=c=>{n||c.target.closest(".vx-twist,.vx-row-more")||(c.preventDefault(),this.renameFolderInline(o,e.path))},o.oncontextmenu=c=>{c.preventDefault(),zs(e.path,{x:c.clientX,y:c.clientY},()=>this.renameFolderInline(o,e.path))},this.wireDrop(o,e.path,i&&!n),o}wireDrop(e,n,a){const i=()=>{const o=Yi.cur;return o?o.kind==="notes"?o.paths.some(s=>Be(s)!==n):o.kind==="folder"?!Fi(n,o.path)&&Be(o.path)!==n:o.kind==="pin"?(o.item.kind==="note"||!Fi(n,o.item.key))&&Be(o.item.key)!==n:!1:!1};e.ondragover=o=>{if(!i()){o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}o.preventDefault(),o.stopPropagation(),o.dataTransfer&&(o.dataTransfer.dropEffect="move"),e.classList.contains("vx-drop-into")||(this.host.querySelectorAll(".vx-drop-into").forEach(s=>s.classList.remove("vx-drop-into")),e.classList.add("vx-drop-into")),a&&!hn.has(n)&&this.hoverPath!==n&&(this.hoverPath=n,clearTimeout(this.hoverTimer),this.hoverTimer=window.setTimeout(()=>{this.hoverPath===n&&Yi.cur&&this.toggle(n,!0)},650))},e.ondragleave=o=>{e.contains(o.relatedTarget)||(e.classList.remove("vx-drop-into"),this.hoverPath===n&&(this.hoverPath=null,clearTimeout(this.hoverTimer)))},e.ondrop=o=>{const s=Yi.cur;!s||!i()||(o.preventDefault(),o.stopPropagation(),hp(),this.hoverPath=null,clearTimeout(this.hoverTimer),this.confirmMove(s,n))}}noteRow(e,n){const a=re("div","vx-row vx-nrow");a.setAttribute("role","treeitem"),a.setAttribute("aria-level",String(n+1)),a.tabIndex=-1,a.dataset.key="n:"+e.path,a.dataset.path=e.path,a.dataset.nav="1",a.style.setProperty("--depth",String(Rf(n))),a.classList.toggle("deep",Pf(n)),a.style.setProperty("--fc",En(Be(e.path)));const i=N.note===e.path;return a.classList.toggle("active",i),a.classList.toggle("sel",Je.has(e.path)),a.setAttribute("aria-selected",String(i||Je.has(e.path))),a.innerHTML=`<span class="vx-twist none"></span>${oy(n)}<span class="vx-nico">${me.note}</span><span class="vx-fname" title="${C(e.path)}">${x(lt(e.path))}</span>${am("node",e.path)}${HT(NS(e.path),!0)}<span class="vx-end">${GT(lt(e.path))}</span>`,a.onclick=o=>{const s=o.target.closest(".vx-row-more");if(s){o.stopPropagation();const r=Je.has(e.path)&&Je.size>1?Array.from(Je):[e.path];Go(r,s,()=>this.renameNoteInline(a,e.path));return}if(o.metaKey||o.ctrlKey){Je.has(e.path)?Je.delete(e.path):Je.add(e.path),a.classList.toggle("sel",Je.has(e.path));return}Je.clear(),nt.openNote(e.path)},a.ondblclick=o=>{o.target.closest(".vx-row-more")||(o.preventDefault(),this.renameNoteInline(a,e.path))},a.oncontextmenu=o=>{o.preventDefault();const s=Je.has(e.path)&&Je.size>1?Array.from(Je):[e.path];Go(s,{x:o.clientX,y:o.clientY},()=>this.renameNoteInline(a,e.path))},a}onPress(e){const n=e.target;if(n.closest(".vx-row-more,.vx-pin-x,input,textarea,button"))return;const a=n.closest(".vx-frow[data-folder],.vx-nrow[data-path],.vx-pin[data-pin]");!a||!this.host.contains(a)||a.dataset.folder===""||a.classList.contains("missing")||VN(e,()=>this.dragSpec(a))}dragSpec(e){let n,a;if(e.dataset.folder)n={kind:"folder",path:e.dataset.folder},a=Bi(Io(e.dataset.folder),!1);else if(e.dataset.path){const i=e.dataset.path;n={kind:"notes",paths:Je.has(i)&&Je.size>1?Array.from(Je):[i]},a=me.note}else{const i=Ol()[Number(e.dataset.pin)];if(!i||i.missing)return null;n={kind:"pin",id:e.dataset.key||"",item:{kind:i.kind,key:i.key}},a=i.kind==="note"?me.note:Bi(Io(i.key),!1)}this.dragKeys=n.kind==="notes"?n.paths.map(i=>"n:"+i):[e.dataset.key||""];for(const i of this.dragKeys)this.host.querySelector(`[data-key="${CSS.escape(i)}"]`)?.classList.add("vx-dragsrc");return{payload:n,source:e,icon:a,scroller:()=>Hb(this.host,!0),targetAt:(i,o)=>this.targetAt(i,o),canOpen:i=>{if(i.kind!=="folder"||hn.has(i.path))return null;const o=Nl(i.path);return o&&(o.children.length||this.opts.showNotes&&o.notes.length)?i.path:null},open:i=>this.toggle(i,!0),drop:(i,o)=>{i.kind==="pins"?this.dropOnPins(n,i.index):this.confirmMove(n,o.dest)},held:(i,o)=>e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:i,clientY:o}))}}targetAt(e,n){const a=document.elementFromPoint(e,n);if(!a)return null;const i=a.closest(".vx-treehost .vx-pins");if(i){const c=Array.from(i.querySelectorAll(".vx-pin[data-pin]"));let d=c.length;for(let p=0;p<c.length;p++){const h=c[p].getBoundingClientRect();if(n<h.top+h.height/2){d=p;break}}return{target:{kind:"pins",index:d},el:i}}const o=a.closest(".vx-treehost .vx-frow[data-folder]");if(o){const c=o.dataset.folder||"";return{target:c?{kind:"folder",path:c}:{kind:"root"},el:o}}const s=a.closest(".vx-treehost .vx-nrow[data-path]");if(s)return{target:{kind:"note",path:s.dataset.path},el:s};const r=a.closest("[data-drop-folder]");if(r){const c=r.dataset.dropFolder||"";return{target:c?{kind:"folder",path:c}:{kind:"root"},el:r}}const l=a.closest(".vx-treehost .vx-folders");return l?{target:{kind:"root"},el:l.querySelector(".vx-frow.root")}:null}dropOnPins(e,n){if(e.kind==="pin"){const a=Ol().findIndex(i=>i.kind===e.item.kind&&i.key===e.item.key);mr(e.item,a>=0&&a<n?n-1:n)}else e.kind==="notes"?e.paths.forEach((a,i)=>mr({kind:"note",key:a},n+i)):mr({kind:"folder",key:e.path},n)}confirmMove(e,n){EA(e,n===""?{kind:"root"}:{kind:"folder",path:n}).ok&&ue.open({title:ON(e,n),body:EO(e,n),actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Move",cls:"primary",run:async()=>{ue.close(),await this.doMove(e,n)}}]})}async doMove(e,n){const a=e.kind==="notes"?e.paths:e.kind==="pin"&&e.item.kind==="note"?[e.item.key]:null;for(let s=n;s;s=Be(s))hn.add(s);if(Po(),a){const s=await T0(a,n);if(!s.length)return;Je.clear(),s.forEach(r=>Je.add(r.to)),Ja(),this.revealLater("n:"+s[0].to);return}const i=e.kind==="folder"?e.path:e.kind==="pin"?e.item.key:"",o=(n?n+"/":"")+ct(i);await E0(i,o,"Moved")&&this.revealLater("f:"+o)}revealLater(e){setTimeout(()=>{for(const n of Array.from(qp)){const a=n.host.querySelector(`[data-key="${CSS.escape(e)}"]`);a&&a.offsetParent!==null&&n.reveal(a,!0)}},380)}collapseAll(){const e=Array.from(this.host.querySelectorAll(".vx-frow[aria-expanded=true][data-folder]")).filter(i=>i.dataset.folder&&hn.has(i.dataset.folder)&&i.offsetParent!==null).reverse(),n=new Set(e.map(i=>i.dataset.folder));for(const i of Array.from(hn))n.has(i)||hn.delete(i);Po();const a=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;e.forEach((i,o)=>{const s=()=>{this.toggle(i.dataset.folder,!1),i.classList.remove("vx-zoop"),i.offsetWidth,i.classList.add("vx-zoop"),setTimeout(()=>i.classList.remove("vx-zoop"),420)};a?s():setTimeout(s,o*75)})}toggle(e,n){const a=n??!hn.has(e);a?hn.add(e):hn.delete(e),Po(),KT=performance.now()+340;for(const i of Array.from(qp))i.animate(e,a)}animate(e,n){const a=this.host.querySelector(`.vx-frow[data-folder="${CSS.escape(e)}"]`);if(!a)return;const i=a.nextElementSibling;if(!i||!i.classList.contains("vx-kids"))return;const o=Nl(e);a.setAttribute("aria-expanded",String(n));const s=a.querySelector(".vx-fico");s&&o&&(s.innerHTML=Bi(Io(e),n));const r=()=>{i.style.height="",i.removeEventListener("transitionend",r)};if(n){!i.firstElementChild&&o&&this.fillKids(i,o),i.style.height="0px",i.classList.add("open");const l=i.scrollHeight;requestAnimationFrame(()=>{i.style.height=l+"px"}),i.addEventListener("transitionend",r),setTimeout(r,320),window.matchMedia("(prefers-reduced-motion: reduce)").matches||Array.from(i.firstElementChild?.children||[]).slice(0,12).forEach((d,p)=>d.animate([{opacity:0,transform:"translateY(-6px)"},{opacity:1,transform:"none"}],{duration:260,delay:30+p*22,easing:gc,fill:"backwards"}))}else i.style.height=i.scrollHeight+"px",requestAnimationFrame(()=>{i.style.height="0px",i.classList.remove("open")}),i.addEventListener("transitionend",r),setTimeout(r,320);this.roving()}async renameFolderInline(e,n){const a=e.querySelector(".vx-fname");if(!a)return;const i=await Yu(a,ct(n));i&&await X3(n,i)}async renameNoteInline(e,n){const a=e.querySelector(".vx-fname");if(!a)return;const i=await Yu(a,or(ct(n).replace(/\.md$/i,"")));i&&await nm(n,i)}visibleRows(){return Array.from(this.host.querySelectorAll("[data-nav]")).filter(e=>!e.closest(".vx-kids:not(.open)"))}roving(){const e=this.visibleRows();if(!e.length)return;const n=e.find(a=>a.dataset.key===this.focusKey)||e.find(a=>a.classList.contains("sel")||a.classList.contains("active"))||e.find(a=>a.classList.contains("vx-frow"))||e[0];e.forEach(a=>a.tabIndex=a===n?0:-1)}onKey(e){const n=e.target.closest("[data-nav]");if(!n||e.target.tagName==="INPUT")return;const a=this.visibleRows(),i=a.indexOf(n),o=n.dataset.folder,s=n.dataset.path,r=l=>{l&&(a.forEach(c=>c.tabIndex=-1),l.tabIndex=0,this.focusKey=l.dataset.key||null,l.focus())};switch(e.key){case"ArrowDown":e.preventDefault(),r(a[i+1]);return;case"ArrowUp":e.preventDefault(),r(a[i-1]);return;case"Home":e.preventDefault(),r(a[0]);return;case"End":e.preventDefault(),r(a[a.length-1]);return;case"ArrowRight":o!=null&&o!==""&&(e.preventDefault(),n.getAttribute("aria-expanded")==="false"?this.toggle(o,!0):r(a[i+1]));return;case"ArrowLeft":{if(e.preventDefault(),o&&n.getAttribute("aria-expanded")==="true"){this.toggle(o,!1);return}const l=o!=null?Be(o):Be(s||"");if(o==="")return;r(this.host.querySelector(`.vx-frow[data-folder="${CSS.escape(l)}"]`)||void 0);return}case"Enter":case" ":e.preventDefault(),o!=null?nt.selectFolder(o):s&&nt.openNote(s);return;case"F2":e.preventDefault(),o?this.renameFolderInline(n,o):s&&this.renameNoteInline(n,s);return;case"Delete":e.preventDefault(),o?_p(o):s&&dc(Je.size>1&&Je.has(s)?Array.from(Je):[s]);return;case"p":case"P":if(e.ctrlKey||e.metaKey||e.altKey)return;e.preventDefault(),o?Fr("folder",o):s&&Fr("note",s);return;case"n":case"N":if(e.ctrlKey||e.metaKey||e.altKey)return;e.preventDefault(),nt.newNote(o??Be(s||""));return;case"ContextMenu":e.preventDefault(),o!=null?zs(o,n,()=>{this.renameFolderInline(n,o)}):s&&Go([s],n,()=>{this.renameNoteInline(n,s)});return;case"F10":e.shiftKey&&(e.preventDefault(),o!=null?zs(o,n,()=>{this.renameFolderInline(n,o)}):s&&Go([s],n,()=>{this.renameNoteInline(n,s)}));return;default:return}}}ES(()=>Ja());function IO(t,e={}){return new JT(t,{showNotes:e.showNotes??!0,showPins:e.showPins??!0})}const NO=480,zO=2200,DO=`
|
|
4824
4838
|
.totop{position:absolute;right:24px;bottom:calc(24px + var(--toasts-h,0px));z-index:30;width:44px;height:44px;display:grid;place-items:center;padding:0;border-radius:50%;
|
|
4825
4839
|
border:1px solid color-mix(in srgb,var(--fg) 24%,transparent);background:var(--surface-2);color:var(--fg);box-shadow:none;cursor:pointer;
|
|
4826
4840
|
opacity:0;visibility:hidden;transform:translateY(12px) scale(.92);pointer-events:none;
|
|
@@ -4846,7 +4860,7 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4846
4860
|
<div class="vx-main">
|
|
4847
4861
|
<div class="vx-pane vx-pane-list" aria-label="Folder"></div>
|
|
4848
4862
|
<div class="vx-pane vx-pane-note" aria-label="Note"></div>
|
|
4849
|
-
</div>`,t.appendChild(nn),iE=new JT(nn.querySelector(".vx-pane-tree"),{showNotes:Ge.showNotesInTree,showPins:!0}),Na(nn.querySelector(".vx-pane-tree")),jO(nn),nn.addEventListener("keydown",e=>{if(e.key==="F6"){e.preventDefault();const n=nn?.querySelector(".vx-pane-tree"),i=!!n?.contains(document.activeElement)||nn?.classList.contains("no-tree")?N.note?yc():Sm():n;(i?.querySelector('[tabindex="0"],button,input,textarea')||i)?.focus()}})}function jO(t){t.querySelectorAll(".vx-resizer").forEach(e=>{const n=a=>{Ge.treeW=Math.round(Math.max(190,Math.min(460,a))),t.style.setProperty("--tree-w",Ge.treeW+"px")};e.onpointerdown=a=>{a.preventDefault(),e.setPointerCapture(a.pointerId);const i=a.clientX,o=Ge.treeW;t.classList.add("resizing"),e.onpointermove=s=>n(o+s.clientX-i),e.onpointerup=()=>{e.onpointermove=null,t.classList.remove("resizing"),Va()}},e.onkeydown=a=>{(a.key==="ArrowLeft"||a.key==="ArrowRight")&&(a.preventDefault(),n(Ge.treeW+(a.key==="ArrowLeft"?-16:16)),Va())}})}function Wr(){const t=Sm();t&&Pn(t,sy())}async function wc(t=!1){const e=yc();if(e){if(!N.note&&xc){bc("note"),e.innerHTML=As(me.note,"Note not found",`“${x(lt(xc))}” may have been moved, renamed or deleted. Deleted notes wait in the Trash.`,'<span><button class="btn sm primary" data-home>Show all notes</button> <button class="btn sm ghost" data-trash>Open Trash</button></span>').replace("vx-empty","vx-empty vx-missing"),e.querySelector("[data-trash]").onclick=()=>nt.openTrash(),e.querySelector("[data-home]").onclick=()=>{xc=null,Kp("")};return}if(!N.note){bc("list");return}bc("note"),await Os(e,N.note,sy(),t)}}function Yp(){const t=H(".crumb");t.textContent=N.note?lt(N.note):Ge.folder?"Notes / "+Ge.folder:"Notes"}function ry(){if(!nn)return;const t=nn.querySelector(".vx-pane-tree"),e=Array.from(document.querySelectorAll(".vx-treehost")).some(n=>n!==t&&n.isConnected&&!nn.contains(n));nn.classList.toggle("no-tree",e||sy())}async function ly(){Fx();const t=H("#view-vault");if(t.classList){if(!nn||!t.contains(nn)){VO(t),Ge.folder&&!Nl(Ge.folder)&&(Ge.folder=""),ry(),bc(N.note?"note":"list"),iE?.render(),Wr(),await wc(),Yp();return}Ge.folder&&!Nl(Ge.folder)&&(Ge.folder=""),ry(),Ja(),Wr(),(N.note!==KD()||!N.note)&&await wc(!0),Yp()}}function sE(t){return en().some(e=>e.path===t)}async function Xp(t){if(!sE(t)&&!Object.keys(N.tree).length)try{await te.loadCore()}catch{}await lE(t)}function rE(t,e){if(location.pathname+location.search===t)return;const a=e?.vxDepth||0;try{history.replaceState({...history.state||{},vxDepth:a+1},"")}catch{}}function YO(){if((history.state?.vxDepth||0)>0){history.back();return}Kp(N.note?Be(N.note):Ge.folder||"")}async function lE(t,e=!1){await fc();const n=location.pathname+location.search,a=history.state;if(!sE(t)){if($r())return;xc=t,N.note=null,N.editing=!1,N.page!=="vault"?te.go("vault"):(wc(),Yp());return}xc=null,N.note=t,N.editing=!1,Je.clear(),Fi(Be(t),Ge.folder||"")||(Ge.folder=Be(t),U0(),Va());let i=Be(t);for(;i;)pn.add(i),i=Be(i);if(Po(),N.page!=="vault"){te.go("vault"),rE(n,a),te.refreshTree(),e&&setTimeout(()=>yc()?.querySelector("[data-mode=edit]")?.click(),400);return}rE(n,a),bc("note"),Ja(),Wr(),await wc(),e&&yc()?.querySelector("[data-mode=edit]")?.click(),Yp(),te.refreshTree(),yc()?.querySelector(".vx-note-scroll")?.scrollTo(0,0)}function Kp(t){xc=null,fc().then(()=>{const e=(Ge.folder||"")!==t;if(Ge.folder=t,Va(),U0(),Je.clear(),N.note=null,N.editing=!1,bc("list"),N.page!=="vault"){te.go("vault");return}Ja(),Wr(),e&&Sm()?.querySelector(".vx-bscroll")?.scrollTo(0,0),wc(),Yp()})}function XO(){Ge.filter="all",wD(),Kp("")}nt.selectFolder=Kp,nt.allNotes=XO,nt.openNote=t=>{Xp(t)},nt.newNote=t=>{const e=Ms(),n=t&&t!=="Root"&&e.includes(t)?t:"";let a=null;const i=async o=>{const s=o.querySelector("#vxName"),r=s?.value.trim()||"";if(!r){s?.focus();return}const l=a?.value??"";ue.close();const c=await K3(l,r);c&&await lE(c,!0)};ue.open({title:"New note",body:ue.field("Title","vxName",{value:""})+'<div class="field"><label id="vxWhereL">Location</label><div id="vxWhere"></div></div>',actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Create",cls:"primary",run:i}],onOpen:o=>{a=zf({folders:e,value:n,label:"Location",onPick:()=>{i(o)}}),o.querySelector("#vxWhere")?.appendChild(a.el);const s=o.querySelector("#vxName");s?.focus(),s&&(s.onkeydown=r=>{r.key==="Enter"&&(r.preventDefault(),i(o))})}})},nt.newFolder=t=>{Xx(t?`New folder in ${t}`:"New folder","Folder name","",async e=>{const n=await M8(t,e);n&&Kp(n)})},j3(()=>{N.page==="vault"&&nn?ly():Ja()}),ES(()=>{N.page==="vault"&&nn&&Wr()});let cE=0;YR(()=>{clearTimeout(cE),cE=window.setTimeout(()=>{Ja(),N.page==="vault"&&nn&&!N.editing&&Wr()},250)}),document.addEventListener("vx-back",()=>YO()),window.matchMedia(oE).addEventListener?.("change",()=>{N.page==="vault"&&nn&&(ry(),Wr(),wc(!0))});function KO(){nt.newNote("")}function ZO(){nt.newFolder("")}function JO(t){Ur([t])}function QO(t){I0(t)}function e$(t){_p(t)}function t$(t){z0(t)}const dE="Memora by Codrihub Tech",cy="Second brain for your AI",pE="A self-hosted memory vault: your notes as plain Markdown, wired into a living brain that your AI agents read and write over MCP. What they learn stays.",n$="Set up once, use everywhere: connect each agent once and they all share the same memory, on your local network or over the internet.",hE="Memora is memory, advanced: built to remember what you and your AI learn, and to remember more the more you use it.",a$={bg:"#0b0f17",bgTop:"#17202e",accent:"#5eead4",cyan:"#22d3ee",coreLight:"#a5f3fc"},i$="M7.2 16.8V7.4l4.8 5.1 4.8-5.1v9.4",o$=[[7.2,16.8],[7.2,7.4],[16.8,7.4],[16.8,16.8]],Mm=[12,12.5];let s$=0;const dy=typeof document>"u"?"s":"r";function r$(t){const{bg:e,bgTop:n,accent:a,cyan:i,coreLight:o}=a$,s=++s$,r=`mmg${dy}${s}`,l=`mmt${dy}${s}`,c=`mmc${dy}${s}`,d=o$.map(([p,h])=>`<circle cx="${p}" cy="${h}" r="1.7" fill="${p<12?a:i}"/>`).join("");return`<defs><linearGradient id="${r}" x1="3" y1="3" x2="21" y2="21" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${a}"/><stop offset="1" stop-color="${i}"/></linearGradient><linearGradient id="${l}" x1="0" y1="0" x2="0" y2="24" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${n}"/><stop offset="1" stop-color="${e}"/></linearGradient><radialGradient id="${c}" cx="50%" cy="50%" r="50%"><stop offset="0" stop-color="#ffffff"/><stop offset=".55" stop-color="${o}"/><stop offset="1" stop-color="${i}"/></radialGradient></defs><g fill="none" stroke="none"><rect x="1.5" y="1.5" width="21" height="21" rx="6.2" fill="url(#${l})"/><rect x="1.5" y="1.5" width="21" height="21" rx="6.2" fill="none" stroke="url(#${r})" stroke-opacity=".55" stroke-width=".8"/><path d="${i$}" fill="none" stroke="url(#${r})" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/>`+d+`<circle cx="${Mm[0]}" cy="${Mm[1]}" r="3" fill="${i}" opacity=".22"/><circle cx="${Mm[0]}" cy="${Mm[1]}" r="2" fill="url(#${c})"/></g>`}function to(t="brand-mark"){return`<svg class="${t}" viewBox="0 0 24 24" aria-hidden="true">${r$()}</svg>`}const Zp="'Memora Script', 'Segoe Script', cursive",uE="@font-face{font-family:'Memora Script';font-style:normal;font-weight:700;font-display:block;src:url(data:font/woff2;base64,d09GMgABAAAAAA/sABAAAAAAHHwAAA+QAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGjYbhwYcgk4GYD9TVEFUKgCBJBEICqMAnUsBNgIkA3ALOgAEIAWEVgcgDAcbcRijopyyciP4iwQOrxo/YUJJ0KGxLYMtMChiyWS84W/ql0UgbBZ6Di4wnBshySzP83/v5z73TelUewLYrDUcDki+zwpojAYT8WhpwME5w9Op/y7xBWpyiS9GoS1CmaYptJoj1Indp4sPuxPXFFgU4UiGMoyq87T9ziPxIzsBL2e31mxqv+oBPZDTdX5t1h5CCSG96Pf/2y+1czMbJldkoYKqKkLXmN35CwOfdif08ouMQjZClVgBudbVqBrfUynqfY1QtTVkJ/C41laa+xiZm7oMAOl1MkS2QwUalm4sgDWd5YHBXskEmXTfVZ5vWqHigHkezEsA+qx+qAfQ4QAaA2/xsXmgB5CwhIOhQzHgnDJ8zOsXKeRI6vMy+BLyAowuInzYAlIR1N7RezDB9hAABPzxx7/w3z7/sh2YmrBV4CrBpxWBEbHM5LokcjkwJ0qpJevSaGXRI8XILWNWxIqXsYvgZGQKc4jV7pwS5JWQK4K+TEeshFQCtQZ2L8AP24apBVsRbgURKhYYj+ORK4PronDyKNnQwUEGDwxkPpvvGl4CAHzBsE8RdjENeviggTYGeKONGZqYoclOxd3hg8H7N2FiATggr6EBQEED6tTuvWeBsTPfDEBm9aRx4NKQIv4ene7+YwsecXCESTtPeXxQYGDhEJDtti0DC0cKKFRsDwiPadkArDjm1LxiihaRrj4JQBmPCBb+LApq7S1goyXkAGbh4R5j1xXermbTvPAc/kllAAWmZ/EECjLeXS5Dgf/aY01F1/GYqX6ueRin4tijMUFLbEtcS/wAAfFN+jXANGtvrQeOWW9jF8gY8Rncz6O6CLnvOwwncLyjUUbqlkRMeWb1DM4XFtvRAIuKB4Wv4MNgz0DAaZ5wjbBg91iSDSkB/loIO+TE9Rlw+XTc16p5fB4l99140PkAHJ45/L074j9pvxMcgZo77bljAJh7DTmqp+Y95lXAKSxIcgRsjnY8hLlpbRuCQJBEzZnD3L8wZkJ4WGSEs4UuQuHGv5eHT0C+QnEJzdp16zVg2NzGwC712v5c/d1bgV576bnHHrrvtqsuO++0I5DONAE1xlByqOihefeBBSla/H+2jU8YAAQoOeNiU9HLrBkMtYBo7NznPqDYMipzUqk6TxaVrg3KaQG6iJp0Uh2ZbliU2qZLc2jUUk77VYDFLYjRlC8+h29mGwqvqYmmZg7CvKUXMOkHzMsqKvv+AhgCiPmyeqBBbPVpyprE8URsVgpBnJiWU1a1A95wH4a4UJ88cQ1iaRiostfXkJ1yIhjHZUPtUaBxTdjcNK9Dztr6mLiZ+MKXsgn5XVUm6660NVS5uzzkuckbCuiJOAdWp1+kZx5L3xVEHRHbl+4VQPsYBqgsq9NKsSDAoMh8iGnQ0j5M7q3pJUl5Bx4GlyLWJX49XYRc25uI1xofr4fzZLOWBTEBa83pCG7pVFl1eRsL4vugxD7TGBpXldiKYqXZsiCPL9BpSoR9qWlZqpx3rct+dYyn1LMrJSnh+osJA48AYj7srZ1ragzCNLlFAvHo9YepKaMcFmMngeSFC4DqPD0arzcWMgZ12YrI8W1OoBhlCMWnKi3R1iORF8OI+FwM5j0heh39y9rAy2KZbm8yz1R25unJzGRq6hrCGCQMx6lFsmMPKMLwJhfclN2Ow825UI9u721f2gWLLRBSpHjmjuobhzg++cRmUvZyfMHMWt953KcMMRvJCjUtOLkEAeHeszVGK5OJzStP6HHNo0e5+46BnOFYtB9U8SGvUHjrYLY4+sWRyV9Z3/rHr6/s8jmjF6pYc+BjM8ZGF/UVSoRlj7pBFaQhdljPdbvJrH1Yoa0woRT5ED9VWcWFLrAdty0wPxLJnd2vZfAzk1de8KUlQNnD1MDcnI5MXX2Zkn0fUEI/Ea3kCtnRI7bqN6aD0FbGjqEfTeI4vzEmej++qjivawt0VZYPAbdUOV25mw/UFFH3tp+cUogVlKmrlBSxdUcuEzfbvPKE6PtCXDp12TmaRFkxeGLqmuiy6exrjrtKnY+59KHrtlZyeL8C2pCTeJlWJ1kWvfVLdBkGopxvlHXkwYYiV9Yet3Wo7P3IGGZgExZwRlG8f/9gDb83rxAR/T+7J6pkZ2xQBLR4EBvb9y60BVoYmxy+yPWF+KBjvDtnx5A+zEhc+9LNaWGNc+2aSGYprF5KP08IX+isecfO8tnLxh/tdc7rGxIHtlxVn9i8Mvbk0ubCCxFXls+WzY7azB6uWefSCue5oIJ+0aMXwzpvX8/BO2Oi9ImejyS7jw7PpE476yD1nzjNkQ9UakFT6Rk+/N//x3xjq7/12e2hWYuTLcxpHv0d3e04pR5Fk2K2aD6zz6j7nYP4AvoCtrS4oT3Dpo2HkYqOmz7iJ9ZExQ2F7nnFHE2PcSpSUTRXH5p4ANxk3qyQqT+30Hoosbmzd54713TbIU2JKPz3ELhmyYdFvEQK2yUwVXtKe/xrtFs8NnHyd1daR3Z5/ektCm99zzwveDXprnO4Ei6TutQfrLa1zlTm61NT6+qzPbmerAytKNjJoa/ZnO/wqaSLUPPT0oTZKEseDsHteZnNDinfs8GW3p5T3nj6iMrf2DPXDXDJAltH/Gr/b4G96R4ifI9l8PIjKjIi5X/7NweNjYZFKnWGqKPJQ1pBHtRnZa3wLfMMupLjE6Uc+tvLkPjkN5JNyFb6Mocwf1Wx8bkvrb2OX+VLb2V3Z851jmibji6rxyvZiagWKsdWQ1UGBo0eG237O3IgNwx+SmbV5aT3FuRbD5Rs6u1b5PbBrcqiD0mudnddd3SdcWfIJaqYdKbXefJ70tdItnglRK+VzZqn9ojD1byXuCK150WvViKNcnzEPHmL/UxiaVtFjxn8OYf/hrfE3ZTZnCGssl3lxiRWIeVgrjhpXqMbMPQ558vzW8/6iPicj4l3o4IKts1cl1JstkdcVr0/YC2RlDLD+L6fc+uCtTW1PzpXoy8MdonK7a6o05VVLHgk9868Dphk+j5Iwiu6jgSda12LbYNuH2jAF5NuRfymQVZM68d89vpnUSzznUp+I95sHS78Tz7/FaZ3RIangkVyikkpK04vDLmLtXrjPZWobAdfDqdMC8U78/RhJCBGEWRBhs8Z1KnwtpZcCkxvwrFok0x+MmhKKIa98YhFox+UYDDQYm86aAtnZgVn2OUr07f5N4QGZvqQlFyCGCk0VmSW+UP+rkJmsV7XJhGOyX3qkM4e06BbnBK6+wf8LIKSy9nx6bpwbjae4r4fn1FyYPkavgqi0pQCLpL4ZNW3Oq/U7ZJhsNCy5Y64tQn0pbu8bp9dXTMzWmDUGyJi8QmEc3VXqZQ0hyLosgTFBXLxywZNsTFUkLQvSNS2pAG/hNNwWiaXFacVh33FegNyiIXPGUp1UeTXBSrfDITzO1MUnVEwIouXW0es3ZbSY2wKoLHQqKM1a45jETovjb+EwitO9/ZYk76SfItG/4uS6bZ+6w96tGDQ6Pb7XSZTQyxZlWoRfq3TGD0RZzn6JJYE43Xv/CI2JCzR/M0zzycqWux117f9dzEipswmI8xf68AEj+0zW6RLXZvda/19M3x8bo1AxC8wVmQl/aHAY1+XCPAwPpUl9Zrdb+sUtf8iaMjNY/9H4Z3PCsd+rM8tidiNmtlS7sdvcPkehmDkP5H/weeR3l3TOr/UzaFBEESY5Yg7WkGhxHRNjTAC4jy17y6PKmHQPtH5pGE52sRTFPoMiR8UZZ316Y9zPk7h28XszVzuJICl2hoUee9dNutFGMkJmLx/XHfJT1WSyU6Bn+NF6Icp3KPuoowGFuXPBXhoklPMLV1sKKLT7Qx4uCz2uVEvUO+Q0TLaiowvZ0u074uFJAwb3sIQsQzhD3F/OhK+DOCRmWElyvHqj/GIKtfD9e4r3JSvOJzo/H9Ffjs38IXOaJWrNVVnbjAZB/vuieNhi5K24zhSlt23d0BeqEDG6ZxhPfcbcFugnpSLx17iI+9nJtNaqN++Za6L7mUJ/2NQz+Hxa7kwbv9fqGT/dg79S5ifI4nv6DeE4mUuEJMoLunFrJg49AON+PK5y1IPEpPhzHcYrKZ1Gt8PO5c8U03FGtZb+PQTTO7O3FD/N6WB0kKbRvL8PjyegoMHHgNWRHBJgcbv+hX/X3gr3/l1wGNkLzohE7Ij4uD/VEJbrW59ddoTHMYNFu+TZ8S83EL3eoT02lZGSlLeH95SWSAK0z7KicScs4TuGd0BdwrHV6gonHYbxgTwUn+6UroFT1uh+vIh5AdwPemLnLUY9gWrJqlu+GAvS2hiUeqJtBNEGHcAlkvmDdniseb/vCuYBk9JPBW0P+A8Bwvw/mKBqKC8qUirW1qyx1Jly9F+l1TRix+geKzuqjlfVnLEFSVLJExaO550mkDGXaDIJQtXptCEffP3vp2ibHeyONOi/lwhFnou8QXfGJ9VVDgKwjYH4dGsRz/GwB6B7HP6vwoh35n8ZORtred7F4ohM5cO2ksszeA5W67HnX+0Oz3D4/c7Tab6WLIqzSZ8Tqc2uiP2ctmTWCqJfZ0sT23yl6wxF3o9BVq96Dm93R/rsjyNg0nsk3+jxqQ9WrRIcj5R3Zx6486dD9fZhKQ2Cpf+SW1MtuecUyyizqGIH9qjoEBmualzqSoywh7neQ6eky6vx4kZHJZRpWB76Vr2X1z/1nV0HrOByCwj4s/iYdx+GJXOH+QwvoQR03/xFblZnpJ4uln9hUxyeD9fyNRfE8cO/W6jEY+fSHr7ae0dp2MZ1NbnNzk2Oa5up6QLOKD7xNmRQN5BuEomrw9g7gEuYJHILnJgmHaKRQL9DgIM3tv987fWMXJ+I2GxXwJ8Y0FUAPieXN2bLt59iWNg94AQYAAE+PkfTv9SRc2LlX07X3KYC0DmABg3AIzHAB3c6WDSTPtjM/uZbUA2xCAv90tlb83kT3v5pkpKp+V8D+/XOmNHwQxNG+kEIF8bp17Bb3X6H5T+6c+EnbbGucrj65pAg78ZBrcMXiucXmbMv23ZACxojgxAtgGYGwkRhzcSgxTHSKysZI3E0WRoJJ4w+0YQqHJ9IgiAtbxpcHRf6tOrz1wD2rVqMwTlYGOXBpUI0LyuX70ejVnVUwlVwgTS9CWqSKhXx4RpnCeP4VG1RTRgUIyOnob0HZTF2kWt2oHLhjWwaNSre5V69Q7LujRrOVRP9t5BVlrsm5Ce6fRmkxIqvkAN9jRgpK5qggrSEarATTerk1ekN69ggT3eq1eXJg4WNosty1agsL/ZgGydAzPBwVs1AzZJPtGgdiZHoXIPXdacMs0Ha7E6M+qYw/pfEpdvcRU=) format('woff2')}",Qa=[{version:"2.1.7",title:"Skills, fleeting chats and chats that follow their note",lead:"Teach Mnemo a skill once and run it with a slash, chat without keeping anything, and find a note's chats wherever the note goes.",groups:[{kind:"new",items:[{icon:"bolt",title:"Skills",text:'Skills are notes in the Skills folder. Ask Mnemo to make one ("a skill that tidies meeting notes"), then type / in the chat to pick it. Mnemo can change or remove them too.'},{icon:"eye",title:"Fleeting chats",text:"The eye in Mnemo's header starts a chat that is not kept: it and the pictures sent in it are gone when you leave it, and it stays out of search. Changes to notes stay."},{icon:"sparkle",title:"Suggestions that change",text:"A new chat shows different suggestions each time: some of yours (Your suggestions), some Mnemo wrote from your recent notes (Fresh ideas writes new ones) and some built in. Your skills are one tap away."},{icon:"image",title:"Mnemo sees your pictures",text:"Mnemo can open a picture shown in a note to describe it or read it. A picture that is only a web address it cannot open, and it tells you to send or add it instead."}]},{kind:"better",items:[{icon:"note",title:"One chat per note",text:"Every @mnemo request in a note goes to that note's one chat, which follows the note when it is renamed, moved or sent to the Trash. Asking about a note offers its earlier chats."},{icon:"enter",title:"@mnemo from Mnemo works",text:"When Mnemo writes an @mnemo request into a note for you, it is answered like one you wrote."},{icon:"refresh",title:"Steadier chats",text:"Leaving a chat while Mnemo answers no longer shows a network error: it picks the reply up again. Chats get a proper title even when the first try fails, and deleting a chat also deletes the pictures sent in it."},{icon:"expand",title:"Room for the chat",text:"A page open beside the chat folds the chat list away (it comes back when you drag the divider to give the chat more room). If both cannot fit, the page opens full screen."},{icon:"image",title:"Pictures fit the note",text:"Pictures in notes are at most about 60% of the screen tall; tap one for the full size."}]}]},{version:"2.1.6",title:"Pages that grow, chats you can tidy",lead:"Mnemo reworks the page it made instead of starting over, chats can be cleaned up in bulk, and compacting waits until the chat is really full.",groups:[{kind:"new",items:[{icon:"code",title:"Pages are versions of one file",text:"Ask Mnemo to tidy or change a page and it rewrites that same file: the card shows v2, v3 and latest, the panel steps between versions, and on a wide screen the new one opens by itself. Pages stay with their chat (listed under In this chat) and Mnemo can reuse one from another chat."},{icon:"expand",title:"Drag the divider",text:"The line between the chat and an open page can be dragged. Each side keeps a sensible minimum, the width is remembered, and a double-click resets it."},{icon:"trash",title:"Select, clean up or delete all",text:"The ⋯ beside New chat picks several chats to delete, cleans up chats older than 7, 30 or 90 days, or deletes them all (pinned ones kept unless you say so)."},{icon:"chat",title:"Chats know each other",text:'Mnemo can list your other chats, search them by title or words and read one, so "the chat from yesterday" just works.'}]},{kind:"better",items:[{icon:"refresh",title:"Compacting only when full",text:"A chat is compacted only once it fills the model's memory, and while it happens you see it working, with a clock, before the reply goes on."},{icon:"sun",title:"Tidier Mnemo foot and pages",text:"Appearance is one wide button with Activity, Settings and Memora under it. Page cards stand out and fill the reply's width. Scrollbars are thin and show only while you scroll."},{icon:"bolt",title:"What's new, as a carousel",text:"Releases slide in one row with arrows, newest first, and the buttons at the bottom no longer bump into each other on a phone."}]}]},{version:"2.1.5",title:"Unread that agrees everywhere, and a tidier Mnemo",lead:"What you have read is remembered on the server, the chat list ends in one neat row, and phones stop sending half a message.",groups:[{kind:"better",items:[{icon:"bell",title:"Unread on every device",text:"A chat you read on your phone is read on your laptop too. Your own messages and the chat you are looking at never count as news."},{icon:"sun",title:"Appearance in one place",text:"Theme, chat background and text size moved into an Appearance panel (a sheet on phones). The chat list ends in one row: Appearance, Activity, Settings and Memora."},{icon:"enter",title:"Enter on phones",text:"On a touch keyboard Enter starts a new line; the send button sends. With a real keyboard Enter still sends and Shift+Enter is a new line."},{icon:"chev-down",title:"Scroll to the bottom",text:"The button above the message box is a plain way down, with no New messages label."}]}]},{version:"2.1.4",title:"Pages open like files, and news is marked",lead:"A page Mnemo writes is a card in the chat; open it and it sits beside the chat. Chats with news stand out.",groups:[{kind:"new",items:[{icon:"chev-down",title:"Back to the latest",text:"Scrolled up? A button above the message box takes you down again, and says New messages when a reply came in meanwhile."},{icon:"bell",title:"Unread chats",text:"The Mnemo item in the sidebar shows how many chats have news; in Mnemo each one is in bold with its number of new messages."}]},{kind:"better",items:[{icon:"code",title:"File cards and a side panel",text:"Charts and pages show as a card with Open and Download. On a wide screen the page opens beside the chat; on a tablet or phone it fills the screen until you close it. Preview, Code, Copy, Download and Close sit in one clear bar."},{icon:"refresh",title:"Compacted, centred",text:"The divider where a chat was compacted sits in the middle of the chat again."}]}]},{version:"2.1.3",title:"Mnemo answers with pictures",lead:"Ask for a chart, a diagram or a small page and see it live in the chat.",groups:[{kind:"new",items:[{icon:"eye",title:"Live previews",text:"When a chart, graph or diagram says it better, Mnemo writes a small HTML or SVG page. Once the reply is done it shows as a preview; switch to Code, copy it, download it or open it full screen. It runs sandboxed, away from your notes."}]},{kind:"better",items:[{icon:"refresh",title:"Calmer compact divider",text:"Where a chat was compacted the divider just says Compacted, centred; open it to read the summary."}]}]},{version:"2.1.2",title:"Mnemo fits your screen, and errors read plainly",lead:"On a phone Mnemo uses the full width, and you choose how big its text is.",groups:[{kind:"new",items:[{icon:"eye",title:"Text size",text:"Auto, Small, Medium or Large, from Appearance in the chat list or Settings, Mnemo. Auto is small on phones so more fits, and medium elsewhere."}]},{kind:"better",items:[{icon:"chat",title:"Full width on phones",text:"Replies drop the avatar beside them and use the whole width, with the same margin on both sides."},{icon:"refresh",title:"Clear errors",text:"A provider that is down for a moment is asked again by itself for about half a minute. If it still fails, Mnemo says so in plain words with Try again; the full error is there only if you open it."}]}]},{version:"2.1.1",title:"Mnemo asks first, or just gets on with it",lead:"Pick how much Mnemo may do on its own, answer its questions with a tap, and keep typing while it works.",groups:[{kind:"new",items:[{icon:"help",title:"It asks instead of guessing",text:"When a choice is yours, Mnemo shows the options as buttons, plus Other for your own answer."},{icon:"shield",title:"Ask first, or Auto",text:"Ask first: Mnemo looks freely but waits for your OK before changing notes. Auto: it goes ahead and keeps working until the job is done. Switch from the chip next to the model."},{icon:"chat",title:"Type while it works",text:"Messages you send mid-reply wait in a queue you can reorder; they go out one by one. Ctrl+Enter steers the reply that is running instead."}]},{kind:"better",items:[{icon:"eye",title:"Easier to read",text:"Replies sit on a frosted card, details start closed and keep their header in view, and the chat scrolls without a bar."}]}]},{version:"2.1.0",title:"Meet Mnemo, your notes have a helper now",lead:"Ask in plain words and Mnemo finds, writes, tidies and links your notes for you, with the AI key you already have. And your notes can finally hold pictures.",groups:[{kind:"new",items:[{icon:"mnemo",title:"Ask Mnemo anything about your notes",text:"“What did I decide about the launch?” “Tag everything from last week.” “Turn this into a checklist.” Mnemo does it and shows each step. It only works inside your notes and never deletes for good."},{icon:"note",title:"Write @mnemo: right in a note",text:"Leave a request on any line, save, and come back to the answer underneath with the request crossed out. Handy for to-dos you would rather hand off."},{icon:"image",title:"Show it a picture",text:"Paste a screenshot or a photo and Mnemo actually sees it: ask what it says, or have it filed beside the right note."},{icon:"chat",title:"It remembers the whole chat",text:"Long conversations get folded into a summary instead of forgotten, replies keep going if you switch chats, and the search box finds anything either of you said."},{icon:"image",title:"Images live in your notes",text:"Drop a PNG, JPEG, WebP or GIF into a note. It sits in the note’s folder and moves, goes to the Trash and comes back with it. Each folder gets a gallery too."}]},{kind:"better",items:[{icon:"eye",title:"Read your way",text:"Nine reading themes from paper and sepia to night, plus fonts like Literata, Atkinson Hyperlegible and OpenDyslexic, in the size you like."},{icon:"sparkle",title:"A chat that feels like yours",text:"Light or dark right from Mnemo’s sidebar, a dozen quiet backgrounds, and a timeline on the right edge to jump through long chats with your thumb."},{icon:"check",title:"No more surprise sign-outs",text:"Memora keeps you signed in while you are using it; it only times out when you really step away."}]},{kind:"admin",items:[{icon:"settings",title:"Bring your own AI",text:"Settings, Mnemo: add OpenAI, Anthropic or any OpenAI-compatible server, test it, pick a default model and write instructions in your own words. Mnemo is in the terminal app too."}]}]},{version:"2.0.1",title:"A calmer reader",lead:"Notes now read like a clean page, whatever reading settings you pick.",groups:[{kind:"better",items:[{icon:"note",title:"Cleaner note text",text:"Clearer headings, even lists, quieter code and tables, and real check boxes for tasks."},{icon:"menu",title:"Contents and Details",text:"The panel beside a note has two tabs. Contents holds the outline, links and mentions."},{icon:"settings",title:"Simpler reading settings",text:"The fonts and colours that look right everywhere stay. A choice that was removed moves to the nearest one."}]}]},{version:"2.0.0",title:"A calmer, clearer Memora",lead:"Every page was redesigned around one quiet look, and the places you use most got new tools: version history, tag patterns, a summary of what your AIs do, and a cleaner way to read.",groups:[{kind:"new",items:[{icon:"refresh",title:"Version history for every note",text:"See each version and who made it, compare it with now, and restore it. Restoring adds a new version, so nothing is lost."},{icon:"tags",title:"Find notes by a pattern of tags",text:"Build “session or (memora and plan) not docker” from chips on the Tags page, and see how many notes match before you apply it."},{icon:"activity",title:"Activity, summarised",text:"Numbers, a chart, what your AIs do most and what went wrong, with every action on its own Timeline tab."},{icon:"note",title:"A cleaner way to read",text:"Fold the toolbar away with F. Contents sits beside the note, with its details as a tab."},{icon:"brain",title:"Clean view on the maps",text:"Hide every control on 3D, Graph and Canvas with C, and bring them back the same way."}]},{kind:"better",items:[{icon:"trash",title:"A safer Trash",text:"Choose where a note goes back. Deleting forever asks you to type DELETE, and also erases the note from its history."},{icon:"bolt",title:"Faster",text:"Data travels compressed, Activity remembers each time range, and the start screen leaves the moment the app is ready."},{icon:"settings",title:"Settings you can change",text:"The server name and how long browsers stay signed in. Switching the notes folder now says what moves with it."},{icon:"agents",title:"Your AIs at a glance",text:"The Live panel leads with what your AIs did last, then who is working."}]},{kind:"admin",items:[{icon:"shield",title:"For whoever runs the server",text:"Deleting a note for good over the API now needs an admin key. The database needs no migration: a 1.3 install updates in place."},{icon:"book",title:"A new licence",text:"From 2.0.0 Memora is under the GNU AGPL v3.0 or later. Forks and hosted copies keep the source open and credit Memora."}]}]}],l$={new:"New",better:"Better",admin:"Good to know"},fE="/api/ui/layout/whats-new",c$=`
|
|
4863
|
+
</div>`,t.appendChild(nn),iE=new JT(nn.querySelector(".vx-pane-tree"),{showNotes:Ge.showNotesInTree,showPins:!0}),Na(nn.querySelector(".vx-pane-tree")),jO(nn),nn.addEventListener("keydown",e=>{if(e.key==="F6"){e.preventDefault();const n=nn?.querySelector(".vx-pane-tree"),i=!!n?.contains(document.activeElement)||nn?.classList.contains("no-tree")?N.note?yc():Sm():n;(i?.querySelector('[tabindex="0"],button,input,textarea')||i)?.focus()}})}function jO(t){t.querySelectorAll(".vx-resizer").forEach(e=>{const n=a=>{Ge.treeW=Math.round(Math.max(190,Math.min(460,a))),t.style.setProperty("--tree-w",Ge.treeW+"px")};e.onpointerdown=a=>{a.preventDefault(),e.setPointerCapture(a.pointerId);const i=a.clientX,o=Ge.treeW;t.classList.add("resizing"),e.onpointermove=s=>n(o+s.clientX-i),e.onpointerup=()=>{e.onpointermove=null,t.classList.remove("resizing"),Va()}},e.onkeydown=a=>{(a.key==="ArrowLeft"||a.key==="ArrowRight")&&(a.preventDefault(),n(Ge.treeW+(a.key==="ArrowLeft"?-16:16)),Va())}})}function Wr(){const t=Sm();t&&Pn(t,sy())}async function wc(t=!1){const e=yc();if(e){if(!N.note&&xc){bc("note"),e.innerHTML=As(me.note,"Note not found",`“${x(lt(xc))}” may have been moved, renamed or deleted. Deleted notes wait in the Trash.`,'<span><button class="btn sm primary" data-home>Show all notes</button> <button class="btn sm ghost" data-trash>Open Trash</button></span>').replace("vx-empty","vx-empty vx-missing"),e.querySelector("[data-trash]").onclick=()=>nt.openTrash(),e.querySelector("[data-home]").onclick=()=>{xc=null,Kp("")};return}if(!N.note){bc("list");return}bc("note"),await Os(e,N.note,sy(),t)}}function Yp(){const t=H(".crumb");t.textContent=N.note?lt(N.note):Ge.folder?"Notes / "+Ge.folder:"Notes"}function ry(){if(!nn)return;const t=nn.querySelector(".vx-pane-tree"),e=Array.from(document.querySelectorAll(".vx-treehost")).some(n=>n!==t&&n.isConnected&&!nn.contains(n));nn.classList.toggle("no-tree",e||sy())}async function ly(){Fx();const t=H("#view-vault");if(t.classList){if(!nn||!t.contains(nn)){VO(t),Ge.folder&&!Nl(Ge.folder)&&(Ge.folder=""),ry(),bc(N.note?"note":"list"),iE?.render(),Wr(),await wc(),Yp();return}Ge.folder&&!Nl(Ge.folder)&&(Ge.folder=""),ry(),Ja(),Wr(),(N.note!==KD()||!N.note)&&await wc(!0),Yp()}}function sE(t){return en().some(e=>e.path===t)}async function Xp(t){if(!sE(t)&&!Object.keys(N.tree).length)try{await te.loadCore()}catch{}await lE(t)}function rE(t,e){if(location.pathname+location.search===t)return;const a=e?.vxDepth||0;try{history.replaceState({...history.state||{},vxDepth:a+1},"")}catch{}}function YO(){if((history.state?.vxDepth||0)>0){history.back();return}Kp(N.note?Be(N.note):Ge.folder||"")}async function lE(t,e=!1){await fc();const n=location.pathname+location.search,a=history.state;if(!sE(t)){if($r())return;xc=t,N.note=null,N.editing=!1,N.page!=="vault"?te.go("vault"):(wc(),Yp());return}xc=null,N.note=t,N.editing=!1,Je.clear(),Fi(Be(t),Ge.folder||"")||(Ge.folder=Be(t),U0(),Va());let i=Be(t);for(;i;)hn.add(i),i=Be(i);if(Po(),N.page!=="vault"){te.go("vault"),rE(n,a),te.refreshTree(),e&&setTimeout(()=>yc()?.querySelector("[data-mode=edit]")?.click(),400);return}rE(n,a),bc("note"),Ja(),Wr(),await wc(),e&&yc()?.querySelector("[data-mode=edit]")?.click(),Yp(),te.refreshTree(),yc()?.querySelector(".vx-note-scroll")?.scrollTo(0,0)}function Kp(t){xc=null,fc().then(()=>{const e=(Ge.folder||"")!==t;if(Ge.folder=t,Va(),U0(),Je.clear(),N.note=null,N.editing=!1,bc("list"),N.page!=="vault"){te.go("vault");return}Ja(),Wr(),e&&Sm()?.querySelector(".vx-bscroll")?.scrollTo(0,0),wc(),Yp()})}function XO(){Ge.filter="all",wD(),Kp("")}nt.selectFolder=Kp,nt.allNotes=XO,nt.openNote=t=>{Xp(t)},nt.newNote=t=>{const e=Ms(),n=t&&t!=="Root"&&e.includes(t)?t:"";let a=null;const i=async o=>{const s=o.querySelector("#vxName"),r=s?.value.trim()||"";if(!r){s?.focus();return}const l=a?.value??"";ue.close();const c=await K3(l,r);c&&await lE(c,!0)};ue.open({title:"New note",body:ue.field("Title","vxName",{value:""})+'<div class="field"><label id="vxWhereL">Location</label><div id="vxWhere"></div></div>',actions:[{label:"Cancel",cls:"ghost",run:()=>ue.close()},{label:"Create",cls:"primary",run:i}],onOpen:o=>{a=zf({folders:e,value:n,label:"Location",onPick:()=>{i(o)}}),o.querySelector("#vxWhere")?.appendChild(a.el);const s=o.querySelector("#vxName");s?.focus(),s&&(s.onkeydown=r=>{r.key==="Enter"&&(r.preventDefault(),i(o))})}})},nt.newFolder=t=>{Xx(t?`New folder in ${t}`:"New folder","Folder name","",async e=>{const n=await M8(t,e);n&&Kp(n)})},j3(()=>{N.page==="vault"&&nn?ly():Ja()}),ES(()=>{N.page==="vault"&&nn&&Wr()});let cE=0;YR(()=>{clearTimeout(cE),cE=window.setTimeout(()=>{Ja(),N.page==="vault"&&nn&&!N.editing&&Wr()},250)}),document.addEventListener("vx-back",()=>YO()),window.matchMedia(oE).addEventListener?.("change",()=>{N.page==="vault"&&nn&&(ry(),Wr(),wc(!0))});function KO(){nt.newNote("")}function ZO(){nt.newFolder("")}function JO(t){Ur([t])}function QO(t){I0(t)}function e$(t){_p(t)}function t$(t){z0(t)}const dE="Memora by Codrihub Tech",cy="Second brain for your AI",pE="A self-hosted memory vault: your notes as plain Markdown, wired into a living brain that your AI agents read and write over MCP. What they learn stays.",n$="Set up once, use everywhere: connect each agent once and they all share the same memory, on your local network or over the internet.",hE="Memora is memory, advanced: built to remember what you and your AI learn, and to remember more the more you use it.",a$={bg:"#0b0f17",bgTop:"#17202e",accent:"#5eead4",cyan:"#22d3ee",coreLight:"#a5f3fc"},i$="M7.2 16.8V7.4l4.8 5.1 4.8-5.1v9.4",o$=[[7.2,16.8],[7.2,7.4],[16.8,7.4],[16.8,16.8]],Mm=[12,12.5];let s$=0;const dy=typeof document>"u"?"s":"r";function r$(t){const{bg:e,bgTop:n,accent:a,cyan:i,coreLight:o}=a$,s=++s$,r=`mmg${dy}${s}`,l=`mmt${dy}${s}`,c=`mmc${dy}${s}`,d=o$.map(([p,h])=>`<circle cx="${p}" cy="${h}" r="1.7" fill="${p<12?a:i}"/>`).join("");return`<defs><linearGradient id="${r}" x1="3" y1="3" x2="21" y2="21" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${a}"/><stop offset="1" stop-color="${i}"/></linearGradient><linearGradient id="${l}" x1="0" y1="0" x2="0" y2="24" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${n}"/><stop offset="1" stop-color="${e}"/></linearGradient><radialGradient id="${c}" cx="50%" cy="50%" r="50%"><stop offset="0" stop-color="#ffffff"/><stop offset=".55" stop-color="${o}"/><stop offset="1" stop-color="${i}"/></radialGradient></defs><g fill="none" stroke="none"><rect x="1.5" y="1.5" width="21" height="21" rx="6.2" fill="url(#${l})"/><rect x="1.5" y="1.5" width="21" height="21" rx="6.2" fill="none" stroke="url(#${r})" stroke-opacity=".55" stroke-width=".8"/><path d="${i$}" fill="none" stroke="url(#${r})" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/>`+d+`<circle cx="${Mm[0]}" cy="${Mm[1]}" r="3" fill="${i}" opacity=".22"/><circle cx="${Mm[0]}" cy="${Mm[1]}" r="2" fill="url(#${c})"/></g>`}function to(t="brand-mark"){return`<svg class="${t}" viewBox="0 0 24 24" aria-hidden="true">${r$()}</svg>`}const Zp="'Memora Script', 'Segoe Script', cursive",uE="@font-face{font-family:'Memora Script';font-style:normal;font-weight:700;font-display:block;src:url(data:font/woff2;base64,d09GMgABAAAAAA/sABAAAAAAHHwAAA+QAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGjYbhwYcgk4GYD9TVEFUKgCBJBEICqMAnUsBNgIkA3ALOgAEIAWEVgcgDAcbcRijopyyciP4iwQOrxo/YUJJ0KGxLYMtMChiyWS84W/ql0UgbBZ6Di4wnBshySzP83/v5z73TelUewLYrDUcDki+zwpojAYT8WhpwME5w9Op/y7xBWpyiS9GoS1CmaYptJoj1Indp4sPuxPXFFgU4UiGMoyq87T9ziPxIzsBL2e31mxqv+oBPZDTdX5t1h5CCSG96Pf/2y+1czMbJldkoYKqKkLXmN35CwOfdif08ouMQjZClVgBudbVqBrfUynqfY1QtTVkJ/C41laa+xiZm7oMAOl1MkS2QwUalm4sgDWd5YHBXskEmXTfVZ5vWqHigHkezEsA+qx+qAfQ4QAaA2/xsXmgB5CwhIOhQzHgnDJ8zOsXKeRI6vMy+BLyAowuInzYAlIR1N7RezDB9hAABPzxx7/w3z7/sh2YmrBV4CrBpxWBEbHM5LokcjkwJ0qpJevSaGXRI8XILWNWxIqXsYvgZGQKc4jV7pwS5JWQK4K+TEeshFQCtQZ2L8AP24apBVsRbgURKhYYj+ORK4PronDyKNnQwUEGDwxkPpvvGl4CAHzBsE8RdjENeviggTYGeKONGZqYoclOxd3hg8H7N2FiATggr6EBQEED6tTuvWeBsTPfDEBm9aRx4NKQIv4ene7+YwsecXCESTtPeXxQYGDhEJDtti0DC0cKKFRsDwiPadkArDjm1LxiihaRrj4JQBmPCBb+LApq7S1goyXkAGbh4R5j1xXermbTvPAc/kllAAWmZ/EECjLeXS5Dgf/aY01F1/GYqX6ueRin4tijMUFLbEtcS/wAAfFN+jXANGtvrQeOWW9jF8gY8Rncz6O6CLnvOwwncLyjUUbqlkRMeWb1DM4XFtvRAIuKB4Wv4MNgz0DAaZ5wjbBg91iSDSkB/loIO+TE9Rlw+XTc16p5fB4l99140PkAHJ45/L074j9pvxMcgZo77bljAJh7DTmqp+Y95lXAKSxIcgRsjnY8hLlpbRuCQJBEzZnD3L8wZkJ4WGSEs4UuQuHGv5eHT0C+QnEJzdp16zVg2NzGwC712v5c/d1bgV576bnHHrrvtqsuO++0I5DONAE1xlByqOihefeBBSla/H+2jU8YAAQoOeNiU9HLrBkMtYBo7NznPqDYMipzUqk6TxaVrg3KaQG6iJp0Uh2ZbliU2qZLc2jUUk77VYDFLYjRlC8+h29mGwqvqYmmZg7CvKUXMOkHzMsqKvv+AhgCiPmyeqBBbPVpyprE8URsVgpBnJiWU1a1A95wH4a4UJ88cQ1iaRiostfXkJ1yIhjHZUPtUaBxTdjcNK9Dztr6mLiZ+MKXsgn5XVUm6660NVS5uzzkuckbCuiJOAdWp1+kZx5L3xVEHRHbl+4VQPsYBqgsq9NKsSDAoMh8iGnQ0j5M7q3pJUl5Bx4GlyLWJX49XYRc25uI1xofr4fzZLOWBTEBa83pCG7pVFl1eRsL4vugxD7TGBpXldiKYqXZsiCPL9BpSoR9qWlZqpx3rct+dYyn1LMrJSnh+osJA48AYj7srZ1ragzCNLlFAvHo9YepKaMcFmMngeSFC4DqPD0arzcWMgZ12YrI8W1OoBhlCMWnKi3R1iORF8OI+FwM5j0heh39y9rAy2KZbm8yz1R25unJzGRq6hrCGCQMx6lFsmMPKMLwJhfclN2Ow825UI9u721f2gWLLRBSpHjmjuobhzg++cRmUvZyfMHMWt953KcMMRvJCjUtOLkEAeHeszVGK5OJzStP6HHNo0e5+46BnOFYtB9U8SGvUHjrYLY4+sWRyV9Z3/rHr6/s8jmjF6pYc+BjM8ZGF/UVSoRlj7pBFaQhdljPdbvJrH1Yoa0woRT5ED9VWcWFLrAdty0wPxLJnd2vZfAzk1de8KUlQNnD1MDcnI5MXX2Zkn0fUEI/Ea3kCtnRI7bqN6aD0FbGjqEfTeI4vzEmej++qjivawt0VZYPAbdUOV25mw/UFFH3tp+cUogVlKmrlBSxdUcuEzfbvPKE6PtCXDp12TmaRFkxeGLqmuiy6exrjrtKnY+59KHrtlZyeL8C2pCTeJlWJ1kWvfVLdBkGopxvlHXkwYYiV9Yet3Wo7P3IGGZgExZwRlG8f/9gDb83rxAR/T+7J6pkZ2xQBLR4EBvb9y60BVoYmxy+yPWF+KBjvDtnx5A+zEhc+9LNaWGNc+2aSGYprF5KP08IX+isecfO8tnLxh/tdc7rGxIHtlxVn9i8Mvbk0ubCCxFXls+WzY7azB6uWefSCue5oIJ+0aMXwzpvX8/BO2Oi9ImejyS7jw7PpE476yD1nzjNkQ9UakFT6Rk+/N//x3xjq7/12e2hWYuTLcxpHv0d3e04pR5Fk2K2aD6zz6j7nYP4AvoCtrS4oT3Dpo2HkYqOmz7iJ9ZExQ2F7nnFHE2PcSpSUTRXH5p4ANxk3qyQqT+30Hoosbmzd54713TbIU2JKPz3ELhmyYdFvEQK2yUwVXtKe/xrtFs8NnHyd1daR3Z5/ektCm99zzwveDXprnO4Ei6TutQfrLa1zlTm61NT6+qzPbmerAytKNjJoa/ZnO/wqaSLUPPT0oTZKEseDsHteZnNDinfs8GW3p5T3nj6iMrf2DPXDXDJAltH/Gr/b4G96R4ifI9l8PIjKjIi5X/7NweNjYZFKnWGqKPJQ1pBHtRnZa3wLfMMupLjE6Uc+tvLkPjkN5JNyFb6Mocwf1Wx8bkvrb2OX+VLb2V3Z851jmibji6rxyvZiagWKsdWQ1UGBo0eG237O3IgNwx+SmbV5aT3FuRbD5Rs6u1b5PbBrcqiD0mudnddd3SdcWfIJaqYdKbXefJ70tdItnglRK+VzZqn9ojD1byXuCK150WvViKNcnzEPHmL/UxiaVtFjxn8OYf/hrfE3ZTZnCGssl3lxiRWIeVgrjhpXqMbMPQ558vzW8/6iPicj4l3o4IKts1cl1JstkdcVr0/YC2RlDLD+L6fc+uCtTW1PzpXoy8MdonK7a6o05VVLHgk9868Dphk+j5Iwiu6jgSda12LbYNuH2jAF5NuRfymQVZM68d89vpnUSzznUp+I95sHS78Tz7/FaZ3RIangkVyikkpK04vDLmLtXrjPZWobAdfDqdMC8U78/RhJCBGEWRBhs8Z1KnwtpZcCkxvwrFok0x+MmhKKIa98YhFox+UYDDQYm86aAtnZgVn2OUr07f5N4QGZvqQlFyCGCk0VmSW+UP+rkJmsV7XJhGOyX3qkM4e06BbnBK6+wf8LIKSy9nx6bpwbjae4r4fn1FyYPkavgqi0pQCLpL4ZNW3Oq/U7ZJhsNCy5Y64tQn0pbu8bp9dXTMzWmDUGyJi8QmEc3VXqZQ0hyLosgTFBXLxywZNsTFUkLQvSNS2pAG/hNNwWiaXFacVh33FegNyiIXPGUp1UeTXBSrfDITzO1MUnVEwIouXW0es3ZbSY2wKoLHQqKM1a45jETovjb+EwitO9/ZYk76SfItG/4uS6bZ+6w96tGDQ6Pb7XSZTQyxZlWoRfq3TGD0RZzn6JJYE43Xv/CI2JCzR/M0zzycqWux117f9dzEipswmI8xf68AEj+0zW6RLXZvda/19M3x8bo1AxC8wVmQl/aHAY1+XCPAwPpUl9Zrdb+sUtf8iaMjNY/9H4Z3PCsd+rM8tidiNmtlS7sdvcPkehmDkP5H/weeR3l3TOr/UzaFBEESY5Yg7WkGhxHRNjTAC4jy17y6PKmHQPtH5pGE52sRTFPoMiR8UZZ316Y9zPk7h28XszVzuJICl2hoUee9dNutFGMkJmLx/XHfJT1WSyU6Bn+NF6Icp3KPuoowGFuXPBXhoklPMLV1sKKLT7Qx4uCz2uVEvUO+Q0TLaiowvZ0u074uFJAwb3sIQsQzhD3F/OhK+DOCRmWElyvHqj/GIKtfD9e4r3JSvOJzo/H9Ffjs38IXOaJWrNVVnbjAZB/vuieNhi5K24zhSlt23d0BeqEDG6ZxhPfcbcFugnpSLx17iI+9nJtNaqN++Za6L7mUJ/2NQz+Hxa7kwbv9fqGT/dg79S5ifI4nv6DeE4mUuEJMoLunFrJg49AON+PK5y1IPEpPhzHcYrKZ1Gt8PO5c8U03FGtZb+PQTTO7O3FD/N6WB0kKbRvL8PjyegoMHHgNWRHBJgcbv+hX/X3gr3/l1wGNkLzohE7Ij4uD/VEJbrW59ddoTHMYNFu+TZ8S83EL3eoT02lZGSlLeH95SWSAK0z7KicScs4TuGd0BdwrHV6gonHYbxgTwUn+6UroFT1uh+vIh5AdwPemLnLUY9gWrJqlu+GAvS2hiUeqJtBNEGHcAlkvmDdniseb/vCuYBk9JPBW0P+A8Bwvw/mKBqKC8qUirW1qyx1Jly9F+l1TRix+geKzuqjlfVnLEFSVLJExaO550mkDGXaDIJQtXptCEffP3vp2ibHeyONOi/lwhFnou8QXfGJ9VVDgKwjYH4dGsRz/GwB6B7HP6vwoh35n8ZORtred7F4ohM5cO2ksszeA5W67HnX+0Oz3D4/c7Tab6WLIqzSZ8Tqc2uiP2ctmTWCqJfZ0sT23yl6wxF3o9BVq96Dm93R/rsjyNg0nsk3+jxqQ9WrRIcj5R3Zx6486dD9fZhKQ2Cpf+SW1MtuecUyyizqGIH9qjoEBmualzqSoywh7neQ6eky6vx4kZHJZRpWB76Vr2X1z/1nV0HrOByCwj4s/iYdx+GJXOH+QwvoQR03/xFblZnpJ4uln9hUxyeD9fyNRfE8cO/W6jEY+fSHr7ae0dp2MZ1NbnNzk2Oa5up6QLOKD7xNmRQN5BuEomrw9g7gEuYJHILnJgmHaKRQL9DgIM3tv987fWMXJ+I2GxXwJ8Y0FUAPieXN2bLt59iWNg94AQYAAE+PkfTv9SRc2LlX07X3KYC0DmABg3AIzHAB3c6WDSTPtjM/uZbUA2xCAv90tlb83kT3v5pkpKp+V8D+/XOmNHwQxNG+kEIF8bp17Bb3X6H5T+6c+EnbbGucrj65pAg78ZBrcMXiucXmbMv23ZACxojgxAtgGYGwkRhzcSgxTHSKysZI3E0WRoJJ4w+0YQqHJ9IgiAtbxpcHRf6tOrz1wD2rVqMwTlYGOXBpUI0LyuX70ejVnVUwlVwgTS9CWqSKhXx4RpnCeP4VG1RTRgUIyOnob0HZTF2kWt2oHLhjWwaNSre5V69Q7LujRrOVRP9t5BVlrsm5Ce6fRmkxIqvkAN9jRgpK5qggrSEarATTerk1ekN69ggT3eq1eXJg4WNosty1agsL/ZgGydAzPBwVs1AzZJPtGgdiZHoXIPXdacMs0Ha7E6M+qYw/pfEpdvcRU=) format('woff2')}",Qa=[{version:"2.1.8",title:"@mnemo requests are never dropped",lead:"A request in a note that Mnemo could not answer stays open and is tried again until it goes through.",groups:[{kind:"better",items:[{icon:"refresh",title:"Tried again, not dropped",text:"When the AI provider or the network is down, an @mnemo request is no longer struck through with an error: it stays in the note and Mnemo tries again after 1, 3, 10 and 30 minutes, then every hour, in the same chat."},{icon:"chat",title:"The right chat at its address",text:"Opening a chat by its address shows its title at once, never New chat while it loads."},{icon:"sparkle",title:"Fresh ideas, smoother",text:"While Mnemo writes new suggestions the button shimmers and the cards wait as soft placeholders."},{icon:"bolt",title:"What's new, neater",text:"The release row starts flush left and only fades on a side with more to see; the arrows show only where you can go."}]}]},{version:"2.1.7",title:"Skills, fleeting chats and chats that follow their note",lead:"Teach Mnemo a skill once and run it with a slash, chat without keeping anything, and find a note's chats wherever the note goes.",groups:[{kind:"new",items:[{icon:"bolt",title:"Skills",text:'Skills are notes in the Skills folder. Ask Mnemo to make one ("a skill that tidies meeting notes"), then type / in the chat to pick it. Mnemo can change or remove them too.'},{icon:"eye",title:"Fleeting chats",text:"The eye in Mnemo's header starts a chat that is not kept: it and the pictures sent in it are gone when you leave it, and it stays out of search. Changes to notes stay."},{icon:"sparkle",title:"Suggestions that change",text:"A new chat shows different suggestions each time: some of yours (Your suggestions), some Mnemo wrote from your recent notes (Fresh ideas writes new ones) and some built in. Your skills are one tap away."},{icon:"image",title:"Mnemo sees your pictures",text:"Mnemo can open a picture shown in a note to describe it or read it. A picture that is only a web address it cannot open, and it tells you to send or add it instead."}]},{kind:"better",items:[{icon:"note",title:"One chat per note",text:"Every @mnemo request in a note goes to that note's one chat, which follows the note when it is renamed, moved or sent to the Trash. Asking about a note offers its earlier chats."},{icon:"enter",title:"@mnemo from Mnemo works",text:"When Mnemo writes an @mnemo request into a note for you, it is answered like one you wrote."},{icon:"refresh",title:"Steadier chats",text:"Leaving a chat while Mnemo answers no longer shows a network error: it picks the reply up again. Chats get a proper title even when the first try fails, and deleting a chat also deletes the pictures sent in it."},{icon:"expand",title:"Room for the chat",text:"A page open beside the chat folds the chat list away (it comes back when you drag the divider to give the chat more room). If both cannot fit, the page opens full screen."},{icon:"image",title:"Pictures fit the note",text:"Pictures in notes are at most about 60% of the screen tall; tap one for the full size."}]}]},{version:"2.1.6",title:"Pages that grow, chats you can tidy",lead:"Mnemo reworks the page it made instead of starting over, chats can be cleaned up in bulk, and compacting waits until the chat is really full.",groups:[{kind:"new",items:[{icon:"code",title:"Pages are versions of one file",text:"Ask Mnemo to tidy or change a page and it rewrites that same file: the card shows v2, v3 and latest, the panel steps between versions, and on a wide screen the new one opens by itself. Pages stay with their chat (listed under In this chat) and Mnemo can reuse one from another chat."},{icon:"expand",title:"Drag the divider",text:"The line between the chat and an open page can be dragged. Each side keeps a sensible minimum, the width is remembered, and a double-click resets it."},{icon:"trash",title:"Select, clean up or delete all",text:"The ⋯ beside New chat picks several chats to delete, cleans up chats older than 7, 30 or 90 days, or deletes them all (pinned ones kept unless you say so)."},{icon:"chat",title:"Chats know each other",text:'Mnemo can list your other chats, search them by title or words and read one, so "the chat from yesterday" just works.'}]},{kind:"better",items:[{icon:"refresh",title:"Compacting only when full",text:"A chat is compacted only once it fills the model's memory, and while it happens you see it working, with a clock, before the reply goes on."},{icon:"sun",title:"Tidier Mnemo foot and pages",text:"Appearance is one wide button with Activity, Settings and Memora under it. Page cards stand out and fill the reply's width. Scrollbars are thin and show only while you scroll."},{icon:"bolt",title:"What's new, as a carousel",text:"Releases slide in one row with arrows, newest first, and the buttons at the bottom no longer bump into each other on a phone."}]}]},{version:"2.1.5",title:"Unread that agrees everywhere, and a tidier Mnemo",lead:"What you have read is remembered on the server, the chat list ends in one neat row, and phones stop sending half a message.",groups:[{kind:"better",items:[{icon:"bell",title:"Unread on every device",text:"A chat you read on your phone is read on your laptop too. Your own messages and the chat you are looking at never count as news."},{icon:"sun",title:"Appearance in one place",text:"Theme, chat background and text size moved into an Appearance panel (a sheet on phones). The chat list ends in one row: Appearance, Activity, Settings and Memora."},{icon:"enter",title:"Enter on phones",text:"On a touch keyboard Enter starts a new line; the send button sends. With a real keyboard Enter still sends and Shift+Enter is a new line."},{icon:"chev-down",title:"Scroll to the bottom",text:"The button above the message box is a plain way down, with no New messages label."}]}]},{version:"2.1.4",title:"Pages open like files, and news is marked",lead:"A page Mnemo writes is a card in the chat; open it and it sits beside the chat. Chats with news stand out.",groups:[{kind:"new",items:[{icon:"chev-down",title:"Back to the latest",text:"Scrolled up? A button above the message box takes you down again, and says New messages when a reply came in meanwhile."},{icon:"bell",title:"Unread chats",text:"The Mnemo item in the sidebar shows how many chats have news; in Mnemo each one is in bold with its number of new messages."}]},{kind:"better",items:[{icon:"code",title:"File cards and a side panel",text:"Charts and pages show as a card with Open and Download. On a wide screen the page opens beside the chat; on a tablet or phone it fills the screen until you close it. Preview, Code, Copy, Download and Close sit in one clear bar."},{icon:"refresh",title:"Compacted, centred",text:"The divider where a chat was compacted sits in the middle of the chat again."}]}]},{version:"2.1.3",title:"Mnemo answers with pictures",lead:"Ask for a chart, a diagram or a small page and see it live in the chat.",groups:[{kind:"new",items:[{icon:"eye",title:"Live previews",text:"When a chart, graph or diagram says it better, Mnemo writes a small HTML or SVG page. Once the reply is done it shows as a preview; switch to Code, copy it, download it or open it full screen. It runs sandboxed, away from your notes."}]},{kind:"better",items:[{icon:"refresh",title:"Calmer compact divider",text:"Where a chat was compacted the divider just says Compacted, centred; open it to read the summary."}]}]},{version:"2.1.2",title:"Mnemo fits your screen, and errors read plainly",lead:"On a phone Mnemo uses the full width, and you choose how big its text is.",groups:[{kind:"new",items:[{icon:"eye",title:"Text size",text:"Auto, Small, Medium or Large, from Appearance in the chat list or Settings, Mnemo. Auto is small on phones so more fits, and medium elsewhere."}]},{kind:"better",items:[{icon:"chat",title:"Full width on phones",text:"Replies drop the avatar beside them and use the whole width, with the same margin on both sides."},{icon:"refresh",title:"Clear errors",text:"A provider that is down for a moment is asked again by itself for about half a minute. If it still fails, Mnemo says so in plain words with Try again; the full error is there only if you open it."}]}]},{version:"2.1.1",title:"Mnemo asks first, or just gets on with it",lead:"Pick how much Mnemo may do on its own, answer its questions with a tap, and keep typing while it works.",groups:[{kind:"new",items:[{icon:"help",title:"It asks instead of guessing",text:"When a choice is yours, Mnemo shows the options as buttons, plus Other for your own answer."},{icon:"shield",title:"Ask first, or Auto",text:"Ask first: Mnemo looks freely but waits for your OK before changing notes. Auto: it goes ahead and keeps working until the job is done. Switch from the chip next to the model."},{icon:"chat",title:"Type while it works",text:"Messages you send mid-reply wait in a queue you can reorder; they go out one by one. Ctrl+Enter steers the reply that is running instead."}]},{kind:"better",items:[{icon:"eye",title:"Easier to read",text:"Replies sit on a frosted card, details start closed and keep their header in view, and the chat scrolls without a bar."}]}]},{version:"2.1.0",title:"Meet Mnemo, your notes have a helper now",lead:"Ask in plain words and Mnemo finds, writes, tidies and links your notes for you, with the AI key you already have. And your notes can finally hold pictures.",groups:[{kind:"new",items:[{icon:"mnemo",title:"Ask Mnemo anything about your notes",text:"“What did I decide about the launch?” “Tag everything from last week.” “Turn this into a checklist.” Mnemo does it and shows each step. It only works inside your notes and never deletes for good."},{icon:"note",title:"Write @mnemo: right in a note",text:"Leave a request on any line, save, and come back to the answer underneath with the request crossed out. Handy for to-dos you would rather hand off."},{icon:"image",title:"Show it a picture",text:"Paste a screenshot or a photo and Mnemo actually sees it: ask what it says, or have it filed beside the right note."},{icon:"chat",title:"It remembers the whole chat",text:"Long conversations get folded into a summary instead of forgotten, replies keep going if you switch chats, and the search box finds anything either of you said."},{icon:"image",title:"Images live in your notes",text:"Drop a PNG, JPEG, WebP or GIF into a note. It sits in the note’s folder and moves, goes to the Trash and comes back with it. Each folder gets a gallery too."}]},{kind:"better",items:[{icon:"eye",title:"Read your way",text:"Nine reading themes from paper and sepia to night, plus fonts like Literata, Atkinson Hyperlegible and OpenDyslexic, in the size you like."},{icon:"sparkle",title:"A chat that feels like yours",text:"Light or dark right from Mnemo’s sidebar, a dozen quiet backgrounds, and a timeline on the right edge to jump through long chats with your thumb."},{icon:"check",title:"No more surprise sign-outs",text:"Memora keeps you signed in while you are using it; it only times out when you really step away."}]},{kind:"admin",items:[{icon:"settings",title:"Bring your own AI",text:"Settings, Mnemo: add OpenAI, Anthropic or any OpenAI-compatible server, test it, pick a default model and write instructions in your own words. Mnemo is in the terminal app too."}]}]},{version:"2.0.1",title:"A calmer reader",lead:"Notes now read like a clean page, whatever reading settings you pick.",groups:[{kind:"better",items:[{icon:"note",title:"Cleaner note text",text:"Clearer headings, even lists, quieter code and tables, and real check boxes for tasks."},{icon:"menu",title:"Contents and Details",text:"The panel beside a note has two tabs. Contents holds the outline, links and mentions."},{icon:"settings",title:"Simpler reading settings",text:"The fonts and colours that look right everywhere stay. A choice that was removed moves to the nearest one."}]}]},{version:"2.0.0",title:"A calmer, clearer Memora",lead:"Every page was redesigned around one quiet look, and the places you use most got new tools: version history, tag patterns, a summary of what your AIs do, and a cleaner way to read.",groups:[{kind:"new",items:[{icon:"refresh",title:"Version history for every note",text:"See each version and who made it, compare it with now, and restore it. Restoring adds a new version, so nothing is lost."},{icon:"tags",title:"Find notes by a pattern of tags",text:"Build “session or (memora and plan) not docker” from chips on the Tags page, and see how many notes match before you apply it."},{icon:"activity",title:"Activity, summarised",text:"Numbers, a chart, what your AIs do most and what went wrong, with every action on its own Timeline tab."},{icon:"note",title:"A cleaner way to read",text:"Fold the toolbar away with F. Contents sits beside the note, with its details as a tab."},{icon:"brain",title:"Clean view on the maps",text:"Hide every control on 3D, Graph and Canvas with C, and bring them back the same way."}]},{kind:"better",items:[{icon:"trash",title:"A safer Trash",text:"Choose where a note goes back. Deleting forever asks you to type DELETE, and also erases the note from its history."},{icon:"bolt",title:"Faster",text:"Data travels compressed, Activity remembers each time range, and the start screen leaves the moment the app is ready."},{icon:"settings",title:"Settings you can change",text:"The server name and how long browsers stay signed in. Switching the notes folder now says what moves with it."},{icon:"agents",title:"Your AIs at a glance",text:"The Live panel leads with what your AIs did last, then who is working."}]},{kind:"admin",items:[{icon:"shield",title:"For whoever runs the server",text:"Deleting a note for good over the API now needs an admin key. The database needs no migration: a 1.3 install updates in place."},{icon:"book",title:"A new licence",text:"From 2.0.0 Memora is under the GNU AGPL v3.0 or later. Forks and hosted copies keep the source open and credit Memora."}]}]}],l$={new:"New",better:"Better",admin:"Good to know"},fE="/api/ui/layout/whats-new",c$=`
|
|
4850
4864
|
.modal:has(.wn){width:min(620px,100%);padding:0;overflow:hidden}
|
|
4851
4865
|
.modal:has(.wn) .modal-head{display:none}
|
|
4852
4866
|
.modal:has(.wn) .modal-body{padding:0;display:flex;flex-direction:column;min-height:0;overflow:hidden}
|
|
@@ -4869,10 +4883,16 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4869
4883
|
.wn-arr{flex:none;display:grid;place-items:center;width:34px;height:34px;padding:0;border-radius:999px;border:1px solid rgba(148,163,184,.3);background:rgba(15,23,42,.35);color:#e6e9ef;cursor:pointer;
|
|
4870
4884
|
transition:background .15s,border-color .15s,opacity .15s}
|
|
4871
4885
|
.wn-arr:hover:not(:disabled){background:rgba(148,163,184,.18);border-color:rgba(148,163,184,.5)}
|
|
4872
|
-
.wn-arr:disabled{
|
|
4886
|
+
.wn-arr:disabled{display:none}
|
|
4873
4887
|
.wn-arr svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2.4;stroke-linecap:round;stroke-linejoin:round}
|
|
4888
|
+
/* The row fades only on a side that has more to scroll to. */
|
|
4874
4889
|
.wn-vers{flex:1;min-width:0;display:flex;gap:8px;overflow-x:auto;scroll-behavior:smooth;scroll-snap-type:x proximity;scrollbar-width:none;padding:2px;
|
|
4875
|
-
|
|
4890
|
+
--fl:0px;--fr:0px;-webkit-mask-image:linear-gradient(90deg,transparent,#000 var(--fl),#000 calc(100% - var(--fr)),transparent);
|
|
4891
|
+
mask-image:linear-gradient(90deg,transparent,#000 var(--fl),#000 calc(100% - var(--fr)),transparent)}
|
|
4892
|
+
.wn-vers.more-l{--fl:24px}
|
|
4893
|
+
.wn-vers.more-r{--fr:24px}
|
|
4894
|
+
.wn-vers:not(.more-l){-webkit-mask-image:linear-gradient(90deg,#000,#000 calc(100% - var(--fr)),transparent);mask-image:linear-gradient(90deg,#000,#000 calc(100% - var(--fr)),transparent)}
|
|
4895
|
+
.wn-vers:not(.more-l):not(.more-r){-webkit-mask-image:none;mask-image:none}
|
|
4876
4896
|
.wn-vers::-webkit-scrollbar{display:none}
|
|
4877
4897
|
.wn-vers button{flex:none;scroll-snap-align:center;height:34px;padding:0 15px;border-radius:999px;border:1.5px solid rgba(148,163,184,.34);background:rgba(15,23,42,.3);color:#e2e8f0;
|
|
4878
4898
|
font:700 13px/1 var(--font);letter-spacing:.01em;font-variant-numeric:tabular-nums;cursor:pointer;transition:background .15s,border-color .15s,color .15s}
|
|
@@ -4940,7 +4960,7 @@ ${t} .cn-prog .done .n{background:var(--tile);border-color:transparent;color:var
|
|
|
4940
4960
|
<button type="button" class="wn-log" data-log>Changelog</button>
|
|
4941
4961
|
<button type="button" class="btn primary" data-close>Got it</button>
|
|
4942
4962
|
</footer>
|
|
4943
|
-
</div>`}async function u$(t){try{const e=await $n("/api/config"),n=e?.update?.stars,a=t.querySelector("[data-stars]");a&&typeof n=="number"&&(a.textContent=n.toLocaleString("en-US"));const i=t.querySelector("[data-star]");i&&e?.update?.repo&&(i.href=e.update.repo)}catch{}}function hy(t){Ue("whats-new-css",c$),Ue("brand-font-face",uE);let e=Qa.find(a=>a.version===t)||Qa[0];if(!e)return;const n=(a,i=-1)=>{a.querySelectorAll("[data-close]").forEach(
|
|
4963
|
+
</div>`}async function u$(t){try{const e=await $n("/api/config"),n=e?.update?.stars,a=t.querySelector("[data-stars]");a&&typeof n=="number"&&(a.textContent=n.toLocaleString("en-US"));const i=t.querySelector("[data-star]");i&&e?.update?.repo&&(i.href=e.update.repo)}catch{}}function hy(t){Ue("whats-new-css",c$),Ue("brand-font-face",uE);let e=Qa.find(a=>a.version===t)||Qa[0];if(!e)return;const n=(a,i=-1)=>{a.querySelectorAll("[data-close]").forEach(d=>d.onclick=()=>ue.close()),a.querySelector("[data-log]")?.addEventListener("click",()=>{ue.close(),bd("changelog")});const o=(d,p)=>{!d||d===e||(e=d,a.innerHTML=gE(e),n(a,p),a.querySelector(".wn-body")?.scrollTo({top:0}))};a.querySelectorAll("[data-ver]").forEach(d=>{d.onclick=()=>o(Qa.find(p=>p.version===d.dataset.ver),s()?.scrollLeft??0)}),a.querySelectorAll("[data-step]").forEach(d=>{d.onclick=()=>o(Qa[Qa.indexOf(e)+Number(d.dataset.step)],s()?.scrollLeft??0)});const s=()=>a.querySelector(".wn-vers"),r=s(),l=()=>{r&&(r.classList.toggle("more-l",r.scrollLeft>2),r.classList.toggle("more-r",r.scrollLeft+r.clientWidth<r.scrollWidth-2))};r?.addEventListener("scroll",l,{passive:!0}),requestAnimationFrame(l);const c=r?.querySelector("[aria-pressed=true]");if(r&&c){r.style.scrollBehavior="auto",r.scrollLeft=i,r.style.scrollBehavior="";const d=c.offsetLeft-(r.clientWidth-c.offsetWidth)/2;requestAnimationFrame(()=>{r.scrollTo({left:Math.max(0,d),behavior:i<0?"auto":"smooth"}),l()})}a.querySelector(".wn")?.addEventListener("keydown",d=>{if((d.key==="ArrowLeft"||d.key==="ArrowRight")&&d.target.closest(".wn-car")){d.preventDefault();const p=d.key==="ArrowLeft"?-1:1,h=Qa[Qa.indexOf(e)+p];h&&(o(h,s()?.scrollLeft??0),a.querySelector(`[data-ver="${h.version}"]`)?.focus({preventScroll:!0}))}}),u$(a)};ue.open({title:"What's new",body:gE(e),onOpen:n}),vE(e.version)}function vE(t){$n(fE,{method:"PUT",body:{data:{seen:t}}}).catch(()=>{})}async function f$(){const t=mE(),e=Qa.find(n=>t&&py(n.version,t)<=0);if(e)try{const a=(await $n(fE))?.data?.seen||"";if(a&&py(a,e.version)>=0)return;if(document.querySelector(".wl-tour"))return vE(e.version);hy(e.version)}catch{}}function m$(t){return/["']memora-build:([0-9a-f]{12})["']/.exec(t)?.[1]??""}function xE(t,e){return!!t&&!!e&&t!==e}const Jp={prompt:null,init(){if("serviceWorker"in navigator){const n=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).catch(()=>{})};document.readyState==="complete"?n():window.addEventListener("load",n,{once:!0})}x$(),window.addEventListener("beforeinstallprompt",n=>{n.preventDefault(),this.prompt=n,H("#pwaBtn").classList.remove("hidden")}),window.addEventListener("appinstalled",()=>{this.prompt=null,H("#pwaBtn").classList.add("hidden"),ye("App installed","ok",2600)});const t=/iphone|ipad|ipod/i.test(navigator.userAgent),e=window.navigator.standalone;t&&!e&&H("#pwaBtn").classList.remove("hidden")},async install(){if(this.prompt){this.prompt.prompt();try{await this.prompt.userChoice}catch{}this.prompt=null,H("#pwaBtn").classList.add("hidden");return}ue.open({title:"Install Memora",body:`<div class="panel-body" style="padding:0">
|
|
4944
4964
|
<p><b>Desktop (Chrome or Edge)</b> - click the install icon at the right end of the address bar, or open the <span class="mono">⋮</span> menu and choose <i>Install</i>.</p>
|
|
4945
4965
|
<p><b>Android (Chrome)</b> - open the <span class="mono">⋮</span> menu and choose <i>Add to home screen</i>.</p>
|
|
4946
4966
|
<p><b>iPhone or iPad (Safari)</b> - tap <i>Share</i> and choose <i>Add to Home Screen</i>.</p>
|
|
@@ -6510,10 +6530,10 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
|
6510
6530
|
<span id="ovHealthPill"></span><svg class="cc-i chev" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
|
|
6511
6531
|
<div class="ov-sys" id="ovHealth"></div><div class="ov-tech-more" id="ovTechMore"></div></details>
|
|
6512
6532
|
</div>
|
|
6513
|
-
</div>`,H("#ovBrain").onclick=()=>te.go("brain"),H("#ovNew").onclick=()=>te.openNewNote(),H("#ovNodes").onclick=()=>te.go("vault"),H("#ovRecentAll").onclick=()=>te.go("vault"),H("#ovKeys").onclick=()=>te.go("keys"),H("#ovAll").onclick=()=>te.go("logs"),H("#ovTodayAll").onclick=()=>$y();const i=H("#ovTech");try{i.open=localStorage.getItem(y4)==="1"}catch{}wU(i),i.ontoggle=()=>{try{localStorage.setItem(y4,i.open?"1":"0")}catch{}};const o=s=>Qo.find(r=>r.id===s);Rl(H("#ovToday"),o),t.querySelectorAll(".ov-kpi[data-go]").forEach(s=>s.onclick=()=>te.go(s.dataset.go)),Rl(H("#ovAct"),o)}Td(t,()=>{Yy=Dd.state,Gm=Dd.clients;const e=[ku(a=>{wu(Qo,a,500),vU()}),Hn("connection",a=>{Yy=a,Km()}),Hn("presence",a=>{Gm=a,Km()})],n=window.setInterval(()=>{yh(),ew(),tw()},2e3);return()=>{e.forEach(a=>a()),clearInterval(n)}}),Ym(),Qy(),Km(),await xU()}}function mU(){return new Date().toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})}function gU(){const t=new Date().getHours();return t<5?"Good night":t<12?"Good morning":t<18?"Good afternoon":"Good evening"}function vU(){Xy||(Xy=!0,setTimeout(()=>{Xy=!1,yh(),ew(),Qy(),tw(),Xm()},150))}function xU(){return new Promise(t=>{Vm.push(t),Ky||bU()})}async function bU(){for(Ky=!0;Vm.length;){const t=Vm;Vm=[];try{await yU()}catch(e){console.warn("overview: load failed",e)}t.forEach(e=>e())}Ky=!1}async function yU(){const[t,e,n,a]=await Promise.all([Oe("/api/keys").catch(()=>null),yu("1d",500).catch(()=>[]),Oe("/api/oauth/clients").catch(()=>null),Jr?Promise.resolve(Jr):Fb(N.health.version||"").catch(()=>null)]);Jr=a,t&&(ro=Array.isArray(t)?t:t.keys||[],xh=!0),Sd(ro),Gy=new Set((n?.connections||[]).map(i=>i.key_id)),Qo=e,lo=!0,document.querySelector(".ov.ov-loading")?.classList.remove("ov-loading"),T4(),Ym(),yh(),Qy(),ew(),Km(),tw(),Xm()}function wU(t){const e=t.querySelector("summary");if(!e)return;let n=null;e.addEventListener("click",a=>{if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;a.preventDefault();const i=t.offsetHeight;n?.cancel();const o=!t.open||t.classList.contains("closing");t.classList.remove("closing"),o&&(t.open=!0);const s=o?t.offsetHeight:e.offsetHeight+(t.offsetHeight-t.clientHeight);if(o||t.classList.add("closing"),n=t.animate([{height:i+"px"},{height:s+"px"}],{duration:320,easing:"cubic-bezier(.2,.8,.2,1)"}),o)for(const r of Array.from(t.children))r!==e&&r.animate([{opacity:0,transform:"translateY(-4px)"},{opacity:1,transform:"none"}],{duration:280,easing:"ease-out"});n.onfinish=()=>{n=null,o||(t.classList.remove("closing"),t.open=!1)}})}const kU=/(<time data-ts="[^"]*">)[^<]*(<\/time>)/g;function ti(t,e){const n=e.replace(kU,"$1$2");if(t.dataset.html===n){const i=Array.from(e.matchAll(/<time data-ts="[^"]*">([^<]*)<\/time>/g),o=>o[1]);return t.querySelectorAll("time[data-ts]").forEach((o,s)=>{const r=i[s];r!==void 0&&o.innerHTML!==r&&(o.innerHTML=r)}),!1}t.dataset.html=n;const a=!!t.querySelector(".sk,.ov-sk-block");return t.innerHTML=e,a&&(t.classList.remove("ov-in"),t.offsetWidth,t.classList.add("ov-in")),!0}function Zy(t){return`<time data-ts="${t}">${x(SU(t))}</time>`}function SU(t){const e=$i(t);return e==="now"?"just now":e==="-"?e:e+" ago"}function MU(t){const e=t.replace(/[\\/]+$/,"").search(/[^\\/]+$/),n=e>0?t.slice(0,e):"",a=e>0?t.slice(e):t;return`<span class="ov-path" title="${C(t)}"><span class="h">${x(n)}</span><span class="e">${x(a)}</span></span>`}function bh(t,e,n,a=""){return`<div class="ov-empty"><span class="ov-tile">${t}</span><b>${e}</b><p>${n}</p>${a}</div>`}function w4(){const t=new Map;for(const e of en()){const n=(e.folder||"Root").split("/")[0]||"Root";t.set(n,(t.get(n)||0)+1)}return[...t.entries()].sort((e,n)=>n[1]-e[1]||e[0].localeCompare(n[0]))}function Qr(t){return typeof t.raw.actor_id=="string"?t.raw.actor_id:null}function k4(t){return Yn(t==="Root"?"":t)}function jm(t,e,n,a){const i=document.getElementById(t);if(!i)return;const o=i.querySelector("[data-v]");e==null?(i.setAttribute("aria-busy","true"),ti(o,'<span class="sk" style="display:inline-block;width:1.4ch;height:.9em;vertical-align:-.05em"></span>')):(i.removeAttribute("aria-busy"),delete o.dataset.html,o.textContent=Number.isNaN(e)?"–":e.toLocaleString()),ti(i.querySelector("[data-viz]"),n),ti(i.querySelector("[data-h]"),a)}function AU(t,e,n){const a=Date.now()/1e3,i=new Array(e).fill(0);for(const o of t){const s=Math.floor((a-o)/n);s>=0&&s<e&&i[e-1-s]++}return i}function S4(t,e,n){return e?`<span class="ov-seg" title="${C(n)}">${Array.from({length:e},(a,i)=>`<i${i<t?' class="on"':""}></i>`).join("")}</span>`:""}function TU(t,e,n){return e?S4(t?Math.max(1,Math.round(t/e*12)):0,12,n):""}function M4(){const t=document.getElementById("ovSub");t&&(t.textContent=!N.health.vault&&N.health.vault_configured===!1?"No notes folder is set up yet. See Technical details below.":"Your notes, your AIs and what they are doing, at a glance.")}function EU(){const t=en(),e=N.stats,n=e.notes||t.length,a=new Date;a.setHours(0,0,0,0);const i=t.filter(c=>(c.mtime||0)>=a.getTime()/1e3).length,o=t.reduce((c,d)=>Math.max(c,d.mtime||0),0);jm("ovKNodes",n,TU(i,n,`${i} of ${n} notes changed today`),i?`<b>${i}</b> changed today`:o?`Last change ${x(kn(o))}`:"No notes yet"),jm("ovKLinks",e.links||0,"",e.links?"Between notes":"No links yet");const s=w4(),r=s.reduce((c,d)=>c+d[1],0)||1,l=s.find(([c])=>c!=="Root");jm("ovKFolders",vu(),s.length?`<span class="ov-kpi-bar" title="${C(s.map(([c,d])=>`${c} ${d}`).join(", "))}">${s.slice(0,8).map(([c,d])=>`<i style="flex:${d/r};background:${C(k4(c))}"></i>`).join("")}</span>`:"",l?`Largest: <b>${x(l[0])}</b>`:"No folders yet"),A4()}function A4(){const t=Jy(),e=ro.filter(s=>s.enabled!==!1).length,n=t.filter(s=>s.active).length,a=t.filter(s=>s.items.length).length,o=Qo.filter(s=>s.source==="agent").map(s=>s.ts).length;jm("ovKAgents",xh?e:lo?NaN:null,xh&&t.length<=24?S4(a,t.length,`${a} of ${t.length} agents did something in the last 24 hours`):"",lo?xh?n?`<span class="cc-dot ok"></span><b>${n}</b> active now`:o?`<b>${o.toLocaleString()}</b> ${o===1?"action":"actions"} in 24h`:e?"Nothing in 24h":"None connected yet":"Could not load agents":" ")}function T4(){const t=document.getElementById("ovWelcome");if(!t)return;const e=rU();t.hidden=!e,t.closest(".ov")?.classList.toggle("is-empty",e);const n=xh?ro.length:0,a=n?"known":"new";!e||t.childElementCount&&t.dataset.mode===a||(t.dataset.mode=a,t.innerHTML=cU(n),dU(t,Zm,kc))}function _U(t){const e=document.querySelector(".ov-vault"),n=e?.querySelectorAll(".ov-bar");if(!e||!n?.length||n.length>=t)return;const a=e.querySelector(".ov-facts");if(!a)return;const o=e.getBoundingClientRect().bottom-22-a.getBoundingClientRect().bottom,s=n[0].offsetHeight+2,r=e.querySelector(".ov-more")?.offsetHeight||0,l=Math.floor((o+(n.length+Math.floor(o/s)>=t?r:0))/s);l>0&&(vh=Math.min(t,n.length+l),Ym())}function Ym(){T4(),M4(),EU();const t=document.getElementById("ovVault");if(!t)return;const e=en(),n=w4(),a=n[0]?.[1]||1,i=e.reduce((d,p)=>(p.mtime||0)>(d?.mtime||0)?p:d,null),o=i?E4(i.path):void 0,s=o?Qr(o):null,l=`<div><div class="ov-cap">Last change</div><div class="ov-row">${o?`<span title="${C("by "+o.actor)}" style="display:flex">${Yt(o.actor,32,"",s)}</span>`:`<span class="ov-tile">${Jo.clock}</span>`}<span class="t">${i?`<button type="button" class="ov-name" data-path="${C(i.path)}" title="${C(i.path)}">${x(i.name||
|
|
6533
|
+
</div>`,H("#ovBrain").onclick=()=>te.go("brain"),H("#ovNew").onclick=()=>te.openNewNote(),H("#ovNodes").onclick=()=>te.go("vault"),H("#ovRecentAll").onclick=()=>te.go("vault"),H("#ovKeys").onclick=()=>te.go("keys"),H("#ovAll").onclick=()=>te.go("logs"),H("#ovTodayAll").onclick=()=>$y();const i=H("#ovTech");try{i.open=localStorage.getItem(y4)==="1"}catch{}wU(i),i.ontoggle=()=>{try{localStorage.setItem(y4,i.open?"1":"0")}catch{}};const o=s=>Qo.find(r=>r.id===s);Rl(H("#ovToday"),o),t.querySelectorAll(".ov-kpi[data-go]").forEach(s=>s.onclick=()=>te.go(s.dataset.go)),Rl(H("#ovAct"),o)}Td(t,()=>{Yy=Dd.state,Gm=Dd.clients;const e=[ku(a=>{wu(Qo,a,500),vU()}),Hn("connection",a=>{Yy=a,Km()}),Hn("presence",a=>{Gm=a,Km()})],n=window.setInterval(()=>{yh(),ew(),tw()},2e3);return()=>{e.forEach(a=>a()),clearInterval(n)}}),Ym(),Qy(),Km(),await xU()}}function mU(){return new Date().toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})}function gU(){const t=new Date().getHours();return t<5?"Good night":t<12?"Good morning":t<18?"Good afternoon":"Good evening"}function vU(){Xy||(Xy=!0,setTimeout(()=>{Xy=!1,yh(),ew(),Qy(),tw(),Xm()},150))}function xU(){return new Promise(t=>{Vm.push(t),Ky||bU()})}async function bU(){for(Ky=!0;Vm.length;){const t=Vm;Vm=[];try{await yU()}catch(e){console.warn("overview: load failed",e)}t.forEach(e=>e())}Ky=!1}async function yU(){const[t,e,n,a]=await Promise.all([Oe("/api/keys").catch(()=>null),yu("1d",500).catch(()=>[]),Oe("/api/oauth/clients").catch(()=>null),Jr?Promise.resolve(Jr):Fb(N.health.version||"").catch(()=>null)]);Jr=a,t&&(ro=Array.isArray(t)?t:t.keys||[],xh=!0),Sd(ro),Gy=new Set((n?.connections||[]).map(i=>i.key_id)),Qo=e,lo=!0,document.querySelector(".ov.ov-loading")?.classList.remove("ov-loading"),T4(),Ym(),yh(),Qy(),ew(),Km(),tw(),Xm()}function wU(t){const e=t.querySelector("summary");if(!e)return;let n=null;e.addEventListener("click",a=>{if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;a.preventDefault();const i=t.offsetHeight;n?.cancel();const o=!t.open||t.classList.contains("closing");t.classList.remove("closing"),o&&(t.open=!0);const s=o?t.offsetHeight:e.offsetHeight+(t.offsetHeight-t.clientHeight);if(o||t.classList.add("closing"),n=t.animate([{height:i+"px"},{height:s+"px"}],{duration:320,easing:"cubic-bezier(.2,.8,.2,1)"}),o)for(const r of Array.from(t.children))r!==e&&r.animate([{opacity:0,transform:"translateY(-4px)"},{opacity:1,transform:"none"}],{duration:280,easing:"ease-out"});n.onfinish=()=>{n=null,o||(t.classList.remove("closing"),t.open=!1)}})}const kU=/(<time data-ts="[^"]*">)[^<]*(<\/time>)/g;function ti(t,e){const n=e.replace(kU,"$1$2");if(t.dataset.html===n){const i=Array.from(e.matchAll(/<time data-ts="[^"]*">([^<]*)<\/time>/g),o=>o[1]);return t.querySelectorAll("time[data-ts]").forEach((o,s)=>{const r=i[s];r!==void 0&&o.innerHTML!==r&&(o.innerHTML=r)}),!1}t.dataset.html=n;const a=!!t.querySelector(".sk,.ov-sk-block");return t.innerHTML=e,a&&(t.classList.remove("ov-in"),t.offsetWidth,t.classList.add("ov-in")),!0}function Zy(t){return`<time data-ts="${t}">${x(SU(t))}</time>`}function SU(t){const e=$i(t);return e==="now"?"just now":e==="-"?e:e+" ago"}function MU(t){const e=t.replace(/[\\/]+$/,"").search(/[^\\/]+$/),n=e>0?t.slice(0,e):"",a=e>0?t.slice(e):t;return`<span class="ov-path" title="${C(t)}"><span class="h">${x(n)}</span><span class="e">${x(a)}</span></span>`}function bh(t,e,n,a=""){return`<div class="ov-empty"><span class="ov-tile">${t}</span><b>${e}</b><p>${n}</p>${a}</div>`}function w4(){const t=new Map;for(const e of en()){const n=(e.folder||"Root").split("/")[0]||"Root";t.set(n,(t.get(n)||0)+1)}return[...t.entries()].sort((e,n)=>n[1]-e[1]||e[0].localeCompare(n[0]))}function Qr(t){return typeof t.raw.actor_id=="string"?t.raw.actor_id:null}function k4(t){return Yn(t==="Root"?"":t)}function jm(t,e,n,a){const i=document.getElementById(t);if(!i)return;const o=i.querySelector("[data-v]");e==null?(i.setAttribute("aria-busy","true"),ti(o,'<span class="sk" style="display:inline-block;width:1.4ch;height:.9em;vertical-align:-.05em"></span>')):(i.removeAttribute("aria-busy"),delete o.dataset.html,o.textContent=Number.isNaN(e)?"–":e.toLocaleString()),ti(i.querySelector("[data-viz]"),n),ti(i.querySelector("[data-h]"),a)}function AU(t,e,n){const a=Date.now()/1e3,i=new Array(e).fill(0);for(const o of t){const s=Math.floor((a-o)/n);s>=0&&s<e&&i[e-1-s]++}return i}function S4(t,e,n){return e?`<span class="ov-seg" title="${C(n)}">${Array.from({length:e},(a,i)=>`<i${i<t?' class="on"':""}></i>`).join("")}</span>`:""}function TU(t,e,n){return e?S4(t?Math.max(1,Math.round(t/e*12)):0,12,n):""}function M4(){const t=document.getElementById("ovSub");t&&(t.textContent=!N.health.vault&&N.health.vault_configured===!1?"No notes folder is set up yet. See Technical details below.":"Your notes, your AIs and what they are doing, at a glance.")}function EU(){const t=en(),e=N.stats,n=e.notes||t.length,a=new Date;a.setHours(0,0,0,0);const i=t.filter(c=>(c.mtime||0)>=a.getTime()/1e3).length,o=t.reduce((c,d)=>Math.max(c,d.mtime||0),0);jm("ovKNodes",n,TU(i,n,`${i} of ${n} notes changed today`),i?`<b>${i}</b> changed today`:o?`Last change ${x(kn(o))}`:"No notes yet"),jm("ovKLinks",e.links||0,"",e.links?"Between notes":"No links yet");const s=w4(),r=s.reduce((c,d)=>c+d[1],0)||1,l=s.find(([c])=>c!=="Root");jm("ovKFolders",vu(),s.length?`<span class="ov-kpi-bar" title="${C(s.map(([c,d])=>`${c} ${d}`).join(", "))}">${s.slice(0,8).map(([c,d])=>`<i style="flex:${d/r};background:${C(k4(c))}"></i>`).join("")}</span>`:"",l?`Largest: <b>${x(l[0])}</b>`:"No folders yet"),A4()}function A4(){const t=Jy(),e=ro.filter(s=>s.enabled!==!1).length,n=t.filter(s=>s.active).length,a=t.filter(s=>s.items.length).length,o=Qo.filter(s=>s.source==="agent").map(s=>s.ts).length;jm("ovKAgents",xh?e:lo?NaN:null,xh&&t.length<=24?S4(a,t.length,`${a} of ${t.length} agents did something in the last 24 hours`):"",lo?xh?n?`<span class="cc-dot ok"></span><b>${n}</b> active now`:o?`<b>${o.toLocaleString()}</b> ${o===1?"action":"actions"} in 24h`:e?"Nothing in 24h":"None connected yet":"Could not load agents":" ")}function T4(){const t=document.getElementById("ovWelcome");if(!t)return;const e=rU();t.hidden=!e,t.closest(".ov")?.classList.toggle("is-empty",e);const n=xh?ro.length:0,a=n?"known":"new";!e||t.childElementCount&&t.dataset.mode===a||(t.dataset.mode=a,t.innerHTML=cU(n),dU(t,Zm,kc))}function _U(t){const e=document.querySelector(".ov-vault"),n=e?.querySelectorAll(".ov-bar");if(!e||!n?.length||n.length>=t)return;const a=e.querySelector(".ov-facts");if(!a)return;const o=e.getBoundingClientRect().bottom-22-a.getBoundingClientRect().bottom,s=n[0].offsetHeight+2,r=e.querySelector(".ov-more")?.offsetHeight||0,l=Math.floor((o+(n.length+Math.floor(o/s)>=t?r:0))/s);l>0&&(vh=Math.min(t,n.length+l),Ym())}function Ym(){T4(),M4(),EU();const t=document.getElementById("ovVault");if(!t)return;const e=en(),n=w4(),a=n[0]?.[1]||1,i=e.reduce((d,p)=>(p.mtime||0)>(d?.mtime||0)?p:d,null),o=i?E4(i.path):void 0,s=o?Qr(o):null,l=`<div><div class="ov-cap">Last change</div><div class="ov-row">${o?`<span title="${C("by "+o.actor)}" style="display:flex">${Yt(o.actor,32,"",s)}</span>`:`<span class="ov-tile">${Jo.clock}</span>`}<span class="t">${i?`<button type="button" class="ov-name" data-path="${C(i.path)}" title="${C(i.path)}">${x(i.name||pn(i.path))}</button><span class="ov-sub" title="${C(sa(i.mtime))}">${x(kn(i.mtime))} · ${x(i.folder||"Top level")}${o?` · by ${x(Oi(o,ks()))}`:""}</span>`:'<span class="ov-name">Nothing yet</span><span class="ov-sub">Changes to notes show up here</span>'}</span></div></div>`,c=`<div><div class="ov-cap">Largest folders</div>${n.length?`<div class="ov-bars">${n.slice(0,vh).map(([d,p])=>{const h=C(k4(d)),u=d==="Root"?"Top level":d;return`<button type="button" class="ov-bar" data-folder="${C(d)}" aria-label="${C(`${u}: ${Zt(p,"note")}`)}">
|
|
6514
6534
|
<span class="l"><span class="d" style="background:${h}"></span><span>${x(u)}</span></span>
|
|
6515
6535
|
<span class="tr"><i style="width:${Math.max(4,Math.round(p/a*100))}%;background:${h}"></i></span><span class="c">${p}</span></button>`}).join("")}</div>${n.length>vh?`<div class="ov-more">+${Zt(n.length-vh,"more folder")}</div>`:""}`:'<div class="ov-sub">No notes yet.</div>'}</div>`;t.innerHTML=`<div class="ov-facts">${l}${c}</div>`,requestAnimationFrame(()=>_U(n.length)),t.querySelectorAll("[data-path]").forEach(d=>d.onclick=()=>te.openNote(d.dataset.path)),t.querySelectorAll("[data-folder]").forEach(d=>{d.onclick=()=>nt.selectFolder(d.dataset.folder==="Root"?"":d.dataset.folder)})}function CU(t){const e=t.name||t.id;return Qo.filter(n=>{if(n.source!=="agent")return!1;const a=Qr(n)??"";return a?a===t.id:n.actor===e})}function Jy(){const t=Date.now()/1e3;return ro.map(n=>{const a=CU(n),i=a[0],o=i?t-i.ts:1/0;return{k:n,items:a,last:i,active:n.enabled!==!1&&o<hU,since:o}}).sort((n,a)=>Number(a.active)-Number(n.active)||n.since-a.since||(n.k.name||"").localeCompare(a.k.name||""))}function LU(){x4||(x4=!0,window.addEventListener("resize",()=>{gh=v4,vh=b4,yh(),Ym()}));const t=document.getElementById("ovAgents"),e=t?.querySelectorAll(":scope > .ov-li");if(!t||!e?.length)return;const n=Jy().length;if(e.length>=n)return;const a=getComputedStyle(t),i=Array.from(t.children).reduce((c,d)=>c+d.offsetHeight,0),o=t.clientHeight-parseFloat(a.paddingTop)-parseFloat(a.paddingBottom)-i,s=e[0].offsetHeight,r=t.querySelector(".ov-foot")?.offsetHeight||0,l=e.length+Math.floor((o+r)/s)>=n?n:e.length+Math.floor(o/s);l>e.length&&(gh=l,yh())}function yh(){const t=document.getElementById("ovAgents");if(!t)return;A4(),M4(),I4();const e=Jy();H("#ovAgN").textContent=e.length?String(e.length):"";let n;lo?e.length?n=e.slice(0,gh).map(a=>{const i=a.k.name||a.k.id,s=a.k.enabled===!1?'<span class="ov-st off">Turned off</span>':a.active?'<span class="ov-st on"><span class="cc-dot ok" style="box-shadow:none;width:7px;height:7px"></span>Active now</span>':a.last?`<span class="ov-st">Seen ${Zy(a.last.ts)}</span>`:`<span class="ov-st">${Gy.has(a.k.id)?"Signed in, nothing in 24h":a.k.last_used?"Nothing in 24h":"Not connected yet"}</span>`,r=a.last?`<span class="sep">·</span><span>${x(Wa(da(a.last)))}</span>`:"",l=AU(a.items.map(p=>p.ts),30,60),c=l.reduce((p,h)=>p+h,0),d=c?`<span class="sp" title="${Zt(c,"action")} in the last 30 minutes">${Su(l,56,24)}</span>`:"";return`<button type="button" class="ov-li" data-agent="${C(i)}" data-kid="${C(a.k.id)}" style="--ag:${C(An(i,a.k.id))}">${Yt(i,32,a.active?"live":"",a.k.id)}<span class="t"><span class="n"><span>${x(i)}</span></span><span class="s">${s}${r}</span></span>${d}
|
|
6516
|
-
<span class="m"><b>${a.items.length.toLocaleString()}</b>${a.items.length===1?"action":"actions"}</span></button>`}).join("")+(e.length>gh?`<div class="ov-foot"><button type="button" class="ov-lnk" data-more>+${Zt(e.length-gh,"more agent")}</button></div>`:""):n=bh(Jo.agent,"No agents yet","Connect Claude, ChatGPT, Cursor or another AI app so it can remember things here.",`<button type="button" class="btn primary sm" id="ovNewKey">${ve.plus}New agent</button>`):n=Oo(3),ti(t,n)&&(requestAnimationFrame(LU),t.querySelector("#ovNewKey")?.addEventListener("click",Zm),t.querySelector("[data-more]")?.addEventListener("click",()=>te.go("keys")),t.querySelectorAll("[data-agent]").forEach(a=>{a.onclick=()=>{if(a.dataset.kid){hr(a.dataset.kid,"activity");return}try{sessionStorage.setItem("memora.activity.agent",a.dataset.agent)}catch{}te.go("logs")}}))}function E4(t){return Qo.find(e=>(e.source==="vault"||e.source==="agent"&&m4.test(e.action))&&e.paths.includes(t))}function Qy(){const t=document.getElementById("ovRecent");if(!t)return;const e=en().filter(o=>o.mtime).sort((o,s)=>(s.mtime||0)-(o.mtime||0)).slice(0,Wy),n=o=>{const s=new Date(o*1e3),r=new Date,l=Math.round((new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime()-new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime())/864e5);return l<=0?"Today":l===1?"Yesterday":l<7?s.toLocaleDateString(void 0,{weekday:"long"}):s.toLocaleDateString(void 0,{month:"short",day:"numeric"})};let a="";const i=e.length?e.map(o=>{const s=n(o.mtime||0),r=s!==a?`<div class="ov-day">${x(s)}</div>`:"";a=s;const l=E4(o.path),c=l?Qr(l):null,d=l?`<span class="sep">·</span><span class="who">${Yt(l.actor,18,"",c)}<span>${x(Oi(l,ks()))}</span></span>`:"";return`${r}<button type="button" class="ov-li" data-path="${C(o.path)}" title="${C(o.path)}"><span class="ov-tile fc" style="--fc:${C(Yn(o.folder||""))}">${ve.note}</span><span class="t"><span class="n"><span>${x(o.name||
|
|
6536
|
+
<span class="m"><b>${a.items.length.toLocaleString()}</b>${a.items.length===1?"action":"actions"}</span></button>`}).join("")+(e.length>gh?`<div class="ov-foot"><button type="button" class="ov-lnk" data-more>+${Zt(e.length-gh,"more agent")}</button></div>`:""):n=bh(Jo.agent,"No agents yet","Connect Claude, ChatGPT, Cursor or another AI app so it can remember things here.",`<button type="button" class="btn primary sm" id="ovNewKey">${ve.plus}New agent</button>`):n=Oo(3),ti(t,n)&&(requestAnimationFrame(LU),t.querySelector("#ovNewKey")?.addEventListener("click",Zm),t.querySelector("[data-more]")?.addEventListener("click",()=>te.go("keys")),t.querySelectorAll("[data-agent]").forEach(a=>{a.onclick=()=>{if(a.dataset.kid){hr(a.dataset.kid,"activity");return}try{sessionStorage.setItem("memora.activity.agent",a.dataset.agent)}catch{}te.go("logs")}}))}function E4(t){return Qo.find(e=>(e.source==="vault"||e.source==="agent"&&m4.test(e.action))&&e.paths.includes(t))}function Qy(){const t=document.getElementById("ovRecent");if(!t)return;const e=en().filter(o=>o.mtime).sort((o,s)=>(s.mtime||0)-(o.mtime||0)).slice(0,Wy),n=o=>{const s=new Date(o*1e3),r=new Date,l=Math.round((new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime()-new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime())/864e5);return l<=0?"Today":l===1?"Yesterday":l<7?s.toLocaleDateString(void 0,{weekday:"long"}):s.toLocaleDateString(void 0,{month:"short",day:"numeric"})};let a="";const i=e.length?e.map(o=>{const s=n(o.mtime||0),r=s!==a?`<div class="ov-day">${x(s)}</div>`:"";a=s;const l=E4(o.path),c=l?Qr(l):null,d=l?`<span class="sep">·</span><span class="who">${Yt(l.actor,18,"",c)}<span>${x(Oi(l,ks()))}</span></span>`:"";return`${r}<button type="button" class="ov-li" data-path="${C(o.path)}" title="${C(o.path)}"><span class="ov-tile fc" style="--fc:${C(Yn(o.folder||""))}">${ve.note}</span><span class="t"><span class="n"><span>${x(o.name||pn(o.path))}</span></span><span class="s"><span>${x(o.folder||"Top level")}</span>${d}</span></span><span class="m" title="${C(sa(o.mtime))}">${Zy(o.mtime||0)}</span></button>`}).join("")+g4(e.length,"That is every note."):bh(ve.note,"No changes yet","Notes you or your AIs write show up here, newest first.");ti(t,i)&&t.querySelectorAll("[data-path]").forEach(o=>o.onclick=()=>te.openNote(o.dataset.path))}function ew(){const t=document.getElementById("ovAct");if(!t)return;const e=new Set(ro.map(r=>r.id)),n=new Set(ro.map(r=>r.name||r.id)),a=Date.now()/1e3,i=ks(),o=Qo.filter(r=>!ci(r)&&a-r.ts<uU).slice(0,Wy),s=lo?o.length?o.map(r=>{const l=Qr(r)??"",c=r.source==="agent"&&l!=="mnemo"&&(l?!e.has(l):!n.has(r.actor)),d=!!r.live&&a-r.ts<2,p=Oi(r,i),h=Wa(da(r)),u=la(r),f=dr(r)?'<span class="ov-st"><span class="cc-dot run"></span>Working…</span>':u?`<span class="ov-st off">${u==="refused"?"Refused":"Did not work"}</span>`:"";return`<div class="ov-li${c?" gone":""}${d?" new":""}" role="button" tabindex="0" data-act="${C(r.id)}" style="--ag:${C(An(r.actor,l||null))}" aria-label="${C(`${p} ${h}`)}"${c?' title="No longer connected"':""}>${Yt(r.actor,32,r.running?"live":"",l||null)}
|
|
6517
6537
|
<span class="t"><span class="sn"><span class="ag-who">${x(p)}</span> ${x(h)}</span></span>
|
|
6518
6538
|
<span class="m"><span title="${C(sa(r.ts))}">${Zy(r.ts)}</span>${f}</span></div>`}).join("")+g4(o.length,"Nothing else in the last 24 hours."):bh(Jo.pulse,"Quiet for now","Nothing in the last 24 hours. What your AIs do shows up here as it happens."):Oo(8);ti(t,s)}function _4(){const t=new Date;t.setHours(0,0,0,0);const e=t.getTime()/1e3;return Qo.filter(n=>n.ts>=e&&n.source==="agent"&&!ci(n)&&Oi(n)!=="You")}function tw(){const t=document.getElementById("ovToday");if(!t)return;const e=_4(),n=e.filter(o=>la(o)!=="refused"),a=bu(n,!0,900,3600);RU(e,n.length);let i;lo?a.length?i=a.slice(0,jy).map(o=>Q2(o.it,{burst:o,compact:!0})).join("")+(a.length>jy?`<div class="ov-foot"><button type="button" class="ov-lnk" data-all>${Zt(a.length-jy,"more thing")} today</button></div>`:""):i=ro.length?bh(Jo.pulse,"Nothing yet today","When your AIs read or write notes, you see it here in plain sentences."):bh(Jo.agent,"No AI connected yet","Connect an AI app, and everything it remembers for you shows up here.",`<button type="button" class="btn primary sm" data-new-agent>${ve.plus}Connect an AI</button>`):i=Oo(3),ti(t,i.replace(/<span title="[^"]*">(\d\d:\d\d) · [^<]*<\/span>/g,"<span>$1</span>"))&&(t.querySelector("[data-new-agent]")?.addEventListener("click",Zm),t.querySelector("[data-all]")?.addEventListener("click",()=>te.go("logs")))}const Rc={read:"#7dd3fc",write:"#5eead4",refused:"#fda4af"};function RU(t,e){const n=document.getElementById("ovTodayN"),a=document.getElementById("ovTodayU"),i=document.getElementById("ovTodayLg"),o=document.getElementById("ovTodayChart");if(!n||!a||!i||!o)return;n.textContent=lo?e.toLocaleString():"–",a.textContent=e===1?"action so far":"actions so far";const s=Array.from({length:24},()=>({read:0,write:0,refused:0}));let r=0,l=0,c=0;for(const p of t){const h=s[new Date(p.ts*1e3).getHours()];la(p)==="refused"?(h.refused++,c++):m4.test(p.action)?(h.write++,l++):(h.read++,r++)}const d=(p,h,u)=>`<span><i style="--c:${p}"></i><b>${h.toLocaleString()}</b>${u}</span>`;ti(i,lo?d(Rc.read,r,r===1?"read":"reads")+d(Rc.write,l,l===1?"change":"changes")+(c?d(Rc.refused,c,"refused"):""):" "),ti(o,PU(s))}function PU(t){const a=new Date,i=a.getHours()+a.getMinutes()/60;let o=0,s=0,r=0;const l=[{t:0,r:0,w:0,x:0}];for(let w=0;w<24&&w<i;w++)o+=t[w].read,s+=t[w].write,r+=t[w].refused,l.push({t:Math.min(w+1,i),r:o,w:s,x:r});const c=Math.max(1,o+s+r),d=w=>w/24*240,p=w=>82-w/c*76,h=w=>l.map((A,_)=>`${_?"L":"M"}${d(A.t).toFixed(1)},${p(w(A)).toFixed(1)}`).join(""),u=(w,A)=>h(w)+l.slice().reverse().map(_=>`L${d(_.t).toFixed(1)},${p(A(_)).toFixed(1)}`).join("")+"Z",f=[{c:Rc.read,top:w=>w.r,low:()=>0,id:"r"},{c:Rc.write,top:w=>w.r+w.w,low:w=>w.r,id:"w"},{c:Rc.refused,top:w=>w.r+w.w+w.x,low:w=>w.r+w.w,id:"x"}],v=f.map(w=>`<linearGradient id="ovg-${w.id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${w.c}" stop-opacity=".42"/><stop offset="1" stop-color="${w.c}" stop-opacity=".06"/></linearGradient>`).join(""),g=f.map(w=>`<path d="${u(w.top,w.low)}" fill="url(#ovg-${w.id})"/><path d="${h(w.top)}" fill="none" stroke="${w.c}" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"/>`).join(""),m=[.25,.5,.75].map(w=>`<line x1="${240*w}" y1="0" x2="${240*w}" y2="84" class="g"/>`).join(""),b=l[l.length-1],k=d(b.t),y=p(b.r+b.w+b.x);return`<svg viewBox="0 0 240 84" preserveAspectRatio="none" aria-hidden="true"><defs>${v}</defs>${m}
|
|
6519
6539
|
<line x1="0" y1="82" x2="240" y2="82" class="b"/><line x1="${k}" y1="82" x2="240" y2="82" class="later"/>${g}
|
|
@@ -6584,7 +6604,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
|
6584
6604
|
@media (prefers-reduced-motion:reduce){.mf{animation:none}}
|
|
6585
6605
|
`;class hB{constructor(e,n){this.host=e,this.src=n,this.acts=[],this.active=0,this.query=V4(""),this.timer=0,Ue("map-find-css",pB),this.box=document.createElement("div"),this.box.className="mf",this.box.hidden=!0,this.box.innerHTML=`<div class="mf-head"></div><div class="mf-list" role="listbox" aria-label="Search results"></div>
|
|
6586
6606
|
<div class="mf-foot"><span><kbd>↑</kbd><kbd>↓</kbd>move</span><span><kbd>Enter</kbd>open</span><span><kbd>Tab</kbd>use tag or folder</span><span><kbd>Esc</kbd>close</span></div>`,e.root.appendChild(this.box),this.head=this.box.querySelector(".mf-head"),this.list=this.box.querySelector(".mf-list"),this.box.addEventListener("pointerdown",a=>{a.target.closest("input")||a.preventDefault()}),this.list.addEventListener("click",a=>{const i=a.target.closest("[data-k]");i&&this.run(Number(i.dataset.k),!1)}),this.list.addEventListener("pointermove",a=>{const i=a.target.closest("[data-k]");i&&Number(i.dataset.k)!==this.active&&(this.active=Number(i.dataset.k),this.paintActive(!1))}),this.head.addEventListener("click",a=>{const i=a.target.closest("[data-drop]");i&&this.dropToken(i.dataset.drop);const o=a.target.closest("[data-try]");o&&this.setInput(o.dataset.try||"")}),e.input.setAttribute("role","combobox"),e.input.setAttribute("aria-autocomplete","list"),e.input.setAttribute("aria-expanded","false")}get el(){return this.box}get isOpen(){return!this.box.hidden}input(){clearTimeout(this.timer),this.timer=window.setTimeout(()=>{this.refresh(),this.show()},60)}show(){this.place(),this.box.hidden&&(this.box.hidden=!1,this.host.input.setAttribute("aria-expanded","true"),this.refresh())}hide(){this.box.hidden=!0,this.host.input.setAttribute("aria-expanded","false")}update(){this.query.raw&&this.refresh()}clear(){this.host.input.value="",this.refresh()}destroy(){clearTimeout(this.timer),this.box.remove()}key(e){const n=this.acts.length;if(e.key==="ArrowDown"||e.key==="ArrowUp")return this.isOpen?n&&(this.active=(this.active+(e.key==="ArrowDown"?1:n-1))%n,this.paintActive(!0)):this.show(),!0;if(e.key==="Enter")return n&&this.run(this.active,!1),!0;if(e.key==="Tab"&&!e.shiftKey&&this.isOpen){const a=this.acts[this.active];return a&&(a.kind==="tag"||a.kind==="folder"||a.kind==="query")?(this.run(this.active,!0),!0):!1}return e.key==="Escape"?(this.host.input.value?this.clear():this.hide(),!0):!1}place(){const e=this.host.anchor();if(!e)return;const n=e.getBoundingClientRect(),a=this.host.root.getBoundingClientRect();this.host.compact()?(this.box.style.left="12px",this.box.style.right="12px",this.box.style.width="auto"):(this.box.style.left=n.left-a.left+"px",this.box.style.right="",this.box.style.width=Math.max(n.width,Math.min(440,a.width-(n.left-a.left)-16))+"px"),this.box.style.top=n.bottom-a.top+8+"px"}setInput(e){this.host.input.value=e,this.host.input.focus({preventScroll:!0});const n=e.length;this.host.input.setSelectionRange(n,n),this.refresh(),this.show()}complete(e){const n=this.host.input.value,a=n.split(/(\s+)/);!/\s$/.test(n)&&a.length?a[a.length-1]=e:a.push(e),this.setInput(a.join("").trimStart()+" ")}dropToken(e){const n=this.host.input.value.split(/\s+/).filter(a=>a&&a.toLowerCase()!==e.toLowerCase()).join(" ");this.setInput(n?n+" ":"")}run(e,n){const a=this.acts[e];a&&(a.kind==="node"?(dB(a.item.id),this.hide(),this.host.input.blur(),this.src.pick(a.item)):a.kind==="tag"?this.complete("#"+a.tag):a.kind==="folder"?(this.complete("in:"+a.folder),n||this.src.folder?.(a.region)):this.setInput(a.q))}refresh(){const e=this.host.input.value;this.query=V4(e);const n=this.query,a=this.src.items().map(g=>{const m=lt(g.id);return m&&m!==g.name?{...g,name:m}:g}),i=this.src.noun||"note";this.acts=[],this.active=0;const o=[],s=(g,m)=>{o.push(m.replace("data-k",`data-k="${this.acts.length}"`)),this.acts.push(g)},r=(g,m)=>{const b=g?.why,k=b?.field==="name"?Ah(m.name,b.ranges):x(m.name),y=b?.field==="folder"?Ah(m.folder,b.ranges):x(sB(m.folder)),w=m.tags.slice(0,3);b?.tag&&!w.includes(b.tag)&&w.unshift(b.tag);const A=w.slice(0,3).map(S=>`<span class="t">#${b?.tag===S?Ah(S,b.ranges):x(S)}</span>`).join(""),_=b?.badge?`<span class="mf-why${b.score>=84?" top":""}" title="${C(b.text)}">${x(b.badge)}</span>`:`<span class="mf-n">${tg(m.degree,"link")}</span>`;return`<div class="mf-row" role="option" data-k style="--c:${C(m.color)}"><i></i>
|
|
6587
|
-
<div class="mf-main"><span class="mf-name">${k}</span><div class="mf-sub"><span>${y}</span>${A}</div></div>${_}</div>`},l=new Map,c=new Map;for(const g of a){for(const k of g.tags)l.set(k,(l.get(k)||0)+1);const m=g.folder||"Root",b=c.get(m);b?b.n++:c.set(m,{n:1,region:g.region,color:g.color})}if(!e.trim()){this.src.highlight(null),this.host.setCount("");const g=new Map(a.map(_=>[_.id,_])),m=X4().map(_=>g.get(_)).filter(_=>!!_&&!this.src.hidden?.(_.region));if(m.length){o.push('<div class="mf-sec">Recent</div>');for(const _ of m.slice(0,4))s({kind:"node",item:_},r(null,_))}const b=a.filter(_=>!this.src.hidden?.(_.region)&&!m.includes(_)).sort((_,S)=>S.degree-_.degree).slice(0,m.length?4:5);if(b.length){o.push('<div class="mf-sec">Most connected</div>');for(const _ of b)s({kind:"node",item:_},r(null,_))}const k=[...l.entries()].sort((_,S)=>S[1]-_[1])[0]?.[0],y=[...c.entries()].filter(([_])=>_!=="Root").sort((_,S)=>S[1].n-_[1].n)[0]?.[0],w=y?y.split("/").pop():"",A=(_,S,T)=>`<button type="button" class="mf-try" data-try="${C(S)}" title="${C(T)}">${x(_)}</button>`;this.head.innerHTML="<span>Try</span>"+A("#"+(k||"tag"),k?`#${k} `:"#","Notes with a tag; the start of the tag is enough")+A("in:"+(w||"folder"),w?`in:${w} `:"in:","Notes inside a folder")+A("name words","","Plain words match names first, then tags and folders")+'<span class="grow"></span><span>Matches light up on the map</span>',this.paint(o);return}const{hits:d,held:p}=lB(a,n,this.src.hidden?.bind(this.src));this.src.highlight(new Set(d.map(g=>g.item.id))),this.host.setCount(d.length?String(d.length):"none");const h=[...n.tags.map(g=>["#"+g,`#${g}`]),...n.folders.map(g=>["in:"+g,`in: ${g}`])].map(([g,m])=>`<span class="mf-chip">${x(m)}<button type="button" data-drop="${C(g)}" aria-label="Remove ${C(m)}">×</button></span>`).join(""),u=n.text?` for “<b>${x(n.text)}</b>”`:"";this.head.innerHTML=h+`<span>${d.length?`<b>${tg(d.length,i)}</b>${u} lit on the map`:`No ${i}s${u}`}${p?` · ${p} more in hidden folders`:""}</span>`;const f=n.partial;if(f?.kind==="tag"||!f&&n.text&&!n.tags.length){const g=f?.kind==="tag"?f.value:n.text,m=[...l.entries()].filter(([b])=>b.toLowerCase().includes(g)).sort((b,k)=>Number(k[0].toLowerCase().startsWith(g))-Number(b[0].toLowerCase().startsWith(g))||k[1]-b[1]).slice(0,f?6:3);if(m.length){o.push(`<div class="mf-sec">Tags <span>${f?"Tab or click to filter by it":""}</span></div>`);for(const[b,k]of m){const y=b.toLowerCase().indexOf(g);s({kind:"tag",tag:b},`<div class="mf-row" role="option" data-k><i class="tg">#</i><div class="mf-main"><span class="mf-name">${Ah(b,g&&y>=0?[[y,y+g.length]]:[])}</span></div><span class="mf-n">${tg(k,i)}</span></div>`)}}}if(f?.kind==="folder"||!f&&n.text&&!n.folders.length){const g=f?.kind==="folder"?f.value:n.text,m=[...c.entries()].filter(([b])=>b!=="Root"&&b.toLowerCase().includes(g)).sort((b,k)=>k[1].n-b[1].n).slice(0,f?6:3);if(m.length){o.push(`<div class="mf-sec">Folders <span>${f?"Tab to filter · click to go there":""}</span></div>`);for(const[b,k]of m){const y=b.toLowerCase().indexOf(g);s({kind:"folder",folder:b.split("/").pop()||b,region:k.region},`<div class="mf-row" role="option" data-k style="--c:${C(k.color)}"><i class="sq"></i><div class="mf-main"><span class="mf-name">${Ah(b,g&&y>=0?[[y,y+g.length]]:[])}</span></div><span class="mf-n">${tg(k.n,i)}</span></div>`)}}}if(d.length){o.push(`<div class="mf-sec">${i[0].toUpperCase()+i.slice(1)}s <span>${d.length>Mh?`top ${Mh} of ${d.length}`:""}</span></div>`);for(const g of d.slice(0,Mh))s({kind:"node",item:g.item},r(g,g.item));d.length>Mh&&o.push(`<div class="mf-more">${d.length-Mh} more are lit on the map. Add a word, a #tag or in:folder to narrow.</div>`)}else if(!o.length||!this.acts.length){const g=cB(a,n.text);if(o.push(`<div class="mf-empty">Nothing matches${n.text?` “<b>${x(n.text)}</b>”`:""}${n.tags.length||n.folders.length?" with these filters":""}.${p?` ${p} ${i}s match in hidden folders: show them in Folders.`:""}</div>`),g.length){o.push('<div class="mf-sec">Did you mean</div>');for(const m of g)s({kind:"node",item:m.item},r(m,m.item))}(n.tags.length||n.folders.length)&&(o.push('<div class="mf-sec">Try</div>'),s({kind:"query",q:n.text},`<div class="mf-tip" role="option" data-k><code>no filters</code><span>search “${x(n.text||"…")}” without #tag and in:</span></div>`))}const v=this.acts.findIndex(g=>g.kind==="node");v>0&&!f&&(this.active=v),this.paint(o)}paint(e){this.list.innerHTML=e.join(""),this.paintActive(!1)}paintActive(e){const n=this.list.querySelectorAll("[data-k]");let a=null;n.forEach(i=>{const o=Number(i.dataset.k)===this.active;i.setAttribute("aria-selected",String(o)),o?a=i:i.removeAttribute("id")}),a?(a.id="mfActive",this.host.input.setAttribute("aria-activedescendant","mfActive"),e&&a.scrollIntoView({block:"nearest"})):this.host.input.removeAttribute("aria-activedescendant")}}function Th(){const t=window.innerWidth;return t<=760?"phone":t<=1100?"tablet":"desktop"}const ow=()=>"memora.viewChrome.v3."+Th(),qs=()=>Th()==="phone";function sw(){const t=Th();return{minimap:t==="desktop",controls:t!=="phone"}}function K4(){const t=sw();try{const e=JSON.parse(localStorage.getItem(ow())||"{}");return{minimap:e.minimap??t.minimap,controls:e.controls??t.controls}}catch{return t}}const Z4="memora.map.dots";function rw(){try{return localStorage.getItem(Z4)!=="0"}catch{return!0}}function uB(t){try{localStorage.setItem(Z4,t?"1":"0")}catch{}document.documentElement.classList.toggle("no-dots",!t),window.dispatchEvent(new Event("memora:dots"))}document.documentElement.classList.toggle("no-dots",!rw());function J4(t){try{localStorage.setItem(ow(),JSON.stringify(t))}catch{}}const Q4=[["brain","3D",'<svg class="i" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 4 7.5v9L12 21l8-4.5v-9z"/><path d="m4 7.5 8 4.5 8-4.5M12 12v9"/></svg>',"3D: your notes as points in a 3D brain"],["graph","Graph",V("graph"),"Graph: a map of the links between notes"],["canvas","Canvas",V("canvas"),"Canvas: your notes as cards on a board"]],fB={brain:{title:"Your brain is empty",text:"Every note becomes a point of light here, grouped by folder. The guide shows how to have an AI save its knowledge here, or write a note yourself."},graph:{title:"No notes to map yet",text:"Notes and the links between them show up here as a map. The guide shows how to have an AI save its knowledge here, or write a note yourself."},canvas:{title:"Your board is empty",text:"Every note becomes a card here, inside a frame for its folder. The guide shows how to have an AI save its knowledge here, or write a note yourself."}};let e5=0;const
|
|
6607
|
+
<div class="mf-main"><span class="mf-name">${k}</span><div class="mf-sub"><span>${y}</span>${A}</div></div>${_}</div>`},l=new Map,c=new Map;for(const g of a){for(const k of g.tags)l.set(k,(l.get(k)||0)+1);const m=g.folder||"Root",b=c.get(m);b?b.n++:c.set(m,{n:1,region:g.region,color:g.color})}if(!e.trim()){this.src.highlight(null),this.host.setCount("");const g=new Map(a.map(_=>[_.id,_])),m=X4().map(_=>g.get(_)).filter(_=>!!_&&!this.src.hidden?.(_.region));if(m.length){o.push('<div class="mf-sec">Recent</div>');for(const _ of m.slice(0,4))s({kind:"node",item:_},r(null,_))}const b=a.filter(_=>!this.src.hidden?.(_.region)&&!m.includes(_)).sort((_,S)=>S.degree-_.degree).slice(0,m.length?4:5);if(b.length){o.push('<div class="mf-sec">Most connected</div>');for(const _ of b)s({kind:"node",item:_},r(null,_))}const k=[...l.entries()].sort((_,S)=>S[1]-_[1])[0]?.[0],y=[...c.entries()].filter(([_])=>_!=="Root").sort((_,S)=>S[1].n-_[1].n)[0]?.[0],w=y?y.split("/").pop():"",A=(_,S,T)=>`<button type="button" class="mf-try" data-try="${C(S)}" title="${C(T)}">${x(_)}</button>`;this.head.innerHTML="<span>Try</span>"+A("#"+(k||"tag"),k?`#${k} `:"#","Notes with a tag; the start of the tag is enough")+A("in:"+(w||"folder"),w?`in:${w} `:"in:","Notes inside a folder")+A("name words","","Plain words match names first, then tags and folders")+'<span class="grow"></span><span>Matches light up on the map</span>',this.paint(o);return}const{hits:d,held:p}=lB(a,n,this.src.hidden?.bind(this.src));this.src.highlight(new Set(d.map(g=>g.item.id))),this.host.setCount(d.length?String(d.length):"none");const h=[...n.tags.map(g=>["#"+g,`#${g}`]),...n.folders.map(g=>["in:"+g,`in: ${g}`])].map(([g,m])=>`<span class="mf-chip">${x(m)}<button type="button" data-drop="${C(g)}" aria-label="Remove ${C(m)}">×</button></span>`).join(""),u=n.text?` for “<b>${x(n.text)}</b>”`:"";this.head.innerHTML=h+`<span>${d.length?`<b>${tg(d.length,i)}</b>${u} lit on the map`:`No ${i}s${u}`}${p?` · ${p} more in hidden folders`:""}</span>`;const f=n.partial;if(f?.kind==="tag"||!f&&n.text&&!n.tags.length){const g=f?.kind==="tag"?f.value:n.text,m=[...l.entries()].filter(([b])=>b.toLowerCase().includes(g)).sort((b,k)=>Number(k[0].toLowerCase().startsWith(g))-Number(b[0].toLowerCase().startsWith(g))||k[1]-b[1]).slice(0,f?6:3);if(m.length){o.push(`<div class="mf-sec">Tags <span>${f?"Tab or click to filter by it":""}</span></div>`);for(const[b,k]of m){const y=b.toLowerCase().indexOf(g);s({kind:"tag",tag:b},`<div class="mf-row" role="option" data-k><i class="tg">#</i><div class="mf-main"><span class="mf-name">${Ah(b,g&&y>=0?[[y,y+g.length]]:[])}</span></div><span class="mf-n">${tg(k,i)}</span></div>`)}}}if(f?.kind==="folder"||!f&&n.text&&!n.folders.length){const g=f?.kind==="folder"?f.value:n.text,m=[...c.entries()].filter(([b])=>b!=="Root"&&b.toLowerCase().includes(g)).sort((b,k)=>k[1].n-b[1].n).slice(0,f?6:3);if(m.length){o.push(`<div class="mf-sec">Folders <span>${f?"Tab to filter · click to go there":""}</span></div>`);for(const[b,k]of m){const y=b.toLowerCase().indexOf(g);s({kind:"folder",folder:b.split("/").pop()||b,region:k.region},`<div class="mf-row" role="option" data-k style="--c:${C(k.color)}"><i class="sq"></i><div class="mf-main"><span class="mf-name">${Ah(b,g&&y>=0?[[y,y+g.length]]:[])}</span></div><span class="mf-n">${tg(k.n,i)}</span></div>`)}}}if(d.length){o.push(`<div class="mf-sec">${i[0].toUpperCase()+i.slice(1)}s <span>${d.length>Mh?`top ${Mh} of ${d.length}`:""}</span></div>`);for(const g of d.slice(0,Mh))s({kind:"node",item:g.item},r(g,g.item));d.length>Mh&&o.push(`<div class="mf-more">${d.length-Mh} more are lit on the map. Add a word, a #tag or in:folder to narrow.</div>`)}else if(!o.length||!this.acts.length){const g=cB(a,n.text);if(o.push(`<div class="mf-empty">Nothing matches${n.text?` “<b>${x(n.text)}</b>”`:""}${n.tags.length||n.folders.length?" with these filters":""}.${p?` ${p} ${i}s match in hidden folders: show them in Folders.`:""}</div>`),g.length){o.push('<div class="mf-sec">Did you mean</div>');for(const m of g)s({kind:"node",item:m.item},r(m,m.item))}(n.tags.length||n.folders.length)&&(o.push('<div class="mf-sec">Try</div>'),s({kind:"query",q:n.text},`<div class="mf-tip" role="option" data-k><code>no filters</code><span>search “${x(n.text||"…")}” without #tag and in:</span></div>`))}const v=this.acts.findIndex(g=>g.kind==="node");v>0&&!f&&(this.active=v),this.paint(o)}paint(e){this.list.innerHTML=e.join(""),this.paintActive(!1)}paintActive(e){const n=this.list.querySelectorAll("[data-k]");let a=null;n.forEach(i=>{const o=Number(i.dataset.k)===this.active;i.setAttribute("aria-selected",String(o)),o?a=i:i.removeAttribute("id")}),a?(a.id="mfActive",this.host.input.setAttribute("aria-activedescendant","mfActive"),e&&a.scrollIntoView({block:"nearest"})):this.host.input.removeAttribute("aria-activedescendant")}}function Th(){const t=window.innerWidth;return t<=760?"phone":t<=1100?"tablet":"desktop"}const ow=()=>"memora.viewChrome.v3."+Th(),qs=()=>Th()==="phone";function sw(){const t=Th();return{minimap:t==="desktop",controls:t!=="phone"}}function K4(){const t=sw();try{const e=JSON.parse(localStorage.getItem(ow())||"{}");return{minimap:e.minimap??t.minimap,controls:e.controls??t.controls}}catch{return t}}const Z4="memora.map.dots";function rw(){try{return localStorage.getItem(Z4)!=="0"}catch{return!0}}function uB(t){try{localStorage.setItem(Z4,t?"1":"0")}catch{}document.documentElement.classList.toggle("no-dots",!t),window.dispatchEvent(new Event("memora:dots"))}document.documentElement.classList.toggle("no-dots",!rw());function J4(t){try{localStorage.setItem(ow(),JSON.stringify(t))}catch{}}const Q4=[["brain","3D",'<svg class="i" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 4 7.5v9L12 21l8-4.5v-9z"/><path d="m4 7.5 8 4.5 8-4.5M12 12v9"/></svg>',"3D: your notes as points in a 3D brain"],["graph","Graph",V("graph"),"Graph: a map of the links between notes"],["canvas","Canvas",V("canvas"),"Canvas: your notes as cards on a board"]],fB={brain:{title:"Your brain is empty",text:"Every note becomes a point of light here, grouped by folder. The guide shows how to have an AI save its knowledge here, or write a note yourself."},graph:{title:"No notes to map yet",text:"Notes and the links between them show up here as a map. The guide shows how to have an AI save its knowledge here, or write a note yourself."},canvas:{title:"Your board is empty",text:"Every note becomes a card here, inside a frame for its folder. The guide shows how to have an AI save its knowledge here, or write a note yourself."}};let e5=0;const rn={search:'<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20.5 20.5-4.3-4.3"/></svg>',filter:'<svg viewBox="0 0 24 24"><path d="M4 7h10M18 7h2M4 17h4M12 17h8"/><circle cx="16" cy="7" r="2"/><circle cx="10" cy="17" r="2"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',minus:'<svg viewBox="0 0 24 24"><path d="M5 12h14"/></svg>',fit:'<svg viewBox="0 0 24 24"><rect x="8" y="8" width="8" height="8" rx="1.6"/><path d="M3.5 3.5 6.5 6.5M20.5 3.5l-3 3M3.5 20.5l3-3M20.5 20.5l-3-3"/></svg>',full:'<svg viewBox="0 0 24 24"><path d="M14 4h6v6M10 20H4v-6M20 4l-6.5 6.5M4 20l6.5-6.5"/></svg>',eyeOff:'<svg viewBox="0 0 24 24"><path d="M3 3l18 18M10.6 5.1A9.8 9.8 0 0 1 12 5c5 0 8.5 4.2 9.5 7-.4 1.1-1.2 2.5-2.4 3.8M6.6 6.6C4.6 7.9 3.2 9.9 2.5 12c1 2.8 4.5 7 9.5 7 1.9 0 3.6-.6 5-1.5"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg>',eye:'<svg viewBox="0 0 24 24"><path d="M2.5 12C3.5 9.2 7 5 12 5s8.5 4.2 9.5 7c-1 2.8-4.5 7-9.5 7s-8.5-4.2-9.5-7z"/><circle cx="12" cy="12" r="3"/></svg>',exitFull:'<svg viewBox="0 0 24 24"><path d="M4 14h6v6M20 10h-6V4M14 10l6.5-6.5M10 14l-6.5 6.5"/></svg>',target:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/></svg>',up:'<svg viewBox="0 0 24 24"><path d="m6 14 6-6 6 6"/></svg>',home:'<svg viewBox="0 0 24 24"><path d="M4 11.5 12 5l8 6.5M6.5 10v9h11v-9"/></svg>',reset:'<svg viewBox="0 0 24 24"><path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5"/><path d="M4 4v4.5h4.5"/></svg>',close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18"/></svg>',layers:'<svg class="tic" viewBox="0 0 24 24"><path d="m12 4 8 4.5-8 4.5-8-4.5z"/><path d="m4 12.5 8 4.5 8-4.5"/><path d="m4 16.5 8 4.5 8-4.5"/></svg>',pulse:'<svg class="tic" viewBox="0 0 24 24"><path d="M3 12h4l3-7 4 14 3-7h4"/></svg>',pad:'<svg viewBox="0 0 24 24"><path d="M7 9h10a4 4 0 0 1 3.9 4.9l-.6 2.6a2.3 2.3 0 0 1-4 1L14.6 16H9.4l-1.7 1.5a2.3 2.3 0 0 1-4-1l-.6-2.6A4 4 0 0 1 7 9z"/><path d="M8 11.5v3M6.5 13h3"/><circle cx="15.5" cy="12" r=".6"/><circle cx="17" cy="13.8" r=".6"/></svg>'},mB=`
|
|
6588
6608
|
:is(.vc,.nc,.mf,.vc-tip,.cv-help){--vc-ctl:var(--surface-2);--vc-ctl-line:var(--line-strong);--vc-ctl-icon:var(--text-2);
|
|
6589
6609
|
--vc-tint:var(--hover);--vc-track:var(--seg-track);--vc-thumb:var(--seg-thumb);--vc-solid:var(--surface-2);--vc-line:var(--line)}
|
|
6590
6610
|
:root[data-theme=light] :is(.vc,.nc,.mf,.vc-tip,.cv-help){--vc-ctl:#ffffff;--vc-solid:#ffffff}
|
|
@@ -6977,28 +6997,28 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
|
6977
6997
|
<div class="vc-p vc-barin">
|
|
6978
6998
|
<nav class="vc-modes" aria-label="View">${Q4.map(([a,i,o,s])=>`<button type="button" data-page="${a}" aria-label="${C(s)}" title="${C(s)}" aria-pressed="${a===e.page}">${o}<span aria-hidden="true">${i}</span></button>`).join("")}</nav>
|
|
6979
6999
|
<span class="vc-sep" aria-hidden="true"></span>
|
|
6980
|
-
<label class="vc-search">${
|
|
7000
|
+
<label class="vc-search">${rn.search}<input type="search" placeholder="${C(e.search.placeholder)}" aria-label="${C(e.search.placeholder)}" autocomplete="off" spellcheck="false"><em></em><button type="button" class="vc-x" title="Clear the search" aria-label="Clear the search" hidden>${rn.close}</button><kbd title="Press / to search">/</kbd><span class="vc-sq" aria-hidden="true">Search</span></label>
|
|
6981
7001
|
<span class="vc-sep" aria-hidden="true"></span>
|
|
6982
7002
|
<div class="vc-tr">
|
|
6983
|
-
<button type="button" class="vc-b vc-reset" data-reset title="Reset this view to its defaults" aria-label="Reset this view to its defaults">${
|
|
6984
|
-
<button type="button" class="vc-b" data-vc="filter" aria-expanded="false" title="Filter and display" aria-label="Filter and display">${
|
|
7003
|
+
<button type="button" class="vc-b vc-reset" data-reset title="Reset this view to its defaults" aria-label="Reset this view to its defaults">${rn.reset}</button>
|
|
7004
|
+
<button type="button" class="vc-b" data-vc="filter" aria-expanded="false" title="Filter and display" aria-label="Filter and display">${rn.filter}<b class="vc-badge"></b></button>
|
|
6985
7005
|
</div>
|
|
6986
7006
|
<aside class="vc-p vc-ovl vc-panel" hidden aria-label="Filter and display">
|
|
6987
|
-
<div class="vc-ph"><h3>Filter and display</h3><button type="button" class="vc-b" data-close title="Close" aria-label="Close">${
|
|
7007
|
+
<div class="vc-ph"><h3>Filter and display</h3><button type="button" class="vc-b" data-close title="Close" aria-label="Close">${rn.close}</button></div>
|
|
6988
7008
|
<div class="vc-pb vc-fade"></div>
|
|
6989
7009
|
</aside>
|
|
6990
7010
|
</div>
|
|
6991
7011
|
|
|
6992
7012
|
</div>
|
|
6993
7013
|
|
|
6994
|
-
<button type="button" class="vc-tab vc-tab-l" data-open="regions" aria-expanded="false" aria-label="Folders: show or hide them" title="Folders: show or hide them">${
|
|
7014
|
+
<button type="button" class="vc-tab vc-tab-l" data-open="regions" aria-expanded="false" aria-label="Folders: show or hide them" title="Folders: show or hide them">${rn.layers}<svg class="tic tx" viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7 7 17"/></svg><span>Folders</span><em data-rn></em></button>
|
|
6995
7015
|
<aside class="vc-drawer vc-ovl vc-drawer-l" data-d="regions" aria-label="Folders">
|
|
6996
7016
|
<div class="vc-dh"><h3>Folders <em data-rn></em></h3></div>
|
|
6997
7017
|
<div class="vc-bulk"><button type="button" data-all="show">Show all</button><button type="button" data-all="hide">Hide all</button></div>
|
|
6998
7018
|
<div class="vc-db vc-fade vc-rl"></div>
|
|
6999
7019
|
</aside>
|
|
7000
7020
|
|
|
7001
|
-
<button type="button" class="vc-tab vc-tab-r" data-open="activity" aria-expanded="false" aria-label="Agent activity" title="Agent activity"><i class="dot"></i>${
|
|
7021
|
+
<button type="button" class="vc-tab vc-tab-r" data-open="activity" aria-expanded="false" aria-label="Agent activity" title="Agent activity"><i class="dot"></i>${rn.pulse}<svg class="tic tx" viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7 7 17"/></svg><span>Activity</span><em data-an></em></button>
|
|
7002
7022
|
<aside class="vc-drawer vc-ovl vc-drawer-r" data-d="activity" aria-label="Agent activity">
|
|
7003
7023
|
<div class="vc-dh"><h3>Activity <em data-an></em></h3></div>
|
|
7004
7024
|
<div class="vc-bulk vc-sub">Agents and what they did last</div>
|
|
@@ -7009,32 +7029,32 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
|
7009
7029
|
<div class="vc-nav-top"><div class="vc-mini" title="Minimap: click or drag to move the view"><canvas></canvas></div>
|
|
7010
7030
|
<div class="vc-globe" role="group" aria-label="Turn the view">
|
|
7011
7031
|
<canvas></canvas>
|
|
7012
|
-
<button type="button" data-g="u" title="Up" aria-label="Up">${
|
|
7013
|
-
<button type="button" data-g="l" title="Left" aria-label="Left">${
|
|
7014
|
-
<button type="button" data-g="r" title="Right" aria-label="Right">${
|
|
7015
|
-
<button type="button" data-g="d" title="Down" aria-label="Down">${
|
|
7016
|
-
<button type="button" data-g="h" title="Default view" aria-label="Default view">${
|
|
7032
|
+
<button type="button" data-g="u" title="Up" aria-label="Up">${rn.up}</button>
|
|
7033
|
+
<button type="button" data-g="l" title="Left" aria-label="Left">${rn.up}</button>
|
|
7034
|
+
<button type="button" data-g="r" title="Right" aria-label="Right">${rn.up}</button>
|
|
7035
|
+
<button type="button" data-g="d" title="Down" aria-label="Down">${rn.up}</button>
|
|
7036
|
+
<button type="button" data-g="h" title="Default view" aria-label="Default view">${rn.home}</button>
|
|
7017
7037
|
</div></div>
|
|
7018
7038
|
<div class="vc-zoom">
|
|
7019
|
-
<button type="button" class="vc-b vc-padbtn" data-open="sheet" title="Controller" aria-label="Controller">${
|
|
7020
|
-
<button type="button" class="vc-b" data-z="in" title="Zoom in (+)" aria-label="Zoom in">${
|
|
7021
|
-
<button type="button" class="vc-b" data-z="out" title="Zoom out (-)" aria-label="Zoom out">${
|
|
7022
|
-
<button type="button" class="vc-b" data-z="fit" title="Fit to screen" aria-label="Fit to screen">${
|
|
7023
|
-
<button type="button" class="vc-b" data-z="full" title="Full screen" aria-label="Full screen">${
|
|
7024
|
-
<button type="button" class="vc-b" data-z="clean" title="Clean view: hide the controls (C)" aria-label="Clean view">${
|
|
7039
|
+
<button type="button" class="vc-b vc-padbtn" data-open="sheet" title="Controller" aria-label="Controller">${rn.pad}</button>
|
|
7040
|
+
<button type="button" class="vc-b" data-z="in" title="Zoom in (+)" aria-label="Zoom in">${rn.plus}</button>
|
|
7041
|
+
<button type="button" class="vc-b" data-z="out" title="Zoom out (-)" aria-label="Zoom out">${rn.minus}</button>
|
|
7042
|
+
<button type="button" class="vc-b" data-z="fit" title="Fit to screen" aria-label="Fit to screen">${rn.fit}</button>
|
|
7043
|
+
<button type="button" class="vc-b" data-z="full" title="Full screen" aria-label="Full screen">${rn.full}</button>
|
|
7044
|
+
<button type="button" class="vc-b" data-z="clean" title="Clean view: hide the controls (C)" aria-label="Clean view">${rn.eyeOff}</button>
|
|
7025
7045
|
</div>
|
|
7026
7046
|
</div>
|
|
7027
|
-
<button type="button" class="vc-unclean" title="Show the controls (C or Esc)">${
|
|
7047
|
+
<button type="button" class="vc-unclean" title="Show the controls (C or Esc)">${rn.eye}<span>Show controls</span></button>
|
|
7028
7048
|
|
|
7029
7049
|
<div class="vc-ec" hidden></div>
|
|
7030
7050
|
<div class="vc-scrim"></div>
|
|
7031
7051
|
<section class="vc-sheet vc-ovl" aria-label="Controller">
|
|
7032
7052
|
<div class="vc-grab"></div>
|
|
7033
|
-
<div class="vc-sh"><h3>Controller</h3><button type="button" class="vc-b" data-close title="Close" aria-label="Close">${
|
|
7053
|
+
<div class="vc-sh"><h3>Controller</h3><button type="button" class="vc-b" data-close title="Close" aria-label="Close">${rn.close}</button></div>
|
|
7034
7054
|
<div class="vc-sgrid"><div data-slot="globe"></div><div data-slot="mini"></div></div>
|
|
7035
7055
|
<div data-slot="labels"></div>
|
|
7036
7056
|
</section>`}place(){const e=this.q(".vc-globe"),n=this.q(".vc-mini");this.phone?(this.q("[data-slot=globe]").appendChild(e),this.q("[data-slot=mini]").appendChild(n)):this.q(".vc-nav-top").append(n,e),this.applyPrefs()}setEmpty(e){this.el.classList.toggle("vc-is-empty",e);const n=this.q(".vc-ec");if(n.hidden===!e)return;if(n.hidden=!e,!e){n.replaceChildren();return}const a=fB[this.o.page],i=Q4.find(o=>o[0]===this.o.page)?.[2]||"";n.innerHTML=`<div class="vc-ec-card" role="status"><span class="vc-ec-ic" aria-hidden="true">${i}</span><h3>${x(a.title)}</h3><p>${x(a.text)}</p>
|
|
7037
|
-
<div class="vc-ec-acts"><button type="button" class="btn primary" data-ec="setup">Open the guide</button><button type="button" class="btn" data-ec="new">${sn.plus}New note</button></div></div>`,n.querySelector("[data-ec=setup]").onclick=()=>te.go("home"),n.querySelector("[data-ec=new]").onclick=()=>te.openNewNote()}shown(){this.markActive()}markActive(){const e=this.o.page;this.el.querySelectorAll(".vc-modes button").forEach(n=>{n.classList.toggle("on",n.dataset.page===e),n.setAttribute("aria-pressed",String(n.dataset.page===e))})}show(e){if(this.open!==e)if(this.close(),this.open=e,this.el.dataset.open=e,this.o.root.dataset.vcOpen=e,this.o.onOverlay?.(),e==="filter")this.panel.hidden=!1,this.q("[data-vc=filter]").classList.add("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","true"),this.renderPanel();else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.add("open");const n=this.q(`[data-open=${e}]`);n.classList.add("on"),n.setAttribute("aria-expanded","true"),e==="activity"&&this.paintAgents()}else e==="sheet"?(this.q(".vc-sheet").classList.add("open"),this.q(".vc-scrim").classList.add("on"),this.o.root.classList.add("vc-sheet-open"),this.renderSheetLabels(),requestAnimationFrame(()=>this.redrawMini())):e==="search"&&(this.q(".vc-search").classList.add("open"),this.sizeSearch(),this.input.focus())}close(){const e=this.open;if(e){if(Ws(),this.open=null,delete this.el.dataset.open,delete this.o.root.dataset.vcOpen,e==="filter")this.panel.hidden=!0,this.q("[data-vc=filter]").classList.remove("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","false");else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.remove("open");const n=this.q(`[data-open=${e}]`);n.classList.remove("on"),n.setAttribute("aria-expanded","false")}else if(e==="sheet")this.q(".vc-sheet").classList.remove("open"),this.q(".vc-scrim").classList.remove("on"),this.o.root.classList.remove("vc-sheet-open");else if(e==="search"){const n=this.q(".vc-search");n.classList.remove("open"),n.style.width=""}}}sizeSearch(){this.q(".vc-search").style.width=""}openPanel(){this.show("filter")}closePanel(){this.open==="filter"&&this.close()}wire(){const e=this.o;this.el.querySelectorAll(".vc-modes button").forEach(c=>{c.onclick=()=>{const d=c.dataset.page;if(d===e.page)return;this.el.querySelectorAll(".vc-modes button").forEach(h=>h.classList.toggle("on",h===c));const p=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;clearTimeout(e5),e5=window.setTimeout(()=>{te.go(d),this.markActive()},p?0:140)}}),this.q(".vc-search").addEventListener("click",()=>{qs()&&this.open!=="search"&&this.show("search")});const a=this.input,i=e.search.find?new hB({input:a,root:e.root,setCount:c=>this.setCount(c),anchor:()=>this.q(".vc-search"),compact:qs},e.search.find):null;this.finder=i,a.oninput=()=>{i?.input(),e.search.onInput?.(a.value.trim())},a.onfocus=()=>{qs()&&this.open!=="search"?this.show("search"):!qs()&&this.open&&this.open!=="search"&&this.close(),i&&requestAnimationFrame(()=>i.show()),e.search.onFocus?.()},a.addEventListener("blur",()=>{window.setTimeout(()=>{document.activeElement!==a&&i?.hide()},120),qs()&&!a.value&&window.setTimeout(()=>this.open==="search"&&this.close(),150)}),a.onkeydown=c=>{if(i){if(c.key==="Escape"&&!a.value){i.hide(),a.blur(),this.open==="search"&&this.close(),c.preventDefault();return}i.key(c)&&c.preventDefault();return}if(e.search.onKey?.(c,a.value.trim())){c.preventDefault();return}c.key==="Escape"&&(a.value="",e.search.onInput?.(""),a.blur(),this.open==="search"&&this.close())},this.q("[data-vc=filter]").onclick=()=>this.open==="filter"?this.close():this.show("filter"),document.addEventListener("pointerdown",this.onDocDown,!0);const o=this.q("[data-reset]"),s=()=>{const c=JSON.stringify(this.prefs)!==JSON.stringify(sw())||!!e.changed?.();if(o.classList.contains("dirty")===c)return;o.classList.toggle("dirty",c);const d=c?"Reset: this view differs from its defaults":"Reset this view to its defaults";o.title=d,o.setAttribute("aria-label",d)};this.dirtyTimer=window.setInterval(()=>{!document.hidden&&this.el.isConnected&&s()},400),o.onclick=()=>{o.classList.remove("spin"),o.offsetWidth,o.classList.add("spin"),this.close();try{localStorage.removeItem(ow())}catch{}this.prefs=sw(),e.reset(),this.applyPrefs(),this.refreshRegions()},this.el.querySelectorAll("[data-open]").forEach(c=>{c.onclick=()=>{const d=c.dataset.open;this.open===d?this.close():this.show(d)}}),this.el.querySelectorAll("[data-close]").forEach(c=>c.onclick=()=>this.close()),this.q(".vc-scrim").onclick=()=>this.close(),this.el.querySelectorAll("[data-all]").forEach(c=>{c.onclick=()=>{e.regions.setAll(c.dataset.all==="hide"),this.refreshRegions()}}),e.root.addEventListener("keydown",c=>{c.key==="Escape"&&this.open&&this.open!=="search"?this.close():c.key==="Escape"&&this.clean&&this.setClean(!1)},{signal:this.off.signal}),document.addEventListener("keydown",c=>{if(c.key.toLowerCase()!=="c"||c.ctrlKey||c.metaKey||c.altKey||!this.el.isConnected)return;const d=c.target;d&&(d.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(d.tagName))||document.querySelector("[aria-modal=true], dialog[open]")||(c.preventDefault(),this.setClean(!this.clean))},{signal:this.off.signal}),this.q(".vc-unclean").onclick=()=>this.setClean(!1),this.el.querySelectorAll("[data-z]").forEach(c=>{c.onclick=()=>{const d=c.dataset.z;d==="in"?e.nav.zoom(1.4):d==="out"?e.nav.zoom(1/1.4):d==="fit"?e.nav.fit():d==="clean"?this.setClean(!0):this.toggleFullscreen()}}),document.addEventListener("fullscreenchange",this.onFs);const r={u:[0,-1],d:[0,1],l:[-1,0],r:[1,0]};this.el.querySelectorAll(".vc-globe [data-g]").forEach(c=>{const d=c.dataset.g||"";if(d==="h"){c.onclick=()=>e.nav.home();return}const p=()=>e.nav.nudge(r[d][0],r[d][1]);c.onpointerdown=u=>{u.preventDefault(),p(),clearTimeout(this.repeat);const f=()=>{p(),this.repeat=window.setTimeout(f,110)};this.repeat=window.setTimeout(f,380)};const h=()=>clearTimeout(this.repeat);c.onpointerup=h,c.onpointerleave=h,c.onpointercancel=h,c.onkeydown=u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),p())}});const l=this.q(".vc-mini");if(e.minimapNav){const c=p=>{const h=l.getBoundingClientRect();e.minimapNav(Math.max(0,Math.min(1,(p.clientX-h.left)/h.width)),Math.max(0,Math.min(1,(p.clientY-h.top)/h.height)))};let d=!1;l.onpointerdown=p=>{p.stopPropagation(),d=!0,l.setPointerCapture(p.pointerId),c(p)},l.onpointermove=p=>d&&c(p),l.onpointerup=()=>d=!1}for(const c of this.el.querySelectorAll(".vc-p,.vc-tab,.vc-drawer,.vc-sheet,.vc-scrim"))c.addEventListener("pointerdown",d=>d.stopPropagation()),c.addEventListener("wheel",d=>d.stopPropagation(),{passive:!0}),c.addEventListener("dblclick",d=>d.stopPropagation())}renderPanel(){if(this.open!=="filter")return;const e=this.q(".vc-pb"),n=e.scrollTop,a=this.o.page==="brain"?"turn the brain":"move the map";e.innerHTML=(this.phone?"":"<h4>View</h4>"+po("vc-minimap","Minimap",this.prefs.minimap,"The small overview at the bottom left. Click or drag it to move the view.")+po("vc-controls","Orbit globe",this.prefs.controls,`The globe at the bottom right: its arrows ${a}, the middle button goes back to the default view.`))+"<h4>Labels</h4>"+this.labelsHTML()+"<h4>Background</h4>"+this.dotsHTML()+"<div data-own></div>",e.querySelectorAll("[data-t^=vc-]").forEach(i=>i.onclick=()=>this.toggleShared(i.dataset.t||"")),this.o.filter(e.querySelector("[data-own]")),n5(e),e.scrollTop=n}dotsHTML(){return po("vc-dots","Dot grid",rw(),"The dots behind 3D, Graph and Canvas. Turn them off for a clean, plain background.")}labelsHTML(){const e=this.o.labels.get();return po("vc-lab-nodes","Note labels",e.nodes,this.o.labels.help.nodes)+po("vc-lab-folders","Folder labels",e.folders,this.o.labels.help.folders)}toggleShared(e){if(e==="vc-dots")uB(!rw());else if(e==="vc-lab-nodes"||e==="vc-lab-folders"){const n=e==="vc-lab-nodes"?"nodes":"folders";this.o.labels.set(n,!this.o.labels.get()[n])}else e==="vc-minimap"?this.prefs.minimap=!this.prefs.minimap:this.prefs.controls=!this.prefs.controls,J4(this.prefs),this.applyPrefs();this.renderPanel(),this.renderSheetLabels()}renderSheetLabels(){if(this.open!=="sheet")return;const e=this.q("[data-slot=labels]");e.innerHTML="<h4>Labels</h4>"+this.labelsHTML()+"<h4>Background</h4>"+this.dotsHTML(),e.querySelectorAll("[data-t]").forEach(n=>n.onclick=()=>this.toggleShared(n.dataset.t||"")),n5(e)}toggleMinimap(){if(this.phone){this.open==="sheet"?this.close():this.show("sheet");return}this.prefs.minimap=!this.prefs.minimap,J4(this.prefs),this.applyPrefs(),this.renderPanel()}setBadge(e){this.q(".vc-badge").textContent=e?String(e):""}setCount(e){this.q(".vc-search em").textContent=e}applyPrefs(){this.q(".vc-mini").classList.toggle("vc-hide",!this.phone&&!this.prefs.minimap),this.q(".vc-globe").classList.toggle("vc-hide",!this.phone&&!this.prefs.controls),this.o.onPrefs?.(this.prefs),this.redrawMini()}refreshRegions(){const e=this.o.regions.list(),n=this.q(".vc-rl"),a=e.filter(o=>!o.hidden).length;this.el.querySelectorAll("[data-rn]").forEach(o=>o.textContent=a===e.length?String(e.length):`${a}/${e.length}`),this.q(".vc-bulk").classList.toggle("vc-hide",e.length<2);const i=!!this.o.regions.focus;n.innerHTML=e.length?e.map(o=>`<div class="vc-rr${o.hidden?" off":""}" style="--c:${C(o.color)}"><button type="button" class="tg" data-r="${C(o.name)}" aria-pressed="${!o.hidden}" title="${o.hidden?"Show":"Hide"} ${C(o.name)}" aria-label="${o.hidden?"Show":"Hide"} ${C(o.name)}"><i></i></button><button type="button" class="t" data-f="${C(o.name)}" title="${i?"Go to":o.hidden?"Show":"Hide"} ${C(o.name)}"><span>${x(o.name)}</span><em>${o.count}</em>${i?sn.target:""}</button></div>`).join(""):'<div class="vc-empty">No folders yet.</div>',n.querySelectorAll("[data-r]").forEach(o=>{o.onclick=()=>{this.o.regions.toggle(o.dataset.r||""),this.refreshRegions()}}),n.querySelectorAll("[data-f]").forEach(o=>{o.onclick=()=>{const s=o.dataset.f||"";if(!this.o.regions.focus){this.o.regions.toggle(s),this.refreshRegions();return}e.find(r=>r.name===s)?.hidden&&(this.o.regions.toggle(s),this.refreshRegions()),this.close(),this.o.regions.focus(s)}})}paintAgents(){const e=Date.now(),n=r=>r.open>0&&e-r.lastAt<12e4||e-r.lastAt<5e3,a=Pl(),i=zd(),o=this.q(".vc-tab-r");if(o.classList.toggle("live",i.length>0),this.el.querySelectorAll("[data-an]").forEach(r=>r.textContent=String(i.length)),o.title=i.length?`${i.length} agent${i.length===1?"":"s"} working now`:"Agent activity",this.open!=="activity")return;const s=this.q(".vc-al");s.innerHTML=a.length?a.slice(0,30).map(r=>{const l=n(r),c=r.lastLabel||r.lastAction||(r.kind==="user"?"in the app":"connected");return`<div class="vc-ag${l?" on":""}" style="--ag:var(--accent)">${Yt(r.actor,24,l?"live":"",r.id)}<div class="m"><b>${x(r.actor)}</b><small>${x(c)}</small></div><time>${l?"now":x($i(Math.floor(r.lastAt/1e3)))}</time></div>`}).join(""):'<div class="vc-empty">No agent activity yet. Agents show up here the moment they read or write your memory.</div>'}redrawMini(){if(!this.phone&&!this.prefs.minimap||this.phone&&this.open!=="sheet")return;const e=this.miniCanvas.getBoundingClientRect();if(!e.width||!e.height)return;const n=Math.min(2,window.devicePixelRatio||1),a=Math.round(e.width),i=Math.round(e.height);(this.miniCanvas.width!==a*n||this.miniCanvas.height!==i*n)&&(this.miniCanvas.width=a*n,this.miniCanvas.height=i*n),this.o.minimap(this.miniCanvas,a,i,n)}setOrientation(e,n){Math.abs(e-this.orient.yaw)<.004&&Math.abs(n-this.orient.pitch)<.004||(this.orient={yaw:e,pitch:n},this.drawGlobe())}drawGlobe(){const e=this.globe,n=Math.min(2,window.devicePixelRatio||1),a=64;e.width!==a*n&&(e.width=a*n,e.height=a*n);const i=e.getContext("2d");if(!i)return;const o=document.documentElement.dataset.theme==="light",s=o?"15,23,42":"230,233,239",r=o?"13,148,136":"94,234,212";i.setTransform(n,0,0,n,0,0),i.clearRect(0,0,a,a);const l=a/2-2,c=a/2,d=i.createRadialGradient(c-l*.35,c-l*.4,l*.1,c,c,l);d.addColorStop(0,`rgba(${r},.28)`),d.addColorStop(1,`rgba(${r},.04)`),i.fillStyle=d,i.beginPath(),i.arc(c,c,l,0,Math.PI*2),i.fill(),i.strokeStyle=`rgba(${r},.55)`,i.lineWidth=1.2,i.stroke();const{yaw:p,pitch:h}=this.orient,u=Math.cos(p),f=Math.sin(p),v=Math.cos(h),g=Math.sin(h),m=(k,y)=>{const w=Math.cos(k)*Math.sin(y),A=Math.sin(k),_=Math.cos(k)*Math.cos(y),S=w*u-_*f,T=w*f+_*u,E=A*v-T*g,P=A*g+T*v;return[c+S*l,c-E*l,P]},b=(k,y)=>{for(let w=1;w<k.length;w++){const A=k[w-1],_=k[w],S=(A[2]+_[2])/2>0;i.strokeStyle=`rgba(${y?r:s},${S?y?.85:.38:.09})`,i.lineWidth=y&&S?1.4:1,i.beginPath(),i.moveTo(A[0],A[1]),i.lineTo(_[0],_[1]),i.stroke()}};for(let k=0;k<6;k++){const y=k/6*Math.PI,w=[];for(let A=0;A<=36;A++)w.push(m(-Math.PI/2+A/36*Math.PI*2,y));b(w,!1)}for(const k of[-.9,-.45,0,.45,.9]){const y=[];for(let w=0;w<=48;w++)y.push(m(k,w/48*Math.PI*2));b(y,k===0)}}get clean(){return this.o.root.classList.contains("vc-clean")}setClean(e){e&&this.close(),this.o.root.classList.toggle("vc-clean",e);const n=this.q(".vc-unclean");e&&window.setTimeout(()=>this.clean&&n.focus({preventScroll:!0}),220)}toggleFullscreen(){const e=this.o.root;document.fullscreenElement?document.exitFullscreen().catch(()=>{}):e.requestFullscreen?.().catch(()=>{})}paintFs(){const e=this.q("[data-z=full]"),n=document.fullscreenElement===this.o.root;e.innerHTML=n?sn.exitFull:sn.full,e.title=n?"Exit full screen":"Full screen",e.setAttribute("aria-label",e.title),window.setTimeout(()=>window.dispatchEvent(new Event("resize")),60)}focusSearch(){qs()&&this.show("search"),this.input.focus(),this.input.select()}setQuery(e){qs()&&this.show("search"),this.input.value=e,this.q(".vc-x").hidden=!e,this.input.focus(),this.finder?.input()}destroy(){this.o.root.classList.remove("vc-clean"),clearTimeout(this.repeat),clearInterval(this.agentTimer),clearInterval(this.dirtyTimer),this.unsubAgents?.(),document.removeEventListener("pointerdown",this.onDocDown,!0),document.removeEventListener("fullscreenchange",this.onFs),window.removeEventListener("resize",this.onResize),this.themeObs.disconnect(),this.off.abort(),Ws(),this.finder?.destroy(),this.el.remove()}}function cw(t){return t?`<b class="vc-q" tabindex="0" role="img" aria-label="${C(t)}" data-help="${C(t)}">?</b>`:""}function po(t,e,n,a=""){return`<button type="button" class="vc-tg${n?" on":""}" data-t="${C(t)}" role="switch" aria-checked="${n}"><span>${cw(a)}${x(e)}</span><i></i></button>`}function gB(t,e,n,a,i,o,s=""){return`<label class="vc-sl"><span>${cw(s)}${x(e)}</span><input type="range" min="${n}" max="${a}" step="${i}" value="${o}" data-s="${C(t)}"></label>`}let Eh=null;const t5=new WeakSet;function Ws(){Eh?.remove(),Eh=null}function n5(t){Ws();const e=n=>{Ws();const a=document.createElement("div");Eh=a,a.className="vc-tip",a.textContent=n.dataset.help||"",document.body.appendChild(a);const i=n.getBoundingClientRect(),o=a.offsetWidth,s=i.left-o-10>=8?i.left-o-10:Math.min(innerWidth-o-8,i.right+10);a.style.left=Math.max(8,s)+"px",a.style.top=Math.max(8,Math.min(innerHeight-a.offsetHeight-8,i.top-4))+"px"};t.querySelectorAll(".vc-q").forEach(n=>{n.onmouseenter=()=>e(n),n.onfocus=()=>e(n),n.onmouseleave=Ws,n.onblur=Ws,n.onclick=a=>{a.stopPropagation(),a.preventDefault(),e(n);const i=Eh;window.setTimeout(()=>i===Eh&&Ws(),3500)}}),t5.has(t)||(t5.add(t),t.addEventListener("scroll",Ws,{passive:!0}))}const Fa={close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18"/></svg>',more:'<svg viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>',open:'<svg viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-8 8"/><path d="M19 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h4"/></svg>',target:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2.5"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>',folder:'<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></svg>',only:'<svg viewBox="0 0 24 24"><path d="M4 5h16l-6 7.5V19l-4 1.5v-8z"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',up:'<svg viewBox="0 0 24 24"><path d="m6 15 6-6 6 6"/></svg>'},vB=`
|
|
7057
|
+
<div class="vc-ec-acts"><button type="button" class="btn primary" data-ec="setup">Open the guide</button><button type="button" class="btn" data-ec="new">${rn.plus}New note</button></div></div>`,n.querySelector("[data-ec=setup]").onclick=()=>te.go("home"),n.querySelector("[data-ec=new]").onclick=()=>te.openNewNote()}shown(){this.markActive()}markActive(){const e=this.o.page;this.el.querySelectorAll(".vc-modes button").forEach(n=>{n.classList.toggle("on",n.dataset.page===e),n.setAttribute("aria-pressed",String(n.dataset.page===e))})}show(e){if(this.open!==e)if(this.close(),this.open=e,this.el.dataset.open=e,this.o.root.dataset.vcOpen=e,this.o.onOverlay?.(),e==="filter")this.panel.hidden=!1,this.q("[data-vc=filter]").classList.add("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","true"),this.renderPanel();else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.add("open");const n=this.q(`[data-open=${e}]`);n.classList.add("on"),n.setAttribute("aria-expanded","true"),e==="activity"&&this.paintAgents()}else e==="sheet"?(this.q(".vc-sheet").classList.add("open"),this.q(".vc-scrim").classList.add("on"),this.o.root.classList.add("vc-sheet-open"),this.renderSheetLabels(),requestAnimationFrame(()=>this.redrawMini())):e==="search"&&(this.q(".vc-search").classList.add("open"),this.sizeSearch(),this.input.focus())}close(){const e=this.open;if(e){if(Ws(),this.open=null,delete this.el.dataset.open,delete this.o.root.dataset.vcOpen,e==="filter")this.panel.hidden=!0,this.q("[data-vc=filter]").classList.remove("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","false");else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.remove("open");const n=this.q(`[data-open=${e}]`);n.classList.remove("on"),n.setAttribute("aria-expanded","false")}else if(e==="sheet")this.q(".vc-sheet").classList.remove("open"),this.q(".vc-scrim").classList.remove("on"),this.o.root.classList.remove("vc-sheet-open");else if(e==="search"){const n=this.q(".vc-search");n.classList.remove("open"),n.style.width=""}}}sizeSearch(){this.q(".vc-search").style.width=""}openPanel(){this.show("filter")}closePanel(){this.open==="filter"&&this.close()}wire(){const e=this.o;this.el.querySelectorAll(".vc-modes button").forEach(c=>{c.onclick=()=>{const d=c.dataset.page;if(d===e.page)return;this.el.querySelectorAll(".vc-modes button").forEach(h=>h.classList.toggle("on",h===c));const p=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;clearTimeout(e5),e5=window.setTimeout(()=>{te.go(d),this.markActive()},p?0:140)}}),this.q(".vc-search").addEventListener("click",()=>{qs()&&this.open!=="search"&&this.show("search")});const a=this.input,i=e.search.find?new hB({input:a,root:e.root,setCount:c=>this.setCount(c),anchor:()=>this.q(".vc-search"),compact:qs},e.search.find):null;this.finder=i,a.oninput=()=>{i?.input(),e.search.onInput?.(a.value.trim())},a.onfocus=()=>{qs()&&this.open!=="search"?this.show("search"):!qs()&&this.open&&this.open!=="search"&&this.close(),i&&requestAnimationFrame(()=>i.show()),e.search.onFocus?.()},a.addEventListener("blur",()=>{window.setTimeout(()=>{document.activeElement!==a&&i?.hide()},120),qs()&&!a.value&&window.setTimeout(()=>this.open==="search"&&this.close(),150)}),a.onkeydown=c=>{if(i){if(c.key==="Escape"&&!a.value){i.hide(),a.blur(),this.open==="search"&&this.close(),c.preventDefault();return}i.key(c)&&c.preventDefault();return}if(e.search.onKey?.(c,a.value.trim())){c.preventDefault();return}c.key==="Escape"&&(a.value="",e.search.onInput?.(""),a.blur(),this.open==="search"&&this.close())},this.q("[data-vc=filter]").onclick=()=>this.open==="filter"?this.close():this.show("filter"),document.addEventListener("pointerdown",this.onDocDown,!0);const o=this.q("[data-reset]"),s=()=>{const c=JSON.stringify(this.prefs)!==JSON.stringify(sw())||!!e.changed?.();if(o.classList.contains("dirty")===c)return;o.classList.toggle("dirty",c);const d=c?"Reset: this view differs from its defaults":"Reset this view to its defaults";o.title=d,o.setAttribute("aria-label",d)};this.dirtyTimer=window.setInterval(()=>{!document.hidden&&this.el.isConnected&&s()},400),o.onclick=()=>{o.classList.remove("spin"),o.offsetWidth,o.classList.add("spin"),this.close();try{localStorage.removeItem(ow())}catch{}this.prefs=sw(),e.reset(),this.applyPrefs(),this.refreshRegions()},this.el.querySelectorAll("[data-open]").forEach(c=>{c.onclick=()=>{const d=c.dataset.open;this.open===d?this.close():this.show(d)}}),this.el.querySelectorAll("[data-close]").forEach(c=>c.onclick=()=>this.close()),this.q(".vc-scrim").onclick=()=>this.close(),this.el.querySelectorAll("[data-all]").forEach(c=>{c.onclick=()=>{e.regions.setAll(c.dataset.all==="hide"),this.refreshRegions()}}),e.root.addEventListener("keydown",c=>{c.key==="Escape"&&this.open&&this.open!=="search"?this.close():c.key==="Escape"&&this.clean&&this.setClean(!1)},{signal:this.off.signal}),document.addEventListener("keydown",c=>{if(c.key.toLowerCase()!=="c"||c.ctrlKey||c.metaKey||c.altKey||!this.el.isConnected)return;const d=c.target;d&&(d.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(d.tagName))||document.querySelector("[aria-modal=true], dialog[open]")||(c.preventDefault(),this.setClean(!this.clean))},{signal:this.off.signal}),this.q(".vc-unclean").onclick=()=>this.setClean(!1),this.el.querySelectorAll("[data-z]").forEach(c=>{c.onclick=()=>{const d=c.dataset.z;d==="in"?e.nav.zoom(1.4):d==="out"?e.nav.zoom(1/1.4):d==="fit"?e.nav.fit():d==="clean"?this.setClean(!0):this.toggleFullscreen()}}),document.addEventListener("fullscreenchange",this.onFs);const r={u:[0,-1],d:[0,1],l:[-1,0],r:[1,0]};this.el.querySelectorAll(".vc-globe [data-g]").forEach(c=>{const d=c.dataset.g||"";if(d==="h"){c.onclick=()=>e.nav.home();return}const p=()=>e.nav.nudge(r[d][0],r[d][1]);c.onpointerdown=u=>{u.preventDefault(),p(),clearTimeout(this.repeat);const f=()=>{p(),this.repeat=window.setTimeout(f,110)};this.repeat=window.setTimeout(f,380)};const h=()=>clearTimeout(this.repeat);c.onpointerup=h,c.onpointerleave=h,c.onpointercancel=h,c.onkeydown=u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),p())}});const l=this.q(".vc-mini");if(e.minimapNav){const c=p=>{const h=l.getBoundingClientRect();e.minimapNav(Math.max(0,Math.min(1,(p.clientX-h.left)/h.width)),Math.max(0,Math.min(1,(p.clientY-h.top)/h.height)))};let d=!1;l.onpointerdown=p=>{p.stopPropagation(),d=!0,l.setPointerCapture(p.pointerId),c(p)},l.onpointermove=p=>d&&c(p),l.onpointerup=()=>d=!1}for(const c of this.el.querySelectorAll(".vc-p,.vc-tab,.vc-drawer,.vc-sheet,.vc-scrim"))c.addEventListener("pointerdown",d=>d.stopPropagation()),c.addEventListener("wheel",d=>d.stopPropagation(),{passive:!0}),c.addEventListener("dblclick",d=>d.stopPropagation())}renderPanel(){if(this.open!=="filter")return;const e=this.q(".vc-pb"),n=e.scrollTop,a=this.o.page==="brain"?"turn the brain":"move the map";e.innerHTML=(this.phone?"":"<h4>View</h4>"+po("vc-minimap","Minimap",this.prefs.minimap,"The small overview at the bottom left. Click or drag it to move the view.")+po("vc-controls","Orbit globe",this.prefs.controls,`The globe at the bottom right: its arrows ${a}, the middle button goes back to the default view.`))+"<h4>Labels</h4>"+this.labelsHTML()+"<h4>Background</h4>"+this.dotsHTML()+"<div data-own></div>",e.querySelectorAll("[data-t^=vc-]").forEach(i=>i.onclick=()=>this.toggleShared(i.dataset.t||"")),this.o.filter(e.querySelector("[data-own]")),n5(e),e.scrollTop=n}dotsHTML(){return po("vc-dots","Dot grid",rw(),"The dots behind 3D, Graph and Canvas. Turn them off for a clean, plain background.")}labelsHTML(){const e=this.o.labels.get();return po("vc-lab-nodes","Note labels",e.nodes,this.o.labels.help.nodes)+po("vc-lab-folders","Folder labels",e.folders,this.o.labels.help.folders)}toggleShared(e){if(e==="vc-dots")uB(!rw());else if(e==="vc-lab-nodes"||e==="vc-lab-folders"){const n=e==="vc-lab-nodes"?"nodes":"folders";this.o.labels.set(n,!this.o.labels.get()[n])}else e==="vc-minimap"?this.prefs.minimap=!this.prefs.minimap:this.prefs.controls=!this.prefs.controls,J4(this.prefs),this.applyPrefs();this.renderPanel(),this.renderSheetLabels()}renderSheetLabels(){if(this.open!=="sheet")return;const e=this.q("[data-slot=labels]");e.innerHTML="<h4>Labels</h4>"+this.labelsHTML()+"<h4>Background</h4>"+this.dotsHTML(),e.querySelectorAll("[data-t]").forEach(n=>n.onclick=()=>this.toggleShared(n.dataset.t||"")),n5(e)}toggleMinimap(){if(this.phone){this.open==="sheet"?this.close():this.show("sheet");return}this.prefs.minimap=!this.prefs.minimap,J4(this.prefs),this.applyPrefs(),this.renderPanel()}setBadge(e){this.q(".vc-badge").textContent=e?String(e):""}setCount(e){this.q(".vc-search em").textContent=e}applyPrefs(){this.q(".vc-mini").classList.toggle("vc-hide",!this.phone&&!this.prefs.minimap),this.q(".vc-globe").classList.toggle("vc-hide",!this.phone&&!this.prefs.controls),this.o.onPrefs?.(this.prefs),this.redrawMini()}refreshRegions(){const e=this.o.regions.list(),n=this.q(".vc-rl"),a=e.filter(o=>!o.hidden).length;this.el.querySelectorAll("[data-rn]").forEach(o=>o.textContent=a===e.length?String(e.length):`${a}/${e.length}`),this.q(".vc-bulk").classList.toggle("vc-hide",e.length<2);const i=!!this.o.regions.focus;n.innerHTML=e.length?e.map(o=>`<div class="vc-rr${o.hidden?" off":""}" style="--c:${C(o.color)}"><button type="button" class="tg" data-r="${C(o.name)}" aria-pressed="${!o.hidden}" title="${o.hidden?"Show":"Hide"} ${C(o.name)}" aria-label="${o.hidden?"Show":"Hide"} ${C(o.name)}"><i></i></button><button type="button" class="t" data-f="${C(o.name)}" title="${i?"Go to":o.hidden?"Show":"Hide"} ${C(o.name)}"><span>${x(o.name)}</span><em>${o.count}</em>${i?rn.target:""}</button></div>`).join(""):'<div class="vc-empty">No folders yet.</div>',n.querySelectorAll("[data-r]").forEach(o=>{o.onclick=()=>{this.o.regions.toggle(o.dataset.r||""),this.refreshRegions()}}),n.querySelectorAll("[data-f]").forEach(o=>{o.onclick=()=>{const s=o.dataset.f||"";if(!this.o.regions.focus){this.o.regions.toggle(s),this.refreshRegions();return}e.find(r=>r.name===s)?.hidden&&(this.o.regions.toggle(s),this.refreshRegions()),this.close(),this.o.regions.focus(s)}})}paintAgents(){const e=Date.now(),n=r=>r.open>0&&e-r.lastAt<12e4||e-r.lastAt<5e3,a=Pl(),i=zd(),o=this.q(".vc-tab-r");if(o.classList.toggle("live",i.length>0),this.el.querySelectorAll("[data-an]").forEach(r=>r.textContent=String(i.length)),o.title=i.length?`${i.length} agent${i.length===1?"":"s"} working now`:"Agent activity",this.open!=="activity")return;const s=this.q(".vc-al");s.innerHTML=a.length?a.slice(0,30).map(r=>{const l=n(r),c=r.lastLabel||r.lastAction||(r.kind==="user"?"in the app":"connected");return`<div class="vc-ag${l?" on":""}" style="--ag:var(--accent)">${Yt(r.actor,24,l?"live":"",r.id)}<div class="m"><b>${x(r.actor)}</b><small>${x(c)}</small></div><time>${l?"now":x($i(Math.floor(r.lastAt/1e3)))}</time></div>`}).join(""):'<div class="vc-empty">No agent activity yet. Agents show up here the moment they read or write your memory.</div>'}redrawMini(){if(!this.phone&&!this.prefs.minimap||this.phone&&this.open!=="sheet")return;const e=this.miniCanvas.getBoundingClientRect();if(!e.width||!e.height)return;const n=Math.min(2,window.devicePixelRatio||1),a=Math.round(e.width),i=Math.round(e.height);(this.miniCanvas.width!==a*n||this.miniCanvas.height!==i*n)&&(this.miniCanvas.width=a*n,this.miniCanvas.height=i*n),this.o.minimap(this.miniCanvas,a,i,n)}setOrientation(e,n){Math.abs(e-this.orient.yaw)<.004&&Math.abs(n-this.orient.pitch)<.004||(this.orient={yaw:e,pitch:n},this.drawGlobe())}drawGlobe(){const e=this.globe,n=Math.min(2,window.devicePixelRatio||1),a=64;e.width!==a*n&&(e.width=a*n,e.height=a*n);const i=e.getContext("2d");if(!i)return;const o=document.documentElement.dataset.theme==="light",s=o?"15,23,42":"230,233,239",r=o?"13,148,136":"94,234,212";i.setTransform(n,0,0,n,0,0),i.clearRect(0,0,a,a);const l=a/2-2,c=a/2,d=i.createRadialGradient(c-l*.35,c-l*.4,l*.1,c,c,l);d.addColorStop(0,`rgba(${r},.28)`),d.addColorStop(1,`rgba(${r},.04)`),i.fillStyle=d,i.beginPath(),i.arc(c,c,l,0,Math.PI*2),i.fill(),i.strokeStyle=`rgba(${r},.55)`,i.lineWidth=1.2,i.stroke();const{yaw:p,pitch:h}=this.orient,u=Math.cos(p),f=Math.sin(p),v=Math.cos(h),g=Math.sin(h),m=(k,y)=>{const w=Math.cos(k)*Math.sin(y),A=Math.sin(k),_=Math.cos(k)*Math.cos(y),S=w*u-_*f,T=w*f+_*u,E=A*v-T*g,P=A*g+T*v;return[c+S*l,c-E*l,P]},b=(k,y)=>{for(let w=1;w<k.length;w++){const A=k[w-1],_=k[w],S=(A[2]+_[2])/2>0;i.strokeStyle=`rgba(${y?r:s},${S?y?.85:.38:.09})`,i.lineWidth=y&&S?1.4:1,i.beginPath(),i.moveTo(A[0],A[1]),i.lineTo(_[0],_[1]),i.stroke()}};for(let k=0;k<6;k++){const y=k/6*Math.PI,w=[];for(let A=0;A<=36;A++)w.push(m(-Math.PI/2+A/36*Math.PI*2,y));b(w,!1)}for(const k of[-.9,-.45,0,.45,.9]){const y=[];for(let w=0;w<=48;w++)y.push(m(k,w/48*Math.PI*2));b(y,k===0)}}get clean(){return this.o.root.classList.contains("vc-clean")}setClean(e){e&&this.close(),this.o.root.classList.toggle("vc-clean",e);const n=this.q(".vc-unclean");e&&window.setTimeout(()=>this.clean&&n.focus({preventScroll:!0}),220)}toggleFullscreen(){const e=this.o.root;document.fullscreenElement?document.exitFullscreen().catch(()=>{}):e.requestFullscreen?.().catch(()=>{})}paintFs(){const e=this.q("[data-z=full]"),n=document.fullscreenElement===this.o.root;e.innerHTML=n?rn.exitFull:rn.full,e.title=n?"Exit full screen":"Full screen",e.setAttribute("aria-label",e.title),window.setTimeout(()=>window.dispatchEvent(new Event("resize")),60)}focusSearch(){qs()&&this.show("search"),this.input.focus(),this.input.select()}setQuery(e){qs()&&this.show("search"),this.input.value=e,this.q(".vc-x").hidden=!e,this.input.focus(),this.finder?.input()}destroy(){this.o.root.classList.remove("vc-clean"),clearTimeout(this.repeat),clearInterval(this.agentTimer),clearInterval(this.dirtyTimer),this.unsubAgents?.(),document.removeEventListener("pointerdown",this.onDocDown,!0),document.removeEventListener("fullscreenchange",this.onFs),window.removeEventListener("resize",this.onResize),this.themeObs.disconnect(),this.off.abort(),Ws(),this.finder?.destroy(),this.el.remove()}}function cw(t){return t?`<b class="vc-q" tabindex="0" role="img" aria-label="${C(t)}" data-help="${C(t)}">?</b>`:""}function po(t,e,n,a=""){return`<button type="button" class="vc-tg${n?" on":""}" data-t="${C(t)}" role="switch" aria-checked="${n}"><span>${cw(a)}${x(e)}</span><i></i></button>`}function gB(t,e,n,a,i,o,s=""){return`<label class="vc-sl"><span>${cw(s)}${x(e)}</span><input type="range" min="${n}" max="${a}" step="${i}" value="${o}" data-s="${C(t)}"></label>`}let Eh=null;const t5=new WeakSet;function Ws(){Eh?.remove(),Eh=null}function n5(t){Ws();const e=n=>{Ws();const a=document.createElement("div");Eh=a,a.className="vc-tip",a.textContent=n.dataset.help||"",document.body.appendChild(a);const i=n.getBoundingClientRect(),o=a.offsetWidth,s=i.left-o-10>=8?i.left-o-10:Math.min(innerWidth-o-8,i.right+10);a.style.left=Math.max(8,s)+"px",a.style.top=Math.max(8,Math.min(innerHeight-a.offsetHeight-8,i.top-4))+"px"};t.querySelectorAll(".vc-q").forEach(n=>{n.onmouseenter=()=>e(n),n.onfocus=()=>e(n),n.onmouseleave=Ws,n.onblur=Ws,n.onclick=a=>{a.stopPropagation(),a.preventDefault(),e(n);const i=Eh;window.setTimeout(()=>i===Eh&&Ws(),3500)}}),t5.has(t)||(t5.add(t),t.addEventListener("scroll",Ws,{passive:!0}))}const Fa={close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18"/></svg>',more:'<svg viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>',open:'<svg viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-8 8"/><path d="M19 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h4"/></svg>',target:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2.5"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>',folder:'<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></svg>',only:'<svg viewBox="0 0 24 24"><path d="M4 5h16l-6 7.5V19l-4 1.5v-8z"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',up:'<svg viewBox="0 0 24 24"><path d="m6 15 6-6 6 6"/></svg>'},vB=`
|
|
7038
7058
|
/* Brings the map chrome tokens itself, for pages without a map. */
|
|
7039
7059
|
.nc{--vc-ctl-line:var(--line-strong);--vc-tint:var(--hover);--vc-track:var(--seg-track);--vc-thumb:var(--seg-thumb);--vc-line:var(--line)}
|
|
7040
7060
|
.nc{position:absolute;z-index:35;right:12px;top:12px;bottom:12px;width:min(380px,calc(100% - 24px));display:flex;flex-direction:column;
|
|
@@ -11641,7 +11661,7 @@ Material Type: `+P.type+`
|
|
|
11641
11661
|
|
|
11642
11662
|
Program Info Log: `+$+`
|
|
11643
11663
|
`+ae+`
|
|
11644
|
-
`+q)}else $!==""?it("WebGLProgram: Program Info Log:",$):(G===""||O==="")&&(ne=!1);ne&&(P.diagnostics={runnable:J,programLog:$,vertexShader:{log:G,prefix:g},fragmentShader:{log:O,prefix:m}})}i.deleteShader(w),i.deleteShader(A),S=new tv(i,v),T=jW(i,v)}let S;this.getUniforms=function(){return S===void 0&&_(this),S};let T;this.getAttributes=function(){return T===void 0&&_(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(v,OW)),E},this.destroy=function(){a.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=$W++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=w,this.fragmentShader=A,this}let cG=0;class dG{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,n,a){const i=this._getShaderCacheForMaterial(e);return i.has(n)===!1&&(i.add(n),n.usedTimes++),i.has(a)===!1&&(i.add(a),a.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const a of n)a.usedTimes--,a.usedTimes===0&&this.shaderCache.delete(a.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let a=n.get(e);return a===void 0&&(a=new Set,n.set(e,a)),a}_getShaderStage(e){const n=this.shaderCache;let a=n.get(e);return a===void 0&&(a=new pG(e),n.set(e,a)),a}}class pG{constructor(e){this.id=cG++,this.code=e,this.usedTimes=0}}function hG(t){return t===sl||t===vg||t===xg}function uG(t,e,n,a,i,o){const s=new Q5,r=new dG,l=new Set,c=[],d=new Map,p=a.logarithmicDepthBuffer;let h=a.precision;const u={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function f(S){return l.add(S),S===0?"uv":`uv${S}`}function v(S,T,E,P,R,B){const D=P.fog,$=R.geometry,G=S.isMeshStandardMaterial||S.isMeshLambertMaterial||S.isMeshPhongMaterial?P.environment:null,O=S.isMeshStandardMaterial||S.isMeshLambertMaterial&&!S.envMap||S.isMeshPhongMaterial&&!S.envMap,J=e.get(S.envMap||G,O),ne=J&&J.mapping===pg?J.image.height:null,ae=u[S.type];S.precision!==null&&(h=a.getMaxPrecision(S.precision),h!==S.precision&&it("WebGLProgram.getParameters:",S.precision,"not supported, using",h,"instead."));const q=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,we=q!==void 0?q.length:0;let Re=0;$.morphAttributes.position!==void 0&&(Re=1),$.morphAttributes.normal!==void 0&&(Re=2),$.morphAttributes.color!==void 0&&(Re=3);let ot,Qe,st,de;if(ae){const at=yo[ae];ot=at.vertexShader,Qe=at.fragmentShader}else{ot=S.vertexShader,Qe=S.fragmentShader;const at=r.getVertexShaderStage(S),dt=r.getFragmentShaderStage(S);r.update(S,at,dt),st=at.id,de=dt.id}const Z=t.getRenderTarget(),Ne=t.state.buffers.depth.getReversed(),Xe=R.isInstancedMesh===!0,De=R.isBatchedMesh===!0,be=!!S.map,ft=!!S.matcap,rt=!!J,vt=!!S.aoMap,Rt=!!S.lightMap,mt=!!S.bumpMap&&S.wireframe===!1,Gt=!!S.normalMap,rn=!!S.displacementMap,ln=!!S.emissiveMap,Ut=!!S.metalnessMap,Jt=!!S.roughnessMap,K=S.anisotropy>0,cn=S.clearcoat>0,zt=S.dispersion>0,F=S.retroreflectivity>0,M=S.iridescence>0,ee=S.sheen>0,se=S.transmission>0,he=K&&!!S.anisotropyMap,Le=cn&&!!S.clearcoatMap,ze=cn&&!!S.clearcoatNormalMap,ge=cn&&!!S.clearcoatRoughnessMap,z=M&&!!S.iridescenceMap,j=M&&!!S.iridescenceThicknessMap,ce=ee&&!!S.sheenColorMap,I=ee&&!!S.sheenRoughnessMap,U=!!S.specularMap,Y=!!S.specularColorMap,pe=!!S.specularIntensityMap,Ie=se&&!!S.transmissionMap,W=se&&!!S.thicknessMap,_e=!!S.gradientMap,fe=!!S.alphaMap,Me=S.alphaTest>0,Pe=!!S.alphaHash,ke=!!S.extensions;let Ce=uo;S.toneMapped&&(Z===null||Z.isXRRenderTarget===!0)&&(Ce=t.toneMapping);const Ee={shaderID:ae,shaderType:S.type,shaderName:S.name,vertexShader:ot,fragmentShader:Qe,defines:S.defines,customVertexShaderID:st,customFragmentShaderID:de,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:h,batching:De,batchingColor:De&&R._colorsTexture!==null,instancing:Xe,instancingColor:Xe&&R.instanceColor!==null,instancingMorph:Xe&&R.morphTexture!==null,outputColorSpace:Z===null?t.outputColorSpace:Z.isXRRenderTarget===!0?Z.texture.colorSpace:Ct.workingColorSpace,alphaToCoverage:!!S.alphaToCoverage,map:be,matcap:ft,envMap:rt,envMapMode:rt&&J.mapping,envMapCubeUVHeight:ne,aoMap:vt,lightMap:Rt,bumpMap:mt,normalMap:Gt,displacementMap:rn,emissiveMap:ln,normalMapObjectSpace:Gt&&S.normalMapType===MH,normalMapTangentSpace:Gt&&S.normalMapType===H5,packedNormalMap:Gt&&S.normalMapType===H5&&hG(S.normalMap.format),metalnessMap:Ut,roughnessMap:Jt,anisotropy:K,anisotropyMap:he,clearcoat:cn,clearcoatMap:Le,clearcoatNormalMap:ze,clearcoatRoughnessMap:ge,dispersion:zt,retroreflection:F,iridescence:M,iridescenceMap:z,iridescenceThicknessMap:j,sheen:ee,sheenColorMap:ce,sheenRoughnessMap:I,specularMap:U,specularColorMap:Y,specularIntensityMap:pe,transmission:se,transmissionMap:Ie,thicknessMap:W,gradientMap:_e,opaque:S.transparent===!1&&S.blending===zc&&S.alphaToCoverage===!1,alphaMap:fe,alphaTest:Me,alphaHash:Pe,combine:S.combine,mapUv:be&&f(S.map.channel),aoMapUv:vt&&f(S.aoMap.channel),lightMapUv:Rt&&f(S.lightMap.channel),bumpMapUv:mt&&f(S.bumpMap.channel),normalMapUv:Gt&&f(S.normalMap.channel),displacementMapUv:rn&&f(S.displacementMap.channel),emissiveMapUv:ln&&f(S.emissiveMap.channel),metalnessMapUv:Ut&&f(S.metalnessMap.channel),roughnessMapUv:Jt&&f(S.roughnessMap.channel),anisotropyMapUv:he&&f(S.anisotropyMap.channel),clearcoatMapUv:Le&&f(S.clearcoatMap.channel),clearcoatNormalMapUv:ze&&f(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ge&&f(S.clearcoatRoughnessMap.channel),iridescenceMapUv:z&&f(S.iridescenceMap.channel),iridescenceThicknessMapUv:j&&f(S.iridescenceThicknessMap.channel),sheenColorMapUv:ce&&f(S.sheenColorMap.channel),sheenRoughnessMapUv:I&&f(S.sheenRoughnessMap.channel),specularMapUv:U&&f(S.specularMap.channel),specularColorMapUv:Y&&f(S.specularColorMap.channel),specularIntensityMapUv:pe&&f(S.specularIntensityMap.channel),transmissionMapUv:Ie&&f(S.transmissionMap.channel),thicknessMapUv:W&&f(S.thicknessMap.channel),alphaMapUv:fe&&f(S.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(Gt||K),vertexNormals:!!$.attributes.normal,vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,pointsUvs:R.isPoints===!0&&!!$.attributes.uv&&(be||fe),fog:!!D,useFog:S.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:S.wireframe===!1&&(S.flatShading===!0||$.attributes.normal===void 0&&Gt===!1&&(S.isMeshLambertMaterial||S.isMeshPhongMaterial||S.isMeshStandardMaterial||S.isMeshPhysicalMaterial)),sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:p,reversedDepthBuffer:Ne,skinning:R.isSkinnedMesh===!0,hasPositionAttribute:$.attributes.position!==void 0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:we,morphTextureStride:Re,numSunLights:T.sun.length,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numSunLightShadows:T.sunShadowMap.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numLightProbes:T.numLightProbes,numLightProbeGrids:B.length,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:S.dithering,shadowMapEnabled:t.shadowMap.enabled&&E.length>0,shadowMapType:t.shadowMap.type,toneMapping:Ce,decodeVideoTexture:be&&S.map.isVideoTexture===!0&&Ct.getTransfer(S.map.colorSpace)===Ht,decodeVideoTextureEmissive:ln&&S.emissiveMap.isVideoTexture===!0&&Ct.getTransfer(S.emissiveMap.colorSpace)===Ht,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===es,flipSided:S.side===Ea,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionClipCullDistance:ke&&S.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ke&&S.extensions.multiDraw===!0||De)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()};return Ee.vertexUv1s=l.has(1),Ee.vertexUv2s=l.has(2),Ee.vertexUv3s=l.has(3),l.clear(),Ee}function g(S){const T=[];if(S.shaderID?T.push(S.shaderID):(T.push(S.customVertexShaderID),T.push(S.customFragmentShaderID)),S.defines!==void 0)for(const E in S.defines)T.push(E),T.push(S.defines[E]);return S.isRawShaderMaterial===!1&&(m(T,S),b(T,S),T.push(t.outputColorSpace)),T.push(S.customProgramCacheKey),T.join()}function m(S,T){S.push(T.precision),S.push(T.outputColorSpace),S.push(T.envMapMode),S.push(T.envMapCubeUVHeight),S.push(T.mapUv),S.push(T.alphaMapUv),S.push(T.lightMapUv),S.push(T.aoMapUv),S.push(T.bumpMapUv),S.push(T.normalMapUv),S.push(T.displacementMapUv),S.push(T.emissiveMapUv),S.push(T.metalnessMapUv),S.push(T.roughnessMapUv),S.push(T.anisotropyMapUv),S.push(T.clearcoatMapUv),S.push(T.clearcoatNormalMapUv),S.push(T.clearcoatRoughnessMapUv),S.push(T.iridescenceMapUv),S.push(T.iridescenceThicknessMapUv),S.push(T.sheenColorMapUv),S.push(T.sheenRoughnessMapUv),S.push(T.specularMapUv),S.push(T.specularColorMapUv),S.push(T.specularIntensityMapUv),S.push(T.transmissionMapUv),S.push(T.thicknessMapUv),S.push(T.combine),S.push(T.fogExp2),S.push(T.sizeAttenuation),S.push(T.morphTargetsCount),S.push(T.morphAttributeCount),S.push(T.numSunLights),S.push(T.numDirLights),S.push(T.numPointLights),S.push(T.numSpotLights),S.push(T.numSpotLightMaps),S.push(T.numHemiLights),S.push(T.numRectAreaLights),S.push(T.numSunLightShadows),S.push(T.numDirLightShadows),S.push(T.numPointLightShadows),S.push(T.numSpotLightShadows),S.push(T.numSpotLightShadowsWithMaps),S.push(T.numLightProbes),S.push(T.shadowMapType),S.push(T.toneMapping),S.push(T.numClippingPlanes),S.push(T.numClipIntersection),S.push(T.depthPacking)}function b(S,T){s.disableAll(),T.instancing&&s.enable(0),T.instancingColor&&s.enable(1),T.instancingMorph&&s.enable(2),T.matcap&&s.enable(3),T.envMap&&s.enable(4),T.normalMapObjectSpace&&s.enable(5),T.normalMapTangentSpace&&s.enable(6),T.clearcoat&&s.enable(7),T.iridescence&&s.enable(8),T.alphaTest&&s.enable(9),T.vertexColors&&s.enable(10),T.vertexAlphas&&s.enable(11),T.vertexUv1s&&s.enable(12),T.vertexUv2s&&s.enable(13),T.vertexUv3s&&s.enable(14),T.vertexTangents&&s.enable(15),T.anisotropy&&s.enable(16),T.alphaHash&&s.enable(17),T.batching&&s.enable(18),T.dispersion&&s.enable(19),T.retroreflection&&s.enable(24),T.batchingColor&&s.enable(20),T.gradientMap&&s.enable(21),T.packedNormalMap&&s.enable(22),T.vertexNormals&&s.enable(23),S.push(s.mask),s.disableAll(),T.fog&&s.enable(0),T.useFog&&s.enable(1),T.flatShading&&s.enable(2),T.logarithmicDepthBuffer&&s.enable(3),T.reversedDepthBuffer&&s.enable(4),T.skinning&&s.enable(5),T.morphTargets&&s.enable(6),T.morphNormals&&s.enable(7),T.morphColors&&s.enable(8),T.premultipliedAlpha&&s.enable(9),T.shadowMapEnabled&&s.enable(10),T.doubleSided&&s.enable(11),T.flipSided&&s.enable(12),T.useDepthPacking&&s.enable(13),T.dithering&&s.enable(14),T.transmission&&s.enable(15),T.sheen&&s.enable(16),T.opaque&&s.enable(17),T.pointsUvs&&s.enable(18),T.decodeVideoTexture&&s.enable(19),T.decodeVideoTextureEmissive&&s.enable(20),T.alphaToCoverage&&s.enable(21),T.numLightProbeGrids>0&&s.enable(22),T.hasPositionAttribute&&s.enable(23),S.push(s.mask)}function k(S){const T=u[S.type];let E;if(T){const P=yo[T];E=fq.clone(P.uniforms)}else E=S.uniforms;return E}function y(S,T){let E=d.get(T);return E!==void 0?++E.usedTimes:(E=new lG(t,T,S,i),c.push(E),d.set(T,E)),E}function w(S){if(--S.usedTimes===0){const T=c.indexOf(S);c[T]=c[c.length-1],c.pop(),d.delete(S.cacheKey),S.destroy()}}function A(S){r.remove(S)}function _(){r.dispose()}return{getParameters:v,getProgramCacheKey:g,getUniforms:k,acquireProgram:y,releaseProgram:w,releaseShaderCache:A,programs:c,dispose:_}}function fG(){let t=new WeakMap;function e(s){return t.has(s)}function n(s){let r=t.get(s);return r===void 0&&(r={},t.set(s,r)),r}function a(s){t.delete(s)}function i(s,r,l){t.get(s)[r]=l}function o(){t=new WeakMap}return{has:e,get:n,remove:a,update:i,dispose:o}}function mG(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.materialVariant!==e.materialVariant?t.materialVariant-e.materialVariant:t.z!==e.z?t.z-e.z:t.id-e.id}function nC(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function aC(){const t=[];let e=0;const n=[],a=[],i=[];function o(){e=0,n.length=0,a.length=0,i.length=0}function s(h){let u=0;return h.isInstancedMesh&&(u+=2),h.isSkinnedMesh&&(u+=1),u}function r(h,u,f,v,g,m){let b=t[e];return b===void 0?(b={id:h.id,object:h,geometry:u,material:f,materialVariant:s(h),groupOrder:v,renderOrder:h.renderOrder,z:g,group:m},t[e]=b):(b.id=h.id,b.object=h,b.geometry=u,b.material=f,b.materialVariant=s(h),b.groupOrder=v,b.renderOrder=h.renderOrder,b.z=g,b.group=m),e++,b}function l(h,u,f,v,g,m,b){b.reversedDepth===!0&&(g=-g);const k=r(h,u,f,v,g,m);f.transmission>0?a.push(k):f.transparent===!0?i.push(k):n.push(k)}function c(h,u,f,v,g,m){const b=r(h,u,f,v,g,m);f.transmission>0?a.unshift(b):f.transparent===!0?i.unshift(b):n.unshift(b)}function d(h,u){n.length>1&&n.sort(h||mG),a.length>1&&a.sort(u||nC),i.length>1&&i.sort(u||nC)}function p(){for(let h=e,u=t.length;h<u;h++){const f=t[h];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:n,transmissive:a,transparent:i,init:o,push:l,unshift:c,finish:p,sort:d}}function gG(){let t=new WeakMap;function e(a,i){const o=t.get(a);let s;return o===void 0?(s=new aC,t.set(a,[s])):i>=o.length?(s=new aC,o.push(s)):s=o[i],s}function n(){t=new WeakMap}return{get:e,dispose:n}}function vG(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"SunLight":case"DirectionalLight":n={direction:new Q,color:new $t};break;case"SpotLight":n={position:new Q,direction:new Q,color:new $t,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Q,color:new $t,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Q,skyColor:new $t,groundColor:new $t};break;case"RectAreaLight":n={color:new $t,position:new Q,halfWidth:new Q,halfHeight:new Q};break}return t[e.id]=n,n}}}function xG(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"SunLight":case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let bG=0;function yG(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function wG(t){const e=new vG,n=xG(),a={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)a.probe.push(new Q);const i=new Q,o=new fn,s=new fn;function r(c){let d=0,p=0,h=0;for(let R=0;R<9;R++)a.probe[R].set(0,0,0);let u=0,f=0,v=0,g=0,m=0,b=0,k=0,y=0,w=0,A=0,_=0,S=0,T=0,E=0;c.sort(yG);for(let R=0,B=c.length;R<B;R++){const D=c[R],$=D.color,G=D.intensity,O=D.distance;let J=null;if(D.shadow&&D.shadow.map&&(D.shadow.map.texture.format===sl?J=D.shadow.map.texture:J=D.shadow.map.depthTexture||D.shadow.map.texture),D.isAmbientLight)d+=$.r*G,p+=$.g*G,h+=$.b*G;else if(D.isLightProbe){for(let ne=0;ne<9;ne++)a.probe[ne].addScaledVector(D.sh.coefficients[ne],G);E++}else if(D.isSunLight){const ne=e.get(D);if(ne.color.copy(D.color).multiplyScalar(D.intensity),D.castShadow){const ae=D.shadow,q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize.copy(ae.mapSize).multiply(ae.getFrameExtents()),a.sunShadow[f]=q,a.sunShadowMap[f]=J;const we=ae.getViewportCount();for(let Re=0;Re<we;Re++)a.sunShadowMatrix[v+Re]=ae.getMatrix(Re),a.sunShadowCascade[v+Re]=ae._cascadeData[Re];v+=we,f++}a.sun[u]=ne,u++}else if(D.isDirectionalLight){const ne=e.get(D);if(ne.color.copy(D.color).multiplyScalar(D.intensity),D.castShadow){const ae=D.shadow,q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize=ae.mapSize,a.directionalShadow[g]=q,a.directionalShadowMap[g]=J,a.directionalShadowMatrix[g]=D.shadow.matrix,w++}a.directional[g]=ne,g++}else if(D.isSpotLight){const ne=e.get(D);ne.position.setFromMatrixPosition(D.matrixWorld),ne.color.copy($).multiplyScalar(G),ne.distance=O,ne.coneCos=Math.cos(D.angle),ne.penumbraCos=Math.cos(D.angle*(1-D.penumbra)),ne.decay=D.decay,a.spot[b]=ne;const ae=D.shadow;if(D.map&&(a.spotLightMap[S]=D.map,S++,ae.updateMatrices(D),D.castShadow&&T++),a.spotLightMatrix[b]=ae.matrix,D.castShadow){const q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize=ae.mapSize,a.spotShadow[b]=q,a.spotShadowMap[b]=J,_++}b++}else if(D.isRectAreaLight){const ne=e.get(D);ne.color.copy($).multiplyScalar(G),ne.halfWidth.set(D.width*.5,0,0),ne.halfHeight.set(0,D.height*.5,0),a.rectArea[k]=ne,k++}else if(D.isPointLight){const ne=e.get(D);if(ne.color.copy(D.color).multiplyScalar(D.intensity),ne.distance=D.distance,ne.decay=D.decay,D.castShadow){const ae=D.shadow,q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize=ae.mapSize,q.shadowCameraNear=ae.camera.near,q.shadowCameraFar=ae.camera.far,a.pointShadow[m]=q,a.pointShadowMap[m]=J,a.pointShadowMatrix[m]=D.shadow.matrix,A++}a.point[m]=ne,m++}else if(D.isHemisphereLight){const ne=e.get(D);ne.skyColor.copy(D.color).multiplyScalar(G),ne.groundColor.copy(D.groundColor).multiplyScalar(G),a.hemi[y]=ne,y++}}k>0&&(t.has("OES_texture_float_linear")===!0?(a.rectAreaLTC1=$e.LTC_FLOAT_1,a.rectAreaLTC2=$e.LTC_FLOAT_2):(a.rectAreaLTC1=$e.LTC_HALF_1,a.rectAreaLTC2=$e.LTC_HALF_2)),a.ambient[0]=d,a.ambient[1]=p,a.ambient[2]=h;const P=a.hash;(P.sunLength!==u||P.directionalLength!==g||P.pointLength!==m||P.spotLength!==b||P.rectAreaLength!==k||P.hemiLength!==y||P.numSunShadows!==f||P.numDirectionalShadows!==w||P.numPointShadows!==A||P.numSpotShadows!==_||P.numSpotMaps!==S||P.numLightProbes!==E)&&(a.sun.length=u,a.directional.length=g,a.spot.length=b,a.rectArea.length=k,a.point.length=m,a.hemi.length=y,a.sunShadow.length=f,a.sunShadowMap.length=f,a.sunShadowMatrix.length=v,a.sunShadowCascade.length=v,a.directionalShadow.length=w,a.directionalShadowMap.length=w,a.directionalShadowMatrix.length=w,a.pointShadow.length=A,a.pointShadowMap.length=A,a.pointShadowMatrix.length=A,a.spotShadow.length=_,a.spotShadowMap.length=_,a.spotLightMatrix.length=_+S-T,a.spotLightMap.length=S,a.numSpotLightShadowsWithMaps=T,a.numLightProbes=E,P.sunLength=u,P.directionalLength=g,P.pointLength=m,P.spotLength=b,P.rectAreaLength=k,P.hemiLength=y,P.numSunShadows=f,P.numDirectionalShadows=w,P.numPointShadows=A,P.numSpotShadows=_,P.numSpotMaps=S,P.numLightProbes=E,a.version=bG++)}function l(c,d){let p=0,h=0,u=0,f=0,v=0,g=0;const m=d.matrixWorldInverse;for(let b=0,k=c.length;b<k;b++){const y=c[b];if(y.isSunLight){const w=a.sun[p];w.direction.setFromMatrixPosition(y.matrixWorld),w.direction.transformDirection(m),p++}else if(y.isDirectionalLight){const w=a.directional[h];w.direction.setFromMatrixPosition(y.matrixWorld),i.setFromMatrixPosition(y.target.matrixWorld),w.direction.sub(i),w.direction.transformDirection(m),h++}else if(y.isSpotLight){const w=a.spot[f];w.position.setFromMatrixPosition(y.matrixWorld),w.position.applyMatrix4(m),w.direction.setFromMatrixPosition(y.matrixWorld),i.setFromMatrixPosition(y.target.matrixWorld),w.direction.sub(i),w.direction.transformDirection(m),f++}else if(y.isRectAreaLight){const w=a.rectArea[v];w.position.setFromMatrixPosition(y.matrixWorld),w.position.applyMatrix4(m),s.identity(),o.copy(y.matrixWorld),o.premultiply(m),s.extractRotation(o),w.halfWidth.set(y.width*.5,0,0),w.halfHeight.set(0,y.height*.5,0),w.halfWidth.applyMatrix4(s),w.halfHeight.applyMatrix4(s),v++}else if(y.isPointLight){const w=a.point[u];w.position.setFromMatrixPosition(y.matrixWorld),w.position.applyMatrix4(m),u++}else if(y.isHemisphereLight){const w=a.hemi[g];w.direction.setFromMatrixPosition(y.matrixWorld),w.direction.transformDirection(m),g++}}}return{setup:r,setupView:l,state:a}}function iC(t){const e=new wG(t),n=[],a=[],i=[];function o(h){p.camera=h,n.length=0,a.length=0,i.length=0}function s(h){n.push(h)}function r(h){a.push(h)}function l(h){i.push(h)}function c(){e.setup(n)}function d(h){e.setupView(n,h)}const p={lightsArray:n,shadowsArray:a,lightProbeGridArray:i,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:o,state:p,setupLights:c,setupLightsView:d,pushLight:s,pushShadow:r,pushLightProbeGrid:l}}function kG(t){let e=new WeakMap;function n(i,o=0){const s=e.get(i);let r;return s===void 0?(r=new iC(t),e.set(i,[r])):o>=s.length?(r=new iC(t),s.push(r)):r=s[o],r}function a(){e=new WeakMap}return{get:n,dispose:a}}const SG=`void main() {
|
|
11664
|
+
`+q)}else $!==""?it("WebGLProgram: Program Info Log:",$):(G===""||O==="")&&(ne=!1);ne&&(P.diagnostics={runnable:J,programLog:$,vertexShader:{log:G,prefix:g},fragmentShader:{log:O,prefix:m}})}i.deleteShader(w),i.deleteShader(A),S=new tv(i,v),T=jW(i,v)}let S;this.getUniforms=function(){return S===void 0&&_(this),S};let T;this.getAttributes=function(){return T===void 0&&_(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(v,OW)),E},this.destroy=function(){a.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=$W++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=w,this.fragmentShader=A,this}let cG=0;class dG{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,n,a){const i=this._getShaderCacheForMaterial(e);return i.has(n)===!1&&(i.add(n),n.usedTimes++),i.has(a)===!1&&(i.add(a),a.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const a of n)a.usedTimes--,a.usedTimes===0&&this.shaderCache.delete(a.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let a=n.get(e);return a===void 0&&(a=new Set,n.set(e,a)),a}_getShaderStage(e){const n=this.shaderCache;let a=n.get(e);return a===void 0&&(a=new pG(e),n.set(e,a)),a}}class pG{constructor(e){this.id=cG++,this.code=e,this.usedTimes=0}}function hG(t){return t===sl||t===vg||t===xg}function uG(t,e,n,a,i,o){const s=new Q5,r=new dG,l=new Set,c=[],d=new Map,p=a.logarithmicDepthBuffer;let h=a.precision;const u={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function f(S){return l.add(S),S===0?"uv":`uv${S}`}function v(S,T,E,P,R,B){const D=P.fog,$=R.geometry,G=S.isMeshStandardMaterial||S.isMeshLambertMaterial||S.isMeshPhongMaterial?P.environment:null,O=S.isMeshStandardMaterial||S.isMeshLambertMaterial&&!S.envMap||S.isMeshPhongMaterial&&!S.envMap,J=e.get(S.envMap||G,O),ne=J&&J.mapping===pg?J.image.height:null,ae=u[S.type];S.precision!==null&&(h=a.getMaxPrecision(S.precision),h!==S.precision&&it("WebGLProgram.getParameters:",S.precision,"not supported, using",h,"instead."));const q=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,we=q!==void 0?q.length:0;let Re=0;$.morphAttributes.position!==void 0&&(Re=1),$.morphAttributes.normal!==void 0&&(Re=2),$.morphAttributes.color!==void 0&&(Re=3);let ot,Qe,st,de;if(ae){const at=yo[ae];ot=at.vertexShader,Qe=at.fragmentShader}else{ot=S.vertexShader,Qe=S.fragmentShader;const at=r.getVertexShaderStage(S),dt=r.getFragmentShaderStage(S);r.update(S,at,dt),st=at.id,de=dt.id}const Z=t.getRenderTarget(),Ne=t.state.buffers.depth.getReversed(),Xe=R.isInstancedMesh===!0,De=R.isBatchedMesh===!0,be=!!S.map,ft=!!S.matcap,rt=!!J,vt=!!S.aoMap,Rt=!!S.lightMap,mt=!!S.bumpMap&&S.wireframe===!1,Gt=!!S.normalMap,ln=!!S.displacementMap,cn=!!S.emissiveMap,Ut=!!S.metalnessMap,Jt=!!S.roughnessMap,K=S.anisotropy>0,dn=S.clearcoat>0,zt=S.dispersion>0,F=S.retroreflectivity>0,M=S.iridescence>0,ee=S.sheen>0,se=S.transmission>0,he=K&&!!S.anisotropyMap,Le=dn&&!!S.clearcoatMap,ze=dn&&!!S.clearcoatNormalMap,ge=dn&&!!S.clearcoatRoughnessMap,z=M&&!!S.iridescenceMap,j=M&&!!S.iridescenceThicknessMap,ce=ee&&!!S.sheenColorMap,I=ee&&!!S.sheenRoughnessMap,U=!!S.specularMap,Y=!!S.specularColorMap,pe=!!S.specularIntensityMap,Ie=se&&!!S.transmissionMap,W=se&&!!S.thicknessMap,_e=!!S.gradientMap,fe=!!S.alphaMap,Me=S.alphaTest>0,Pe=!!S.alphaHash,ke=!!S.extensions;let Ce=uo;S.toneMapped&&(Z===null||Z.isXRRenderTarget===!0)&&(Ce=t.toneMapping);const Ee={shaderID:ae,shaderType:S.type,shaderName:S.name,vertexShader:ot,fragmentShader:Qe,defines:S.defines,customVertexShaderID:st,customFragmentShaderID:de,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:h,batching:De,batchingColor:De&&R._colorsTexture!==null,instancing:Xe,instancingColor:Xe&&R.instanceColor!==null,instancingMorph:Xe&&R.morphTexture!==null,outputColorSpace:Z===null?t.outputColorSpace:Z.isXRRenderTarget===!0?Z.texture.colorSpace:Ct.workingColorSpace,alphaToCoverage:!!S.alphaToCoverage,map:be,matcap:ft,envMap:rt,envMapMode:rt&&J.mapping,envMapCubeUVHeight:ne,aoMap:vt,lightMap:Rt,bumpMap:mt,normalMap:Gt,displacementMap:ln,emissiveMap:cn,normalMapObjectSpace:Gt&&S.normalMapType===MH,normalMapTangentSpace:Gt&&S.normalMapType===H5,packedNormalMap:Gt&&S.normalMapType===H5&&hG(S.normalMap.format),metalnessMap:Ut,roughnessMap:Jt,anisotropy:K,anisotropyMap:he,clearcoat:dn,clearcoatMap:Le,clearcoatNormalMap:ze,clearcoatRoughnessMap:ge,dispersion:zt,retroreflection:F,iridescence:M,iridescenceMap:z,iridescenceThicknessMap:j,sheen:ee,sheenColorMap:ce,sheenRoughnessMap:I,specularMap:U,specularColorMap:Y,specularIntensityMap:pe,transmission:se,transmissionMap:Ie,thicknessMap:W,gradientMap:_e,opaque:S.transparent===!1&&S.blending===zc&&S.alphaToCoverage===!1,alphaMap:fe,alphaTest:Me,alphaHash:Pe,combine:S.combine,mapUv:be&&f(S.map.channel),aoMapUv:vt&&f(S.aoMap.channel),lightMapUv:Rt&&f(S.lightMap.channel),bumpMapUv:mt&&f(S.bumpMap.channel),normalMapUv:Gt&&f(S.normalMap.channel),displacementMapUv:ln&&f(S.displacementMap.channel),emissiveMapUv:cn&&f(S.emissiveMap.channel),metalnessMapUv:Ut&&f(S.metalnessMap.channel),roughnessMapUv:Jt&&f(S.roughnessMap.channel),anisotropyMapUv:he&&f(S.anisotropyMap.channel),clearcoatMapUv:Le&&f(S.clearcoatMap.channel),clearcoatNormalMapUv:ze&&f(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ge&&f(S.clearcoatRoughnessMap.channel),iridescenceMapUv:z&&f(S.iridescenceMap.channel),iridescenceThicknessMapUv:j&&f(S.iridescenceThicknessMap.channel),sheenColorMapUv:ce&&f(S.sheenColorMap.channel),sheenRoughnessMapUv:I&&f(S.sheenRoughnessMap.channel),specularMapUv:U&&f(S.specularMap.channel),specularColorMapUv:Y&&f(S.specularColorMap.channel),specularIntensityMapUv:pe&&f(S.specularIntensityMap.channel),transmissionMapUv:Ie&&f(S.transmissionMap.channel),thicknessMapUv:W&&f(S.thicknessMap.channel),alphaMapUv:fe&&f(S.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(Gt||K),vertexNormals:!!$.attributes.normal,vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,pointsUvs:R.isPoints===!0&&!!$.attributes.uv&&(be||fe),fog:!!D,useFog:S.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:S.wireframe===!1&&(S.flatShading===!0||$.attributes.normal===void 0&&Gt===!1&&(S.isMeshLambertMaterial||S.isMeshPhongMaterial||S.isMeshStandardMaterial||S.isMeshPhysicalMaterial)),sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:p,reversedDepthBuffer:Ne,skinning:R.isSkinnedMesh===!0,hasPositionAttribute:$.attributes.position!==void 0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:we,morphTextureStride:Re,numSunLights:T.sun.length,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numSunLightShadows:T.sunShadowMap.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numLightProbes:T.numLightProbes,numLightProbeGrids:B.length,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:S.dithering,shadowMapEnabled:t.shadowMap.enabled&&E.length>0,shadowMapType:t.shadowMap.type,toneMapping:Ce,decodeVideoTexture:be&&S.map.isVideoTexture===!0&&Ct.getTransfer(S.map.colorSpace)===Ht,decodeVideoTextureEmissive:cn&&S.emissiveMap.isVideoTexture===!0&&Ct.getTransfer(S.emissiveMap.colorSpace)===Ht,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===es,flipSided:S.side===Ea,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionClipCullDistance:ke&&S.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ke&&S.extensions.multiDraw===!0||De)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()};return Ee.vertexUv1s=l.has(1),Ee.vertexUv2s=l.has(2),Ee.vertexUv3s=l.has(3),l.clear(),Ee}function g(S){const T=[];if(S.shaderID?T.push(S.shaderID):(T.push(S.customVertexShaderID),T.push(S.customFragmentShaderID)),S.defines!==void 0)for(const E in S.defines)T.push(E),T.push(S.defines[E]);return S.isRawShaderMaterial===!1&&(m(T,S),b(T,S),T.push(t.outputColorSpace)),T.push(S.customProgramCacheKey),T.join()}function m(S,T){S.push(T.precision),S.push(T.outputColorSpace),S.push(T.envMapMode),S.push(T.envMapCubeUVHeight),S.push(T.mapUv),S.push(T.alphaMapUv),S.push(T.lightMapUv),S.push(T.aoMapUv),S.push(T.bumpMapUv),S.push(T.normalMapUv),S.push(T.displacementMapUv),S.push(T.emissiveMapUv),S.push(T.metalnessMapUv),S.push(T.roughnessMapUv),S.push(T.anisotropyMapUv),S.push(T.clearcoatMapUv),S.push(T.clearcoatNormalMapUv),S.push(T.clearcoatRoughnessMapUv),S.push(T.iridescenceMapUv),S.push(T.iridescenceThicknessMapUv),S.push(T.sheenColorMapUv),S.push(T.sheenRoughnessMapUv),S.push(T.specularMapUv),S.push(T.specularColorMapUv),S.push(T.specularIntensityMapUv),S.push(T.transmissionMapUv),S.push(T.thicknessMapUv),S.push(T.combine),S.push(T.fogExp2),S.push(T.sizeAttenuation),S.push(T.morphTargetsCount),S.push(T.morphAttributeCount),S.push(T.numSunLights),S.push(T.numDirLights),S.push(T.numPointLights),S.push(T.numSpotLights),S.push(T.numSpotLightMaps),S.push(T.numHemiLights),S.push(T.numRectAreaLights),S.push(T.numSunLightShadows),S.push(T.numDirLightShadows),S.push(T.numPointLightShadows),S.push(T.numSpotLightShadows),S.push(T.numSpotLightShadowsWithMaps),S.push(T.numLightProbes),S.push(T.shadowMapType),S.push(T.toneMapping),S.push(T.numClippingPlanes),S.push(T.numClipIntersection),S.push(T.depthPacking)}function b(S,T){s.disableAll(),T.instancing&&s.enable(0),T.instancingColor&&s.enable(1),T.instancingMorph&&s.enable(2),T.matcap&&s.enable(3),T.envMap&&s.enable(4),T.normalMapObjectSpace&&s.enable(5),T.normalMapTangentSpace&&s.enable(6),T.clearcoat&&s.enable(7),T.iridescence&&s.enable(8),T.alphaTest&&s.enable(9),T.vertexColors&&s.enable(10),T.vertexAlphas&&s.enable(11),T.vertexUv1s&&s.enable(12),T.vertexUv2s&&s.enable(13),T.vertexUv3s&&s.enable(14),T.vertexTangents&&s.enable(15),T.anisotropy&&s.enable(16),T.alphaHash&&s.enable(17),T.batching&&s.enable(18),T.dispersion&&s.enable(19),T.retroreflection&&s.enable(24),T.batchingColor&&s.enable(20),T.gradientMap&&s.enable(21),T.packedNormalMap&&s.enable(22),T.vertexNormals&&s.enable(23),S.push(s.mask),s.disableAll(),T.fog&&s.enable(0),T.useFog&&s.enable(1),T.flatShading&&s.enable(2),T.logarithmicDepthBuffer&&s.enable(3),T.reversedDepthBuffer&&s.enable(4),T.skinning&&s.enable(5),T.morphTargets&&s.enable(6),T.morphNormals&&s.enable(7),T.morphColors&&s.enable(8),T.premultipliedAlpha&&s.enable(9),T.shadowMapEnabled&&s.enable(10),T.doubleSided&&s.enable(11),T.flipSided&&s.enable(12),T.useDepthPacking&&s.enable(13),T.dithering&&s.enable(14),T.transmission&&s.enable(15),T.sheen&&s.enable(16),T.opaque&&s.enable(17),T.pointsUvs&&s.enable(18),T.decodeVideoTexture&&s.enable(19),T.decodeVideoTextureEmissive&&s.enable(20),T.alphaToCoverage&&s.enable(21),T.numLightProbeGrids>0&&s.enable(22),T.hasPositionAttribute&&s.enable(23),S.push(s.mask)}function k(S){const T=u[S.type];let E;if(T){const P=yo[T];E=fq.clone(P.uniforms)}else E=S.uniforms;return E}function y(S,T){let E=d.get(T);return E!==void 0?++E.usedTimes:(E=new lG(t,T,S,i),c.push(E),d.set(T,E)),E}function w(S){if(--S.usedTimes===0){const T=c.indexOf(S);c[T]=c[c.length-1],c.pop(),d.delete(S.cacheKey),S.destroy()}}function A(S){r.remove(S)}function _(){r.dispose()}return{getParameters:v,getProgramCacheKey:g,getUniforms:k,acquireProgram:y,releaseProgram:w,releaseShaderCache:A,programs:c,dispose:_}}function fG(){let t=new WeakMap;function e(s){return t.has(s)}function n(s){let r=t.get(s);return r===void 0&&(r={},t.set(s,r)),r}function a(s){t.delete(s)}function i(s,r,l){t.get(s)[r]=l}function o(){t=new WeakMap}return{has:e,get:n,remove:a,update:i,dispose:o}}function mG(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.materialVariant!==e.materialVariant?t.materialVariant-e.materialVariant:t.z!==e.z?t.z-e.z:t.id-e.id}function nC(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function aC(){const t=[];let e=0;const n=[],a=[],i=[];function o(){e=0,n.length=0,a.length=0,i.length=0}function s(h){let u=0;return h.isInstancedMesh&&(u+=2),h.isSkinnedMesh&&(u+=1),u}function r(h,u,f,v,g,m){let b=t[e];return b===void 0?(b={id:h.id,object:h,geometry:u,material:f,materialVariant:s(h),groupOrder:v,renderOrder:h.renderOrder,z:g,group:m},t[e]=b):(b.id=h.id,b.object=h,b.geometry=u,b.material=f,b.materialVariant=s(h),b.groupOrder=v,b.renderOrder=h.renderOrder,b.z=g,b.group=m),e++,b}function l(h,u,f,v,g,m,b){b.reversedDepth===!0&&(g=-g);const k=r(h,u,f,v,g,m);f.transmission>0?a.push(k):f.transparent===!0?i.push(k):n.push(k)}function c(h,u,f,v,g,m){const b=r(h,u,f,v,g,m);f.transmission>0?a.unshift(b):f.transparent===!0?i.unshift(b):n.unshift(b)}function d(h,u){n.length>1&&n.sort(h||mG),a.length>1&&a.sort(u||nC),i.length>1&&i.sort(u||nC)}function p(){for(let h=e,u=t.length;h<u;h++){const f=t[h];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:n,transmissive:a,transparent:i,init:o,push:l,unshift:c,finish:p,sort:d}}function gG(){let t=new WeakMap;function e(a,i){const o=t.get(a);let s;return o===void 0?(s=new aC,t.set(a,[s])):i>=o.length?(s=new aC,o.push(s)):s=o[i],s}function n(){t=new WeakMap}return{get:e,dispose:n}}function vG(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"SunLight":case"DirectionalLight":n={direction:new Q,color:new $t};break;case"SpotLight":n={position:new Q,direction:new Q,color:new $t,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Q,color:new $t,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Q,skyColor:new $t,groundColor:new $t};break;case"RectAreaLight":n={color:new $t,position:new Q,halfWidth:new Q,halfHeight:new Q};break}return t[e.id]=n,n}}}function xG(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"SunLight":case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let bG=0;function yG(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function wG(t){const e=new vG,n=xG(),a={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)a.probe.push(new Q);const i=new Q,o=new fn,s=new fn;function r(c){let d=0,p=0,h=0;for(let R=0;R<9;R++)a.probe[R].set(0,0,0);let u=0,f=0,v=0,g=0,m=0,b=0,k=0,y=0,w=0,A=0,_=0,S=0,T=0,E=0;c.sort(yG);for(let R=0,B=c.length;R<B;R++){const D=c[R],$=D.color,G=D.intensity,O=D.distance;let J=null;if(D.shadow&&D.shadow.map&&(D.shadow.map.texture.format===sl?J=D.shadow.map.texture:J=D.shadow.map.depthTexture||D.shadow.map.texture),D.isAmbientLight)d+=$.r*G,p+=$.g*G,h+=$.b*G;else if(D.isLightProbe){for(let ne=0;ne<9;ne++)a.probe[ne].addScaledVector(D.sh.coefficients[ne],G);E++}else if(D.isSunLight){const ne=e.get(D);if(ne.color.copy(D.color).multiplyScalar(D.intensity),D.castShadow){const ae=D.shadow,q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize.copy(ae.mapSize).multiply(ae.getFrameExtents()),a.sunShadow[f]=q,a.sunShadowMap[f]=J;const we=ae.getViewportCount();for(let Re=0;Re<we;Re++)a.sunShadowMatrix[v+Re]=ae.getMatrix(Re),a.sunShadowCascade[v+Re]=ae._cascadeData[Re];v+=we,f++}a.sun[u]=ne,u++}else if(D.isDirectionalLight){const ne=e.get(D);if(ne.color.copy(D.color).multiplyScalar(D.intensity),D.castShadow){const ae=D.shadow,q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize=ae.mapSize,a.directionalShadow[g]=q,a.directionalShadowMap[g]=J,a.directionalShadowMatrix[g]=D.shadow.matrix,w++}a.directional[g]=ne,g++}else if(D.isSpotLight){const ne=e.get(D);ne.position.setFromMatrixPosition(D.matrixWorld),ne.color.copy($).multiplyScalar(G),ne.distance=O,ne.coneCos=Math.cos(D.angle),ne.penumbraCos=Math.cos(D.angle*(1-D.penumbra)),ne.decay=D.decay,a.spot[b]=ne;const ae=D.shadow;if(D.map&&(a.spotLightMap[S]=D.map,S++,ae.updateMatrices(D),D.castShadow&&T++),a.spotLightMatrix[b]=ae.matrix,D.castShadow){const q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize=ae.mapSize,a.spotShadow[b]=q,a.spotShadowMap[b]=J,_++}b++}else if(D.isRectAreaLight){const ne=e.get(D);ne.color.copy($).multiplyScalar(G),ne.halfWidth.set(D.width*.5,0,0),ne.halfHeight.set(0,D.height*.5,0),a.rectArea[k]=ne,k++}else if(D.isPointLight){const ne=e.get(D);if(ne.color.copy(D.color).multiplyScalar(D.intensity),ne.distance=D.distance,ne.decay=D.decay,D.castShadow){const ae=D.shadow,q=n.get(D);q.shadowIntensity=ae.intensity,q.shadowBias=ae.bias,q.shadowNormalBias=ae.normalBias,q.shadowRadius=ae.radius,q.shadowMapSize=ae.mapSize,q.shadowCameraNear=ae.camera.near,q.shadowCameraFar=ae.camera.far,a.pointShadow[m]=q,a.pointShadowMap[m]=J,a.pointShadowMatrix[m]=D.shadow.matrix,A++}a.point[m]=ne,m++}else if(D.isHemisphereLight){const ne=e.get(D);ne.skyColor.copy(D.color).multiplyScalar(G),ne.groundColor.copy(D.groundColor).multiplyScalar(G),a.hemi[y]=ne,y++}}k>0&&(t.has("OES_texture_float_linear")===!0?(a.rectAreaLTC1=$e.LTC_FLOAT_1,a.rectAreaLTC2=$e.LTC_FLOAT_2):(a.rectAreaLTC1=$e.LTC_HALF_1,a.rectAreaLTC2=$e.LTC_HALF_2)),a.ambient[0]=d,a.ambient[1]=p,a.ambient[2]=h;const P=a.hash;(P.sunLength!==u||P.directionalLength!==g||P.pointLength!==m||P.spotLength!==b||P.rectAreaLength!==k||P.hemiLength!==y||P.numSunShadows!==f||P.numDirectionalShadows!==w||P.numPointShadows!==A||P.numSpotShadows!==_||P.numSpotMaps!==S||P.numLightProbes!==E)&&(a.sun.length=u,a.directional.length=g,a.spot.length=b,a.rectArea.length=k,a.point.length=m,a.hemi.length=y,a.sunShadow.length=f,a.sunShadowMap.length=f,a.sunShadowMatrix.length=v,a.sunShadowCascade.length=v,a.directionalShadow.length=w,a.directionalShadowMap.length=w,a.directionalShadowMatrix.length=w,a.pointShadow.length=A,a.pointShadowMap.length=A,a.pointShadowMatrix.length=A,a.spotShadow.length=_,a.spotShadowMap.length=_,a.spotLightMatrix.length=_+S-T,a.spotLightMap.length=S,a.numSpotLightShadowsWithMaps=T,a.numLightProbes=E,P.sunLength=u,P.directionalLength=g,P.pointLength=m,P.spotLength=b,P.rectAreaLength=k,P.hemiLength=y,P.numSunShadows=f,P.numDirectionalShadows=w,P.numPointShadows=A,P.numSpotShadows=_,P.numSpotMaps=S,P.numLightProbes=E,a.version=bG++)}function l(c,d){let p=0,h=0,u=0,f=0,v=0,g=0;const m=d.matrixWorldInverse;for(let b=0,k=c.length;b<k;b++){const y=c[b];if(y.isSunLight){const w=a.sun[p];w.direction.setFromMatrixPosition(y.matrixWorld),w.direction.transformDirection(m),p++}else if(y.isDirectionalLight){const w=a.directional[h];w.direction.setFromMatrixPosition(y.matrixWorld),i.setFromMatrixPosition(y.target.matrixWorld),w.direction.sub(i),w.direction.transformDirection(m),h++}else if(y.isSpotLight){const w=a.spot[f];w.position.setFromMatrixPosition(y.matrixWorld),w.position.applyMatrix4(m),w.direction.setFromMatrixPosition(y.matrixWorld),i.setFromMatrixPosition(y.target.matrixWorld),w.direction.sub(i),w.direction.transformDirection(m),f++}else if(y.isRectAreaLight){const w=a.rectArea[v];w.position.setFromMatrixPosition(y.matrixWorld),w.position.applyMatrix4(m),s.identity(),o.copy(y.matrixWorld),o.premultiply(m),s.extractRotation(o),w.halfWidth.set(y.width*.5,0,0),w.halfHeight.set(0,y.height*.5,0),w.halfWidth.applyMatrix4(s),w.halfHeight.applyMatrix4(s),v++}else if(y.isPointLight){const w=a.point[u];w.position.setFromMatrixPosition(y.matrixWorld),w.position.applyMatrix4(m),u++}else if(y.isHemisphereLight){const w=a.hemi[g];w.direction.setFromMatrixPosition(y.matrixWorld),w.direction.transformDirection(m),g++}}}return{setup:r,setupView:l,state:a}}function iC(t){const e=new wG(t),n=[],a=[],i=[];function o(h){p.camera=h,n.length=0,a.length=0,i.length=0}function s(h){n.push(h)}function r(h){a.push(h)}function l(h){i.push(h)}function c(){e.setup(n)}function d(h){e.setupView(n,h)}const p={lightsArray:n,shadowsArray:a,lightProbeGridArray:i,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:o,state:p,setupLights:c,setupLightsView:d,pushLight:s,pushShadow:r,pushLightProbeGrid:l}}function kG(t){let e=new WeakMap;function n(i,o=0){const s=e.get(i);let r;return s===void 0?(r=new iC(t),e.set(i,[r])):o>=s.length?(r=new iC(t),s.push(r)):r=s[o],r}function a(){e=new WeakMap}return{get:n,dispose:a}}const SG=`void main() {
|
|
11645
11665
|
gl_Position = vec4( position, 1.0 );
|
|
11646
11666
|
}`,MG=`uniform sampler2D shadow_pass;
|
|
11647
11667
|
uniform vec2 resolution;
|
|
@@ -11668,7 +11688,7 @@ void main() {
|
|
|
11668
11688
|
squared_mean = squared_mean / samples;
|
|
11669
11689
|
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
|
11670
11690
|
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
|
11671
|
-
}`,AG=[new Q(1,0,0),new Q(-1,0,0),new Q(0,1,0),new Q(0,-1,0),new Q(0,0,1),new Q(0,0,-1)],TG=[new Q(0,-1,0),new Q(0,-1,0),new Q(0,0,1),new Q(0,0,-1),new Q(0,-1,0),new Q(0,-1,0)],oC=new fn,Kh=new Q,ek=new Q;function EG(t,e,n){let a=new u_;const i=new ut,o=new ut,s=new yn,r=new xq,l=new bq,c={},d=n.maxTextureSize,p={[nl]:Ea,[Ea]:nl,[es]:es},h=new na({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ut},radius:{value:4}},vertexShader:SG,fragmentShader:MG}),u=h.clone();u.defines.HORIZONTAL_PASS=1;const f=new Ln;f.setAttribute("position",new xo(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new hs(f,h),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=dg;let m=this.type;this.render=function(A,_,S){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||A.length===0)return;this.type===tH&&(it("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=dg);const T=t.getRenderTarget(),E=t.getActiveCubeFace(),P=t.getActiveMipmapLevel(),R=t.state;R.setBlending(ts),R.buffers.depth.getReversed()===!0?R.buffers.color.setClear(0,0,0,0):R.buffers.color.setClear(1,1,1,1),R.buffers.depth.setTest(!0),R.setScissorTest(!1);const B=m!==this.type;B&&_.traverse(function(D){D.material&&(Array.isArray(D.material)?D.material.forEach($=>$.needsUpdate=!0):D.material.needsUpdate=!0)});for(let D=0,$=A.length;D<$;D++){const G=A[D],O=G.shadow;if(O===void 0){it("WebGLShadowMap:",G,"has no shadow.");continue}if(O.autoUpdate===!1&&O.needsUpdate===!1)continue;i.copy(O.mapSize);const J=O.getFrameExtents();i.multiply(J),o.copy(O.mapSize),(i.x>d||i.y>d)&&(i.x>d&&(o.x=Math.floor(d/J.x),i.x=o.x*J.x,O.mapSize.x=o.x),i.y>d&&(o.y=Math.floor(d/J.y),i.y=o.y*J.y,O.mapSize.y=o.y));const ne=t.state.buffers.depth.getReversed();if(O.camera._reversedDepth=ne,O.map===null||B===!0){if(O.map!==null&&(O.map.depthTexture!==null&&(O.map.depthTexture.dispose(),O.map.depthTexture=null),O.map.dispose()),this.type===Ih){if(G.isPointLight){it("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}O.map=new Mi(i.x,i.y,{format:sl,type:go,minFilter:Qn,magFilter:Qn,generateMipmaps:!1}),O.map.texture.name=G.name+".shadowMap",O.map.depthTexture=new Vh(i.x,i.y,mo),O.map.depthTexture.name=G.name+".shadowMapDepth",O.map.depthTexture.format=is,O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Vn,O.map.depthTexture.magFilter=Vn}else G.isPointLight?(O.map=new $_(i.x),O.map.depthTexture=new hq(i.x,fo)):(O.map=new Mi(i.x,i.y),O.map.depthTexture=new Vh(i.x,i.y,fo)),O.map.depthTexture.name=G.name+".shadowMap",O.map.depthTexture.format=is,this.type===dg?(O.map.depthTexture.compareFunction=ne?b1:x1,O.map.depthTexture.minFilter=Qn,O.map.depthTexture.magFilter=Qn):(O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Vn,O.map.depthTexture.magFilter=Vn);O.camera.updateProjectionMatrix()}O.map.isWebGLCubeRenderTarget!==!0&&(O.map.width!==i.x||O.map.height!==i.y)&&O.map.setSize(i.x,i.y);const ae=O.map.isWebGLCubeRenderTarget?6:O.getViewportCount();G.isPointLight!==!0&&O.updateMatrices(G,S);for(let q=0;q<ae;q++){const we=O.getCamera(q);if(G.isPointLight){const Re=O.camera,ot=O.matrix,Qe=G.distance||Re.far;Qe!==Re.far&&(Re.far=Qe,Re.updateProjectionMatrix()),Kh.setFromMatrixPosition(G.matrixWorld),Re.position.copy(Kh),ek.copy(Re.position),ek.add(AG[q]),Re.up.copy(TG[q]),Re.lookAt(ek),Re.updateMatrixWorld(),ot.makeTranslation(-Kh.x,-Kh.y,-Kh.z),oC.multiplyMatrices(Re.projectionMatrix,Re.matrixWorldInverse),O._frustum.setFromProjectionMatrix(oC,Re.coordinateSystem,Re.reversedDepth)}if(O.map.isWebGLCubeRenderTarget)t.setRenderTarget(O.map,q),t.clear();else{q===0&&(t.setRenderTarget(O.map),t.clear());const Re=O.getViewport(q);s.set(o.x*Re.x,o.y*Re.y,o.x*Re.z,o.y*Re.w),R.viewport(s)}a=O.getFrustum(q),y(_,S,we,G,this.type)}O.isPointLightShadow!==!0&&this.type===Ih&&b(O,S),O.needsUpdate=!1}m=this.type,g.needsUpdate=!1,t.setRenderTarget(T,E,P)};function b(A,_){const S=e.update(v);h.defines.VSM_SAMPLES!==A.blurSamples&&(h.defines.VSM_SAMPLES=A.blurSamples,u.defines.VSM_SAMPLES=A.blurSamples,h.needsUpdate=!0,u.needsUpdate=!0),A.mapPass===null?A.mapPass=new Mi(i.x,i.y,{format:sl,type:go}):(A.mapPass.width!==A.map.width||A.mapPass.height!==A.map.height)&&A.mapPass.setSize(A.map.width,A.map.height),h.uniforms.shadow_pass.value=A.map.depthTexture,h.uniforms.resolution.value.set(A.map.width,A.map.height),h.uniforms.radius.value=A.radius,t.setRenderTarget(A.mapPass),t.clear(),t.renderBufferDirect(_,null,S,h,v,null),u.uniforms.shadow_pass.value=A.mapPass.texture,u.uniforms.resolution.value.set(A.map.width,A.map.height),u.uniforms.radius.value=A.radius,t.setRenderTarget(A.map),t.clear(),t.renderBufferDirect(_,null,S,u,v,null)}function k(A,_,S,T){let E=null;const P=S.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(P!==void 0)E=P;else if(E=S.isPointLight===!0?l:r,t.localClippingEnabled&&_.clipShadows===!0&&Array.isArray(_.clippingPlanes)&&_.clippingPlanes.length!==0||_.displacementMap&&_.displacementScale!==0||_.alphaMap&&_.alphaTest>0||_.map&&_.alphaTest>0||_.alphaToCoverage===!0){const R=E.uuid,B=_.uuid;let D=c[R];D===void 0&&(D={},c[R]=D);let $=D[B];$===void 0&&($=E.clone(),D[B]=$,_.addEventListener("dispose",w)),E=$}if(E.visible=_.visible,E.wireframe=_.wireframe,T===Ih?E.side=_.shadowSide!==null?_.shadowSide:_.side:E.side=_.shadowSide!==null?_.shadowSide:p[_.side],E.alphaMap=_.alphaMap,E.alphaTest=_.alphaToCoverage===!0?.5:_.alphaTest,E.map=_.map,E.clipShadows=_.clipShadows,E.clippingPlanes=_.clippingPlanes,E.clipIntersection=_.clipIntersection,E.displacementMap=_.displacementMap,E.displacementScale=_.displacementScale,E.displacementBias=_.displacementBias,E.wireframeLinewidth=_.wireframeLinewidth,E.linewidth=_.linewidth,S.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const R=t.properties.get(E);R.light=S}return E}function y(A,_,S,T,E){if(A.visible===!1)return;if(A.layers.test(_.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&E===Ih)&&(!A.frustumCulled||A.intersectsFrustum(a))){A.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,A.matrixWorld);const B=e.update(A),D=A.material;if(Array.isArray(D)){const $=B.groups;for(let G=0,O=$.length;G<O;G++){const J=$[G],ne=D[J.materialIndex];if(ne&&ne.visible){const ae=k(A,ne,T,E);A.onBeforeShadow(t,A,_,S,B,ae,J),t.renderBufferDirect(S,null,B,ae,A,J),A.onAfterShadow(t,A,_,S,B,ae,J)}}}else if(D.visible){const $=k(A,D,T,E);A.onBeforeShadow(t,A,_,S,B,$,null),t.renderBufferDirect(S,null,B,$,A,null),A.onAfterShadow(t,A,_,S,B,$,null)}}const R=A.children;for(let B=0,D=R.length;B<D;B++)y(R[B],_,S,T,E)}function w(A){A.target.removeEventListener("dispose",w);for(const S in c){const T=c[S],E=A.target.uuid;E in T&&(T[E].dispose(),delete T[E])}}}function _G(t,e){function n(){let W=!1;const _e=new yn;let fe=null;const Me=new yn(0,0,0,0);return{setMask:function(Pe){fe!==Pe&&!W&&(t.colorMask(Pe,Pe,Pe,Pe),fe=Pe)},setLocked:function(Pe){W=Pe},setClear:function(Pe,ke,Ce,Ee,at){at===!0&&(Pe*=Ee,ke*=Ee,Ce*=Ee),_e.set(Pe,ke,Ce,Ee),Me.equals(_e)===!1&&(t.clearColor(Pe,ke,Ce,Ee),Me.copy(_e))},reset:function(){W=!1,fe=null,Me.set(-1,0,0,0)}}}function a(){let W=!1,_e=!1,fe=null,Me=null,Pe=null;return{setReversed:function(ke){if(_e!==ke){const Ce=e.get("EXT_clip_control");ke?Ce.clipControlEXT(Ce.LOWER_LEFT_EXT,Ce.ZERO_TO_ONE_EXT):Ce.clipControlEXT(Ce.LOWER_LEFT_EXT,Ce.NEGATIVE_ONE_TO_ONE_EXT),_e=ke;const Ee=Pe;Pe=null,this.setClear(Ee)}},getReversed:function(){return _e},setTest:function(ke){ke?Z(t.DEPTH_TEST):Ne(t.DEPTH_TEST)},setMask:function(ke){fe!==ke&&!W&&(t.depthMask(ke),fe=ke)},setFunc:function(ke){if(_e&&(ke=OH[ke]),Me!==ke){switch(ke){case Sw:t.depthFunc(t.NEVER);break;case Mw:t.depthFunc(t.ALWAYS);break;case Aw:t.depthFunc(t.LESS);break;case Nh:t.depthFunc(t.LEQUAL);break;case Tw:t.depthFunc(t.EQUAL);break;case Ew:t.depthFunc(t.GEQUAL);break;case _w:t.depthFunc(t.GREATER);break;case Cw:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}Me=ke}},setLocked:function(ke){W=ke},setClear:function(ke){Pe!==ke&&(Pe=ke,_e&&(ke=1-ke),t.clearDepth(ke))},reset:function(){W=!1,fe=null,Me=null,Pe=null,_e=!1}}}function i(){let W=!1,_e=null,fe=null,Me=null,Pe=null,ke=null,Ce=null,Ee=null,at=null;return{setTest:function(dt){W||(dt?Z(t.STENCIL_TEST):Ne(t.STENCIL_TEST))},setMask:function(dt){_e!==dt&&!W&&(t.stencilMask(dt),_e=dt)},setFunc:function(dt,va,Ao){(fe!==dt||Me!==va||Pe!==Ao)&&(t.stencilFunc(dt,va,Ao),fe=dt,Me=va,Pe=Ao)},setOp:function(dt,va,Ao){(ke!==dt||Ce!==va||Ee!==Ao)&&(t.stencilOp(dt,va,Ao),ke=dt,Ce=va,Ee=Ao)},setLocked:function(dt){W=dt},setClear:function(dt){at!==dt&&(t.clearStencil(dt),at=dt)},reset:function(){W=!1,_e=null,fe=null,Me=null,Pe=null,ke=null,Ce=null,Ee=null,at=null}}}const o=new n,s=new a,r=new i,l=new WeakMap,c=new WeakMap;let d={},p={},h={},u=new WeakMap,f=[],v=null,g=!1,m=null,b=null,k=null,y=null,w=null,A=null,_=null,S=new $t(0,0,0),T=0,E=!1,P=null,R=null,B=null,D=null,$=null;const G=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let O=!1,J=0;const ne=t.getParameter(t.VERSION);ne.indexOf("WebGL")!==-1?(J=parseFloat(/^WebGL (\d)/.exec(ne)[1]),O=J>=1):ne.indexOf("OpenGL ES")!==-1&&(J=parseFloat(/^OpenGL ES (\d)/.exec(ne)[1]),O=J>=2);let ae=null,q={};const we=t.getParameter(t.SCISSOR_BOX),Re=t.getParameter(t.VIEWPORT),ot=new yn().fromArray(we),Qe=new yn().fromArray(Re);function st(W,_e,fe,Me){const Pe=new Uint8Array(4),ke=t.createTexture();t.bindTexture(W,ke),t.texParameteri(W,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(W,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Ce=0;Ce<fe;Ce++)W===t.TEXTURE_3D||W===t.TEXTURE_2D_ARRAY?t.texImage3D(_e,0,t.RGBA,1,1,Me,0,t.RGBA,t.UNSIGNED_BYTE,Pe):t.texImage2D(_e+Ce,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Pe);return ke}const de={};de[t.TEXTURE_2D]=st(t.TEXTURE_2D,t.TEXTURE_2D,1),de[t.TEXTURE_CUBE_MAP]=st(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),de[t.TEXTURE_2D_ARRAY]=st(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),de[t.TEXTURE_3D]=st(t.TEXTURE_3D,t.TEXTURE_3D,1,1),o.setClear(0,0,0,1),s.setClear(1),r.setClear(0),Z(t.DEPTH_TEST),s.setFunc(Nh),mt(!1),Gt(w5),Z(t.CULL_FACE),vt(ts);function Z(W){d[W]!==!0&&(t.enable(W),d[W]=!0)}function Ne(W){d[W]!==!1&&(t.disable(W),d[W]=!1)}function Xe(W,_e){return h[W]!==_e?(t.bindFramebuffer(W,_e),h[W]=_e,W===t.DRAW_FRAMEBUFFER&&(h[t.FRAMEBUFFER]=_e),W===t.FRAMEBUFFER&&(h[t.DRAW_FRAMEBUFFER]=_e),!0):!1}function De(W,_e){let fe=f,Me=!1;if(W){fe=u.get(_e),fe===void 0&&(fe=[],u.set(_e,fe));const Pe=W.textures;if(fe.length!==Pe.length||fe[0]!==t.COLOR_ATTACHMENT0){for(let ke=0,Ce=Pe.length;ke<Ce;ke++)fe[ke]=t.COLOR_ATTACHMENT0+ke;fe.length=Pe.length,Me=!0}}else fe[0]!==t.BACK&&(fe[0]=t.BACK,Me=!0);Me&&t.drawBuffers(fe)}function be(W){return v!==W?(t.useProgram(W),v=W,!0):!1}const ft={[Dc]:t.FUNC_ADD,[aH]:t.FUNC_SUBTRACT,[iH]:t.FUNC_REVERSE_SUBTRACT};ft[oH]=t.MIN,ft[sH]=t.MAX;const rt={[rH]:t.ZERO,[lH]:t.ONE,[cH]:t.SRC_COLOR,[M5]:t.SRC_ALPHA,[mH]:t.SRC_ALPHA_SATURATE,[uH]:t.DST_COLOR,[pH]:t.DST_ALPHA,[dH]:t.ONE_MINUS_SRC_COLOR,[A5]:t.ONE_MINUS_SRC_ALPHA,[fH]:t.ONE_MINUS_DST_COLOR,[hH]:t.ONE_MINUS_DST_ALPHA,[gH]:t.CONSTANT_COLOR,[vH]:t.ONE_MINUS_CONSTANT_COLOR,[xH]:t.CONSTANT_ALPHA,[bH]:t.ONE_MINUS_CONSTANT_ALPHA};function vt(W,_e,fe,Me,Pe,ke,Ce,Ee,at,dt){if(W===ts){g===!0&&(Ne(t.BLEND),g=!1);return}if(g===!1&&(Z(t.BLEND),g=!0),W!==nH){if(W!==m||dt!==E){if((b!==Dc||w!==Dc)&&(t.blendEquation(t.FUNC_ADD),b=Dc,w=Dc),dt)switch(W){case zc:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case ns:t.blendFunc(t.ONE,t.ONE);break;case k5:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case S5:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:Ot("WebGLState: Invalid blending: ",W);break}else switch(W){case zc:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case ns:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case k5:Ot("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case S5:Ot("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ot("WebGLState: Invalid blending: ",W);break}k=null,y=null,A=null,_=null,S.set(0,0,0),T=0,m=W,E=dt}return}Pe=Pe||_e,ke=ke||fe,Ce=Ce||Me,(_e!==b||Pe!==w)&&(t.blendEquationSeparate(ft[_e],ft[Pe]),b=_e,w=Pe),(fe!==k||Me!==y||ke!==A||Ce!==_)&&(t.blendFuncSeparate(rt[fe],rt[Me],rt[ke],rt[Ce]),k=fe,y=Me,A=ke,_=Ce),(Ee.equals(S)===!1||at!==T)&&(t.blendColor(Ee.r,Ee.g,Ee.b,at),S.copy(Ee),T=at),m=W,E=!1}function Rt(W,_e){W.side===es?Ne(t.CULL_FACE):Z(t.CULL_FACE);let fe=W.side===Ea;_e&&(fe=!fe),mt(fe),W.blending===zc&&W.transparent===!1?vt(ts):vt(W.blending,W.blendEquation,W.blendSrc,W.blendDst,W.blendEquationAlpha,W.blendSrcAlpha,W.blendDstAlpha,W.blendColor,W.blendAlpha,W.premultipliedAlpha),s.setFunc(W.depthFunc),s.setTest(W.depthTest),s.setMask(W.depthWrite),o.setMask(W.colorWrite);const Me=W.stencilWrite;r.setTest(Me),Me&&(r.setMask(W.stencilWriteMask),r.setFunc(W.stencilFunc,W.stencilRef,W.stencilFuncMask),r.setOp(W.stencilFail,W.stencilZFail,W.stencilZPass)),ln(W.polygonOffset,W.polygonOffsetFactor,W.polygonOffsetUnits),W.alphaToCoverage===!0?Z(t.SAMPLE_ALPHA_TO_COVERAGE):Ne(t.SAMPLE_ALPHA_TO_COVERAGE)}function mt(W){P!==W&&(W?t.frontFace(t.CW):t.frontFace(t.CCW),P=W)}function Gt(W){W!==QB?(Z(t.CULL_FACE),W!==R&&(W===w5?t.cullFace(t.BACK):W===eH?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):Ne(t.CULL_FACE),R=W}function rn(W){W!==B&&(O&&t.lineWidth(W),B=W)}function ln(W,_e,fe){W?(Z(t.POLYGON_OFFSET_FILL),(D!==_e||$!==fe)&&(D=_e,$=fe,s.getReversed()&&(_e=-_e),t.polygonOffset(_e,fe))):Ne(t.POLYGON_OFFSET_FILL)}function Ut(W){W?Z(t.SCISSOR_TEST):Ne(t.SCISSOR_TEST)}function Jt(W){W===void 0&&(W=t.TEXTURE0+G-1),ae!==W&&(t.activeTexture(W),ae=W)}function K(W,_e,fe){fe===void 0&&(ae===null?fe=t.TEXTURE0+G-1:fe=ae);let Me=q[fe];Me===void 0&&(Me={type:void 0,texture:void 0},q[fe]=Me),(Me.type!==W||Me.texture!==_e)&&(ae!==fe&&(t.activeTexture(fe),ae=fe),t.bindTexture(W,_e||de[W]),Me.type=W,Me.texture=_e)}function cn(){const W=q[ae];W!==void 0&&W.type!==void 0&&(t.bindTexture(W.type,null),W.type=void 0,W.texture=void 0)}function zt(){try{t.compressedTexImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function F(){try{t.compressedTexImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function M(){try{t.texSubImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function ee(){try{t.texSubImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function se(){try{t.compressedTexSubImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function he(){try{t.compressedTexSubImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function Le(){try{t.texStorage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function ze(){try{t.texStorage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function ge(){try{t.texImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function z(){try{t.texImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function j(W){return p[W]!==void 0?p[W]:t.getParameter(W)}function ce(W,_e){p[W]!==_e&&(t.pixelStorei(W,_e),p[W]=_e)}function I(W){ot.equals(W)===!1&&(t.scissor(W.x,W.y,W.z,W.w),ot.copy(W))}function U(W){Qe.equals(W)===!1&&(t.viewport(W.x,W.y,W.z,W.w),Qe.copy(W))}function Y(W,_e){let fe=c.get(_e);fe===void 0&&(fe=new WeakMap,c.set(_e,fe));let Me=fe.get(W);Me===void 0&&(Me=t.getUniformBlockIndex(_e,W.name),fe.set(W,Me))}function pe(W,_e){const Me=c.get(_e).get(W);l.get(_e)!==Me&&(t.uniformBlockBinding(_e,Me,W.__bindingPointIndex),l.set(_e,Me))}function Ie(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),s.setReversed(!1),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),t.pixelStorei(t.PACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.BROWSER_DEFAULT_WEBGL),t.pixelStorei(t.PACK_ROW_LENGTH,0),t.pixelStorei(t.PACK_SKIP_PIXELS,0),t.pixelStorei(t.PACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_ROW_LENGTH,0),t.pixelStorei(t.UNPACK_IMAGE_HEIGHT,0),t.pixelStorei(t.UNPACK_SKIP_PIXELS,0),t.pixelStorei(t.UNPACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_SKIP_IMAGES,0),d={},p={},ae=null,q={},h={},u=new WeakMap,f=[],v=null,g=!1,m=null,b=null,k=null,y=null,w=null,A=null,_=null,S=new $t(0,0,0),T=0,E=!1,P=null,R=null,B=null,D=null,$=null,ot.set(0,0,t.canvas.width,t.canvas.height),Qe.set(0,0,t.canvas.width,t.canvas.height),o.reset(),s.reset(),r.reset()}return{buffers:{color:o,depth:s,stencil:r},enable:Z,disable:Ne,bindFramebuffer:Xe,drawBuffers:De,useProgram:be,setBlending:vt,setMaterial:Rt,setFlipSided:mt,setCullFace:Gt,setLineWidth:rn,setPolygonOffset:ln,setScissorTest:Ut,activeTexture:Jt,bindTexture:K,unbindTexture:cn,compressedTexImage2D:zt,compressedTexImage3D:F,texImage2D:ge,texImage3D:z,pixelStorei:ce,getParameter:j,updateUBOMapping:Y,uniformBlockBinding:pe,texStorage2D:Le,texStorage3D:ze,texSubImage2D:M,texSubImage3D:ee,compressedTexSubImage2D:se,compressedTexSubImage3D:he,scissor:I,viewport:U,reset:Ie}}function CG(t,e,n,a,i,o,s){const r=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ut,d=new WeakMap,p=new Set;let h;const u=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(F,M){return f?new OffscreenCanvas(F,M):kg("canvas")}function g(F,M,ee){let se=1;const he=zt(F);if((he.width>ee||he.height>ee)&&(se=ee/Math.max(he.width,he.height)),se<1)if(typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&F instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&F instanceof ImageBitmap||typeof VideoFrame<"u"&&F instanceof VideoFrame){const Le=Math.floor(se*he.width),ze=Math.floor(se*he.height);h===void 0&&(h=v(Le,ze));const ge=M?v(Le,ze):h;return ge.width=Le,ge.height=ze,ge.getContext("2d").drawImage(F,0,0,Le,ze),it("WebGLRenderer: Texture has been resized from ("+he.width+"x"+he.height+") to ("+Le+"x"+ze+")."),ge}else return"data"in F&&it("WebGLRenderer: Image in DataTexture is too big ("+he.width+"x"+he.height+")."),F;return F}function m(F){return F.generateMipmaps}function b(F){t.generateMipmap(F)}function k(F){return F.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:F.isWebGL3DRenderTarget?t.TEXTURE_3D:F.isWebGLArrayRenderTarget||F.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function y(F,M,ee,se,he,Le=!1){if(F!==null){if(t[F]!==void 0)return t[F];it("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+F+"'")}let ze;se&&(ze=e.get("EXT_texture_norm16"),ze||it("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let ge=M;if(M===t.RED&&(ee===t.FLOAT&&(ge=t.R32F),ee===t.HALF_FLOAT&&(ge=t.R16F),ee===t.UNSIGNED_BYTE&&(ge=t.R8),ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.R16_EXT),ee===t.SHORT&&ze&&(ge=ze.R16_SNORM_EXT)),M===t.RED_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.R8UI),ee===t.UNSIGNED_SHORT&&(ge=t.R16UI),ee===t.UNSIGNED_INT&&(ge=t.R32UI),ee===t.BYTE&&(ge=t.R8I),ee===t.SHORT&&(ge=t.R16I),ee===t.INT&&(ge=t.R32I)),M===t.RG&&(ee===t.FLOAT&&(ge=t.RG32F),ee===t.HALF_FLOAT&&(ge=t.RG16F),ee===t.UNSIGNED_BYTE&&(ge=t.RG8),ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.RG16_EXT),ee===t.SHORT&&ze&&(ge=ze.RG16_SNORM_EXT)),M===t.RG_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.RG8UI),ee===t.UNSIGNED_SHORT&&(ge=t.RG16UI),ee===t.UNSIGNED_INT&&(ge=t.RG32UI),ee===t.BYTE&&(ge=t.RG8I),ee===t.SHORT&&(ge=t.RG16I),ee===t.INT&&(ge=t.RG32I)),M===t.RGB_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.RGB8UI),ee===t.UNSIGNED_SHORT&&(ge=t.RGB16UI),ee===t.UNSIGNED_INT&&(ge=t.RGB32UI),ee===t.BYTE&&(ge=t.RGB8I),ee===t.SHORT&&(ge=t.RGB16I),ee===t.INT&&(ge=t.RGB32I)),M===t.RGBA_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.RGBA8UI),ee===t.UNSIGNED_SHORT&&(ge=t.RGBA16UI),ee===t.UNSIGNED_INT&&(ge=t.RGBA32UI),ee===t.BYTE&&(ge=t.RGBA8I),ee===t.SHORT&&(ge=t.RGBA16I),ee===t.INT&&(ge=t.RGBA32I)),M===t.RGB&&(ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.RGB16_EXT),ee===t.SHORT&&ze&&(ge=ze.RGB16_SNORM_EXT),ee===t.UNSIGNED_INT_5_9_9_9_REV&&(ge=t.RGB9_E5),ee===t.UNSIGNED_INT_10F_11F_11F_REV&&(ge=t.R11F_G11F_B10F)),M===t.RGBA){const z=Le?yg:Ct.getTransfer(he);ee===t.FLOAT&&(ge=t.RGBA32F),ee===t.HALF_FLOAT&&(ge=t.RGBA16F),ee===t.UNSIGNED_BYTE&&(ge=z===Ht?t.SRGB8_ALPHA8:t.RGBA8),ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.RGBA16_EXT),ee===t.SHORT&&ze&&(ge=ze.RGBA16_SNORM_EXT),ee===t.UNSIGNED_SHORT_4_4_4_4&&(ge=t.RGBA4),ee===t.UNSIGNED_SHORT_5_5_5_1&&(ge=t.RGB5_A1)}return(ge===t.R16F||ge===t.R32F||ge===t.RG16F||ge===t.RG32F||ge===t.RGBA16F||ge===t.RGBA32F)&&e.get("EXT_color_buffer_float"),ge}function w(F,M){let ee;return F?M===null||M===fo||M===Dh?ee=t.DEPTH24_STENCIL8:M===mo?ee=t.DEPTH32F_STENCIL8:M===zh&&(ee=t.DEPTH24_STENCIL8,it("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):M===null||M===fo||M===Dh?ee=t.DEPTH_COMPONENT24:M===mo?ee=t.DEPTH_COMPONENT32F:M===zh&&(ee=t.DEPTH_COMPONENT16),ee}function A(F,M){return m(F)===!0||F.isFramebufferTexture&&F.minFilter!==Vn&&F.minFilter!==Qn?Math.log2(Math.max(M.width,M.height))+1:F.mipmaps!==void 0&&F.mipmaps.length>0?F.mipmaps.length:F.isCompressedTexture&&Array.isArray(F.image)?M.mipmaps.length:1}function _(F){const M=F.target;M.removeEventListener("dispose",_),T(M),M.isVideoTexture&&d.delete(M),M.isHTMLTexture&&p.delete(M)}function S(F){const M=F.target;M.removeEventListener("dispose",S),P(M)}function T(F){const M=a.get(F);if(M.__webglInit===void 0)return;const ee=F.source,se=u.get(ee);if(se){const he=se[M.__cacheKey];he.usedTimes--,he.usedTimes===0&&E(F),Object.keys(se).length===0&&u.delete(ee)}a.remove(F)}function E(F){const M=a.get(F);t.deleteTexture(M.__webglTexture);const ee=F.source,se=u.get(ee);delete se[M.__cacheKey],s.memory.textures--}function P(F){const M=a.get(F);if(F.depthTexture&&(F.depthTexture.dispose(),a.remove(F.depthTexture)),F.isWebGLCubeRenderTarget)for(let se=0;se<6;se++){if(Array.isArray(M.__webglFramebuffer[se]))for(let he=0;he<M.__webglFramebuffer[se].length;he++)t.deleteFramebuffer(M.__webglFramebuffer[se][he]);else t.deleteFramebuffer(M.__webglFramebuffer[se]);M.__webglDepthbuffer&&t.deleteRenderbuffer(M.__webglDepthbuffer[se])}else{if(Array.isArray(M.__webglFramebuffer))for(let se=0;se<M.__webglFramebuffer.length;se++)t.deleteFramebuffer(M.__webglFramebuffer[se]);else t.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer&&t.deleteRenderbuffer(M.__webglDepthbuffer),M.__webglMultisampledFramebuffer&&t.deleteFramebuffer(M.__webglMultisampledFramebuffer),M.__webglColorRenderbuffer)for(let se=0;se<M.__webglColorRenderbuffer.length;se++)M.__webglColorRenderbuffer[se]&&t.deleteRenderbuffer(M.__webglColorRenderbuffer[se]);M.__webglDepthRenderbuffer&&t.deleteRenderbuffer(M.__webglDepthRenderbuffer)}const ee=F.textures;for(let se=0,he=ee.length;se<he;se++){const Le=a.get(ee[se]);Le.__webglTexture&&(t.deleteTexture(Le.__webglTexture),s.memory.textures--),a.remove(ee[se])}a.remove(F)}let R=0;function B(){R=0}function D(){return R}function $(F){R=F}function G(){const F=R;return F>=i.maxTextures&&it("WebGLTextures: Trying to use "+(F+1)+" texture units while this GPU supports only "+i.maxTextures),R+=1,F}function O(F){const M=[];return M.push(F.wrapS),M.push(F.wrapT),M.push(F.wrapR||0),M.push(F.magFilter),M.push(F.minFilter),M.push(F.anisotropy),M.push(F.internalFormat),M.push(F.format),M.push(F.type),M.push(F.generateMipmaps),M.push(F.premultiplyAlpha),M.push(F.flipY),M.push(F.unpackAlignment),M.push(F.colorSpace),M.join()}function J(F,M){const ee=a.get(F);if(F.isVideoTexture&&K(F),F.isRenderTargetTexture===!1&&F.isExternalTexture!==!0&&F.version>0&&ee.__version!==F.version){const se=F.image;if(se===null)it("WebGLRenderer: Texture marked for update but no image data found.");else if(se.complete===!1)it("WebGLRenderer: Texture marked for update but image is incomplete");else{Ne(ee,F,M);return}}else F.isExternalTexture&&(ee.__webglTexture=F.sourceTexture?F.sourceTexture:null);n.bindTexture(t.TEXTURE_2D,ee.__webglTexture,t.TEXTURE0+M)}function ne(F,M){const ee=a.get(F);if(F.isRenderTargetTexture===!1&&F.version>0&&ee.__version!==F.version){Ne(ee,F,M);return}else F.isExternalTexture&&(ee.__webglTexture=F.sourceTexture?F.sourceTexture:null);n.bindTexture(t.TEXTURE_2D_ARRAY,ee.__webglTexture,t.TEXTURE0+M)}function ae(F,M){const ee=a.get(F);if(F.isRenderTargetTexture===!1&&F.version>0&&ee.__version!==F.version){Ne(ee,F,M);return}n.bindTexture(t.TEXTURE_3D,ee.__webglTexture,t.TEXTURE0+M)}function q(F,M){const ee=a.get(F);if(F.isCubeDepthTexture!==!0&&F.version>0&&ee.__version!==F.version){Xe(ee,F,M);return}n.bindTexture(t.TEXTURE_CUBE_MAP,ee.__webglTexture,t.TEXTURE0+M)}const we={[Pw]:t.REPEAT,[as]:t.CLAMP_TO_EDGE,[Iw]:t.MIRRORED_REPEAT},Re={[Vn]:t.NEAREST,[kH]:t.NEAREST_MIPMAP_NEAREST,[hg]:t.NEAREST_MIPMAP_LINEAR,[Qn]:t.LINEAR,[Nw]:t.LINEAR_MIPMAP_NEAREST,[il]:t.LINEAR_MIPMAP_LINEAR},ot={[TH]:t.NEVER,[RH]:t.ALWAYS,[EH]:t.LESS,[x1]:t.LEQUAL,[_H]:t.EQUAL,[b1]:t.GEQUAL,[CH]:t.GREATER,[LH]:t.NOTEQUAL};function Qe(F,M){if(M.type===mo&&e.has("OES_texture_float_linear")===!1&&(M.magFilter===Qn||M.magFilter===Nw||M.magFilter===hg||M.magFilter===il||M.minFilter===Qn||M.minFilter===Nw||M.minFilter===hg||M.minFilter===il)&&it("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(F,t.TEXTURE_WRAP_S,we[M.wrapS]),t.texParameteri(F,t.TEXTURE_WRAP_T,we[M.wrapT]),(F===t.TEXTURE_3D||F===t.TEXTURE_2D_ARRAY)&&t.texParameteri(F,t.TEXTURE_WRAP_R,we[M.wrapR]),t.texParameteri(F,t.TEXTURE_MAG_FILTER,Re[M.magFilter]),t.texParameteri(F,t.TEXTURE_MIN_FILTER,Re[M.minFilter]),M.compareFunction&&(t.texParameteri(F,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(F,t.TEXTURE_COMPARE_FUNC,ot[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===Vn||M.minFilter!==hg&&M.minFilter!==il||M.type===mo&&e.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||a.get(M).__currentAnisotropy){const ee=e.get("EXT_texture_filter_anisotropic");t.texParameterf(F,ee.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,i.getMaxAnisotropy())),a.get(M).__currentAnisotropy=M.anisotropy}}}function st(F,M){let ee=!1;F.__webglInit===void 0&&(F.__webglInit=!0,M.addEventListener("dispose",_));const se=M.source;let he=u.get(se);he===void 0&&(he={},u.set(se,he));const Le=O(M);if(Le!==F.__cacheKey){he[Le]===void 0&&(he[Le]={texture:t.createTexture(),usedTimes:0},s.memory.textures++,ee=!0),he[Le].usedTimes++;const ze=he[F.__cacheKey];ze!==void 0&&(he[F.__cacheKey].usedTimes--,ze.usedTimes===0&&E(M)),F.__cacheKey=Le,F.__webglTexture=he[Le].texture}return ee}function de(F,M,ee){return Math.floor(Math.floor(F/ee)/M)}function Z(F,M,ee,se){const Le=F.updateRanges;if(Le.length===0)n.texSubImage2D(t.TEXTURE_2D,0,0,0,M.width,M.height,ee,se,M.data);else{Le.sort((ce,I)=>ce.start-I.start);let ze=0;for(let ce=1;ce<Le.length;ce++){const I=Le[ze],U=Le[ce],Y=I.start+I.count,pe=de(U.start,M.width,4),Ie=de(I.start,M.width,4);U.start<=Y+1&&pe===Ie&&de(U.start+U.count-1,M.width,4)===pe?I.count=Math.max(I.count,U.start+U.count-I.start):(++ze,Le[ze]=U)}Le.length=ze+1;const ge=n.getParameter(t.UNPACK_ROW_LENGTH),z=n.getParameter(t.UNPACK_SKIP_PIXELS),j=n.getParameter(t.UNPACK_SKIP_ROWS);n.pixelStorei(t.UNPACK_ROW_LENGTH,M.width);for(let ce=0,I=Le.length;ce<I;ce++){const U=Le[ce],Y=Math.floor(U.start/4),pe=Math.ceil(U.count/4),Ie=Y%M.width,W=Math.floor(Y/M.width),_e=pe,fe=1;n.pixelStorei(t.UNPACK_SKIP_PIXELS,Ie),n.pixelStorei(t.UNPACK_SKIP_ROWS,W),n.texSubImage2D(t.TEXTURE_2D,0,Ie,W,_e,fe,ee,se,M.data)}F.clearUpdateRanges(),n.pixelStorei(t.UNPACK_ROW_LENGTH,ge),n.pixelStorei(t.UNPACK_SKIP_PIXELS,z),n.pixelStorei(t.UNPACK_SKIP_ROWS,j)}}function Ne(F,M,ee){let se=t.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(se=t.TEXTURE_2D_ARRAY),M.isData3DTexture&&(se=t.TEXTURE_3D);const he=st(F,M),Le=M.source;n.bindTexture(se,F.__webglTexture,t.TEXTURE0+ee);const ze=a.get(Le);if(Le.version!==ze.__version||he===!0){if(n.activeTexture(t.TEXTURE0+ee),(typeof ImageBitmap<"u"&&M.image instanceof ImageBitmap)===!1){const fe=Ct.getPrimaries(Ct.workingColorSpace),Me=M.colorSpace===Vs?null:Ct.getPrimaries(M.colorSpace),Pe=M.colorSpace===Vs||fe===Me?t.NONE:t.BROWSER_DEFAULT_WEBGL;n.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Pe)}n.pixelStorei(t.UNPACK_ALIGNMENT,M.unpackAlignment);let z=g(M.image,!1,i.maxTextureSize);z=cn(M,z);const j=o.convert(M.format,M.colorSpace),ce=o.convert(M.type);let I=y(M.internalFormat,j,ce,M.normalized,M.colorSpace,M.isVideoTexture);Qe(se,M);let U;const Y=M.mipmaps,pe=M.isVideoTexture!==!0,Ie=ze.__version===void 0||he===!0,W=Le.dataReady,_e=A(M,z);if(M.isDepthTexture)I=w(M.format===ol,M.type),Ie&&(pe?n.texStorage2D(t.TEXTURE_2D,1,I,z.width,z.height):n.texImage2D(t.TEXTURE_2D,0,I,z.width,z.height,0,j,ce,null));else if(M.isDataTexture)if(Y.length>0){pe&&Ie&&n.texStorage2D(t.TEXTURE_2D,_e,I,Y[0].width,Y[0].height);for(let fe=0,Me=Y.length;fe<Me;fe++)U=Y[fe],pe?W&&n.texSubImage2D(t.TEXTURE_2D,fe,0,0,U.width,U.height,j,ce,U.data):n.texImage2D(t.TEXTURE_2D,fe,I,U.width,U.height,0,j,ce,U.data);M.generateMipmaps=!1}else pe?(Ie&&n.texStorage2D(t.TEXTURE_2D,_e,I,z.width,z.height),W&&Z(M,z,j,ce)):n.texImage2D(t.TEXTURE_2D,0,I,z.width,z.height,0,j,ce,z.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){pe&&Ie&&n.texStorage3D(t.TEXTURE_2D_ARRAY,_e,I,Y[0].width,Y[0].height,z.depth);for(let fe=0,Me=Y.length;fe<Me;fe++)if(U=Y[fe],M.format!==Si)if(j!==null)if(pe){if(W)if(M.layerUpdates.size>0){const Pe=L_(U.width,U.height,M.format,M.type);for(const ke of M.layerUpdates){const Ce=U.data.subarray(ke*Pe/U.data.BYTES_PER_ELEMENT,(ke+1)*Pe/U.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,ke,U.width,U.height,1,j,Ce)}}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,0,U.width,U.height,z.depth,j,U.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,fe,I,U.width,U.height,z.depth,0,U.data,0,0);else it("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else pe?W&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,0,U.width,U.height,z.depth,j,ce,U.data):n.texImage3D(t.TEXTURE_2D_ARRAY,fe,I,U.width,U.height,z.depth,0,j,ce,U.data);M.layerUpdates.size>0&&M.clearLayerUpdates()}else{pe&&Ie&&n.texStorage2D(t.TEXTURE_2D,_e,I,Y[0].width,Y[0].height);for(let fe=0,Me=Y.length;fe<Me;fe++)U=Y[fe],M.format!==Si?j!==null?pe?W&&n.compressedTexSubImage2D(t.TEXTURE_2D,fe,0,0,U.width,U.height,j,U.data):n.compressedTexImage2D(t.TEXTURE_2D,fe,I,U.width,U.height,0,U.data):it("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):pe?W&&n.texSubImage2D(t.TEXTURE_2D,fe,0,0,U.width,U.height,j,ce,U.data):n.texImage2D(t.TEXTURE_2D,fe,I,U.width,U.height,0,j,ce,U.data)}else if(M.isDataArrayTexture)if(pe){if(Ie&&n.texStorage3D(t.TEXTURE_2D_ARRAY,_e,I,z.width,z.height,z.depth),W)if(M.layerUpdates.size>0){const fe=L_(z.width,z.height,M.format,M.type);for(const Me of M.layerUpdates){const Pe=z.data.subarray(Me*fe/z.data.BYTES_PER_ELEMENT,(Me+1)*fe/z.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,Me,z.width,z.height,1,j,ce,Pe)}M.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,z.width,z.height,z.depth,j,ce,z.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,I,z.width,z.height,z.depth,0,j,ce,z.data);else if(M.isData3DTexture)pe?(Ie&&n.texStorage3D(t.TEXTURE_3D,_e,I,z.width,z.height,z.depth),W&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,z.width,z.height,z.depth,j,ce,z.data)):n.texImage3D(t.TEXTURE_3D,0,I,z.width,z.height,z.depth,0,j,ce,z.data);else if(M.isFramebufferTexture){if(Ie)if(pe)n.texStorage2D(t.TEXTURE_2D,_e,I,z.width,z.height);else{let fe=z.width,Me=z.height;for(let Pe=0;Pe<_e;Pe++)n.texImage2D(t.TEXTURE_2D,Pe,I,fe,Me,0,j,ce,null),fe>>=1,Me>>=1}}else if(M.isHTMLTexture){if("texElementImage2D"in t){const fe=t.canvas;if(fe.hasAttribute("layoutsubtree")||fe.setAttribute("layoutsubtree","true"),z.parentNode!==fe){fe.appendChild(z),p.add(M),fe.onpaint=Me=>{const Pe=Me.changedElements;for(const ke of p)Pe.includes(ke.image)&&(ke.needsUpdate=!0)},fe.requestPaint();return}if(t.texElementImage2D.length===3)t.texElementImage2D(t.TEXTURE_2D,t.RGBA8,z);else{const Pe=t.RGBA,ke=t.RGBA,Ce=t.UNSIGNED_BYTE;t.texElementImage2D(t.TEXTURE_2D,0,Pe,ke,Ce,z)}t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}}else if(Y.length>0){if(pe&&Ie){const fe=zt(Y[0]);n.texStorage2D(t.TEXTURE_2D,_e,I,fe.width,fe.height)}for(let fe=0,Me=Y.length;fe<Me;fe++)U=Y[fe],pe?W&&n.texSubImage2D(t.TEXTURE_2D,fe,0,0,j,ce,U):n.texImage2D(t.TEXTURE_2D,fe,I,j,ce,U);M.generateMipmaps=!1}else if(pe){if(Ie){const fe=zt(z);n.texStorage2D(t.TEXTURE_2D,_e,I,fe.width,fe.height)}W&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,j,ce,z)}else n.texImage2D(t.TEXTURE_2D,0,I,j,ce,z);m(M)&&b(se),ze.__version=Le.version,M.onUpdate&&M.onUpdate(M)}F.__version=M.version}function Xe(F,M,ee){if(M.image.length!==6)return;const se=st(F,M),he=M.source;n.bindTexture(t.TEXTURE_CUBE_MAP,F.__webglTexture,t.TEXTURE0+ee);const Le=a.get(he);if(he.version!==Le.__version||se===!0){n.activeTexture(t.TEXTURE0+ee);const ze=Ct.getPrimaries(Ct.workingColorSpace),ge=M.colorSpace===Vs?null:Ct.getPrimaries(M.colorSpace),z=M.colorSpace===Vs||ze===ge?t.NONE:t.BROWSER_DEFAULT_WEBGL;n.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(t.UNPACK_ALIGNMENT,M.unpackAlignment),n.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,z);const j=M.isCompressedTexture||M.image[0].isCompressedTexture,ce=M.image[0]&&M.image[0].isDataTexture,I=[];for(let ke=0;ke<6;ke++)!j&&!ce?I[ke]=g(M.image[ke],!0,i.maxCubemapSize):I[ke]=ce?M.image[ke].image:M.image[ke],I[ke]=cn(M,I[ke]);const U=I[0],Y=o.convert(M.format,M.colorSpace),pe=o.convert(M.type),Ie=y(M.internalFormat,Y,pe,M.normalized,M.colorSpace),W=M.isVideoTexture!==!0,_e=Le.__version===void 0||se===!0,fe=he.dataReady;let Me=A(M,U);Qe(t.TEXTURE_CUBE_MAP,M);let Pe;if(j){W&&_e&&n.texStorage2D(t.TEXTURE_CUBE_MAP,Me,Ie,U.width,U.height);for(let ke=0;ke<6;ke++){Pe=I[ke].mipmaps;for(let Ce=0;Ce<Pe.length;Ce++){const Ee=Pe[Ce];M.format!==Si?Y!==null?W?fe&&n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,0,0,Ee.width,Ee.height,Y,Ee.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,Ie,Ee.width,Ee.height,0,Ee.data):it("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,0,0,Ee.width,Ee.height,Y,pe,Ee.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,Ie,Ee.width,Ee.height,0,Y,pe,Ee.data)}}}else{if(Pe=M.mipmaps,W&&_e){Pe.length>0&&Me++;const ke=zt(I[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,Me,Ie,ke.width,ke.height)}for(let ke=0;ke<6;ke++)if(ce){W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,I[ke].width,I[ke].height,Y,pe,I[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ie,I[ke].width,I[ke].height,0,Y,pe,I[ke].data);for(let Ce=0;Ce<Pe.length;Ce++){const at=Pe[Ce].image[ke].image;W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,0,0,at.width,at.height,Y,pe,at.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,Ie,at.width,at.height,0,Y,pe,at.data)}}else{W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,Y,pe,I[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ie,Y,pe,I[ke]);for(let Ce=0;Ce<Pe.length;Ce++){const Ee=Pe[Ce];W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,0,0,Y,pe,Ee.image[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,Ie,Y,pe,Ee.image[ke])}}}m(M)&&b(t.TEXTURE_CUBE_MAP),Le.__version=he.version,M.onUpdate&&M.onUpdate(M)}F.__version=M.version}function De(F,M,ee,se,he,Le){const ze=o.convert(ee.format,ee.colorSpace),ge=o.convert(ee.type),z=y(ee.internalFormat,ze,ge,ee.normalized,ee.colorSpace),j=a.get(M),ce=a.get(ee);if(ce.__renderTarget=M,!j.__hasExternalTextures){const I=Math.max(1,M.width>>Le),U=Math.max(1,M.height>>Le);he===t.TEXTURE_3D||he===t.TEXTURE_2D_ARRAY?n.texImage3D(he,Le,z,I,U,M.depth,0,ze,ge,null):n.texImage2D(he,Le,z,I,U,0,ze,ge,null)}n.bindFramebuffer(t.FRAMEBUFFER,F),Jt(M)?r.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,se,he,ce.__webglTexture,0,Ut(M)):(he===t.TEXTURE_2D||he>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&he<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,se,he,ce.__webglTexture,Le),n.bindFramebuffer(t.FRAMEBUFFER,null)}function be(F,M,ee){if(t.bindRenderbuffer(t.RENDERBUFFER,F),M.depthBuffer){const se=M.depthTexture,he=se&&se.isDepthTexture?se.type:null,Le=w(M.stencilBuffer,he),ze=M.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;Jt(M)?r.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Ut(M),Le,M.width,M.height):ee?t.renderbufferStorageMultisample(t.RENDERBUFFER,Ut(M),Le,M.width,M.height):t.renderbufferStorage(t.RENDERBUFFER,Le,M.width,M.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,ze,t.RENDERBUFFER,F)}else{const se=M.textures;for(let he=0;he<se.length;he++){const Le=se[he],ze=o.convert(Le.format,Le.colorSpace),ge=o.convert(Le.type),z=y(Le.internalFormat,ze,ge,Le.normalized,Le.colorSpace);Jt(M)?r.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Ut(M),z,M.width,M.height):ee?t.renderbufferStorageMultisample(t.RENDERBUFFER,Ut(M),z,M.width,M.height):t.renderbufferStorage(t.RENDERBUFFER,z,M.width,M.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function ft(F,M,ee){const se=M.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(t.FRAMEBUFFER,F),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const he=a.get(M.depthTexture);if(he.__renderTarget=M,(!he.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),se){if(he.__webglInit===void 0&&(he.__webglInit=!0,M.depthTexture.addEventListener("dispose",_)),he.__webglTexture===void 0){he.__webglTexture=t.createTexture(),n.bindTexture(t.TEXTURE_CUBE_MAP,he.__webglTexture),Qe(t.TEXTURE_CUBE_MAP,M.depthTexture);const j=o.convert(M.depthTexture.format),ce=o.convert(M.depthTexture.type);let I;M.depthTexture.format===is?I=t.DEPTH_COMPONENT24:M.depthTexture.format===ol&&(I=t.DEPTH24_STENCIL8);for(let U=0;U<6;U++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+U,0,I,M.width,M.height,0,j,ce,null)}}else J(M.depthTexture,0);const Le=he.__webglTexture,ze=Ut(M),ge=se?t.TEXTURE_CUBE_MAP_POSITIVE_X+ee:t.TEXTURE_2D,z=M.depthTexture.format===ol?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(M.depthTexture.format===is)Jt(M)?r.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,z,ge,Le,0,ze):t.framebufferTexture2D(t.FRAMEBUFFER,z,ge,Le,0);else if(M.depthTexture.format===ol)Jt(M)?r.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,z,ge,Le,0,ze):t.framebufferTexture2D(t.FRAMEBUFFER,z,ge,Le,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function rt(F){const M=a.get(F),ee=F.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==F.depthTexture){const se=F.depthTexture;if(M.__depthDisposeCallback&&M.__depthDisposeCallback(),se){const he=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,se.removeEventListener("dispose",he)};se.addEventListener("dispose",he),M.__depthDisposeCallback=he}M.__boundDepthTexture=se}if(F.depthTexture&&!M.__autoAllocateDepthBuffer)if(ee)for(let se=0;se<6;se++)ft(M.__webglFramebuffer[se],F,se);else{const se=F.texture.mipmaps;se&&se.length>0?ft(M.__webglFramebuffer[0],F,0):ft(M.__webglFramebuffer,F,0)}else if(ee){M.__webglDepthbuffer=[];for(let se=0;se<6;se++)if(n.bindFramebuffer(t.FRAMEBUFFER,M.__webglFramebuffer[se]),M.__webglDepthbuffer[se]===void 0)M.__webglDepthbuffer[se]=t.createRenderbuffer(),be(M.__webglDepthbuffer[se],F,!1);else{const he=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Le=M.__webglDepthbuffer[se];t.bindRenderbuffer(t.RENDERBUFFER,Le),t.framebufferRenderbuffer(t.FRAMEBUFFER,he,t.RENDERBUFFER,Le)}}else{const se=F.texture.mipmaps;if(se&&se.length>0?n.bindFramebuffer(t.FRAMEBUFFER,M.__webglFramebuffer[0]):n.bindFramebuffer(t.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=t.createRenderbuffer(),be(M.__webglDepthbuffer,F,!1);else{const he=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Le=M.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,Le),t.framebufferRenderbuffer(t.FRAMEBUFFER,he,t.RENDERBUFFER,Le)}}n.bindFramebuffer(t.FRAMEBUFFER,null)}function vt(F,M,ee){const se=a.get(F);M!==void 0&&De(se.__webglFramebuffer,F,F.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),ee!==void 0&&rt(F)}function Rt(F){const M=F.texture,ee=a.get(F),se=a.get(M);F.addEventListener("dispose",S);const he=F.textures,Le=F.isWebGLCubeRenderTarget===!0,ze=he.length>1;if(ze||(se.__webglTexture===void 0&&(se.__webglTexture=t.createTexture()),se.__version=M.version,s.memory.textures++),Le){ee.__webglFramebuffer=[];for(let ge=0;ge<6;ge++)if(M.mipmaps&&M.mipmaps.length>0){ee.__webglFramebuffer[ge]=[];for(let z=0;z<M.mipmaps.length;z++)ee.__webglFramebuffer[ge][z]=t.createFramebuffer()}else ee.__webglFramebuffer[ge]=t.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){ee.__webglFramebuffer=[];for(let ge=0;ge<M.mipmaps.length;ge++)ee.__webglFramebuffer[ge]=t.createFramebuffer()}else ee.__webglFramebuffer=t.createFramebuffer();if(ze)for(let ge=0,z=he.length;ge<z;ge++){const j=a.get(he[ge]);j.__webglTexture===void 0&&(j.__webglTexture=t.createTexture(),s.memory.textures++)}if(F.samples>0&&Jt(F)===!1){ee.__webglMultisampledFramebuffer=t.createFramebuffer(),ee.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,ee.__webglMultisampledFramebuffer);for(let ge=0;ge<he.length;ge++){const z=he[ge];ee.__webglColorRenderbuffer[ge]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,ee.__webglColorRenderbuffer[ge]);const j=o.convert(z.format,z.colorSpace),ce=o.convert(z.type),I=y(z.internalFormat,j,ce,z.normalized,z.colorSpace,F.isXRRenderTarget===!0),U=Ut(F);t.renderbufferStorageMultisample(t.RENDERBUFFER,U,I,F.width,F.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+ge,t.RENDERBUFFER,ee.__webglColorRenderbuffer[ge])}t.bindRenderbuffer(t.RENDERBUFFER,null),F.depthBuffer&&(ee.__webglDepthRenderbuffer=t.createRenderbuffer(),be(ee.__webglDepthRenderbuffer,F,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(Le){n.bindTexture(t.TEXTURE_CUBE_MAP,se.__webglTexture),Qe(t.TEXTURE_CUBE_MAP,M);for(let ge=0;ge<6;ge++)if(M.mipmaps&&M.mipmaps.length>0)for(let z=0;z<M.mipmaps.length;z++)De(ee.__webglFramebuffer[ge][z],F,M,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,z);else De(ee.__webglFramebuffer[ge],F,M,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0);m(M)&&b(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(ze){for(let ge=0,z=he.length;ge<z;ge++){const j=he[ge],ce=a.get(j);let I=t.TEXTURE_2D;(F.isWebGL3DRenderTarget||F.isWebGLArrayRenderTarget)&&(I=F.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(I,ce.__webglTexture),Qe(I,j),De(ee.__webglFramebuffer,F,j,t.COLOR_ATTACHMENT0+ge,I,0),m(j)&&b(I)}n.unbindTexture()}else{let ge=t.TEXTURE_2D;if((F.isWebGL3DRenderTarget||F.isWebGLArrayRenderTarget)&&(ge=F.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(ge,se.__webglTexture),Qe(ge,M),M.mipmaps&&M.mipmaps.length>0)for(let z=0;z<M.mipmaps.length;z++)De(ee.__webglFramebuffer[z],F,M,t.COLOR_ATTACHMENT0,ge,z);else De(ee.__webglFramebuffer,F,M,t.COLOR_ATTACHMENT0,ge,0);m(M)&&b(ge),n.unbindTexture()}F.depthBuffer&&rt(F)}function mt(F){const M=F.textures;for(let ee=0,se=M.length;ee<se;ee++){const he=M[ee];if(m(he)){const Le=k(F),ze=a.get(he).__webglTexture;n.bindTexture(Le,ze),b(Le),n.unbindTexture()}}}const Gt=[],rn=[];function ln(F){if(F.samples>0){if(Jt(F)===!1){const M=F.textures,ee=F.width,se=F.height;let he=t.COLOR_BUFFER_BIT;const Le=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ze=a.get(F),ge=M.length>1;if(ge)for(let j=0;j<M.length;j++)n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,ze.__webglMultisampledFramebuffer);const z=F.texture.mipmaps;z&&z.length>0?n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ze.__webglFramebuffer[0]):n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ze.__webglFramebuffer);for(let j=0;j<M.length;j++){if(F.resolveDepthBuffer&&(F.depthBuffer&&(he|=t.DEPTH_BUFFER_BIT),F.stencilBuffer&&F.resolveStencilBuffer&&(he|=t.STENCIL_BUFFER_BIT)),ge){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,ze.__webglColorRenderbuffer[j]);const ce=a.get(M[j]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,ce,0)}t.blitFramebuffer(0,0,ee,se,0,0,ee,se,he,t.NEAREST),l===!0&&(Gt.length=0,rn.length=0,Gt.push(t.COLOR_ATTACHMENT0+j),F.depthBuffer&&F.storeMultisampledDepthBuffer===!1&&(Gt.push(Le),rn.push(Le),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,rn)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,Gt))}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),ge)for(let j=0;j<M.length;j++){n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.RENDERBUFFER,ze.__webglColorRenderbuffer[j]);const ce=a.get(M[j]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.TEXTURE_2D,ce,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ze.__webglMultisampledFramebuffer)}else if(F.depthBuffer&&F.storeMultisampledDepthBuffer===!1&&l){const M=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[M])}}}function Ut(F){return Math.min(i.maxSamples,F.samples)}function Jt(F){const M=a.get(F);return F.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function K(F){const M=s.render.frame;d.get(F)!==M&&(d.set(F,M),F.update())}function cn(F,M){const ee=F.colorSpace,se=F.format,he=F.type;return F.isCompressedTexture===!0||F.isVideoTexture===!0||ee!==bg&&ee!==Vs&&(Ct.getTransfer(ee)===Ht?(se!==Si||he!==ai)&&it("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ot("WebGLTextures: Unsupported texture color space:",ee)),M}function zt(F){return typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement?(c.width=F.naturalWidth||F.width,c.height=F.naturalHeight||F.height):typeof VideoFrame<"u"&&F instanceof VideoFrame?(c.width=F.displayWidth,c.height=F.displayHeight):(c.width=F.width,c.height=F.height),c}this.allocateTextureUnit=G,this.resetTextureUnits=B,this.getTextureUnits=D,this.setTextureUnits=$,this.setTexture2D=J,this.setTexture2DArray=ne,this.setTexture3D=ae,this.setTextureCube=q,this.rebindTextures=vt,this.setupRenderTarget=Rt,this.updateRenderTargetMipmap=mt,this.updateMultisampleRenderTarget=ln,this.setupDepthRenderbuffer=rt,this.setupFrameBufferTexture=De,this.useMultisampledRTT=Jt,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function LG(t,e){function n(a,i=Vs){let o;const s=Ct.getTransfer(i);if(a===ai)return t.UNSIGNED_BYTE;if(a===Dw)return t.UNSIGNED_SHORT_4_4_4_4;if(a===Ow)return t.UNSIGNED_SHORT_5_5_5_1;if(a===O5)return t.UNSIGNED_INT_5_9_9_9_REV;if(a===$5)return t.UNSIGNED_INT_10F_11F_11F_REV;if(a===z5)return t.BYTE;if(a===D5)return t.SHORT;if(a===zh)return t.UNSIGNED_SHORT;if(a===zw)return t.INT;if(a===fo)return t.UNSIGNED_INT;if(a===mo)return t.FLOAT;if(a===go)return t.HALF_FLOAT;if(a===F5)return t.ALPHA;if(a===U5)return t.RGB;if(a===Si)return t.RGBA;if(a===is)return t.DEPTH_COMPONENT;if(a===ol)return t.DEPTH_STENCIL;if(a===B5)return t.RED;if(a===$w)return t.RED_INTEGER;if(a===sl)return t.RG;if(a===Fw)return t.RG_INTEGER;if(a===Uw)return t.RGBA_INTEGER;if(a===ug||a===fg||a===mg||a===gg)if(s===Ht)if(o=e.get("WEBGL_compressed_texture_s3tc_srgb"),o!==null){if(a===ug)return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(a===fg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(a===mg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(a===gg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(o=e.get("WEBGL_compressed_texture_s3tc"),o!==null){if(a===ug)return o.COMPRESSED_RGB_S3TC_DXT1_EXT;if(a===fg)return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(a===mg)return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(a===gg)return o.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(a===Bw||a===Hw||a===qw||a===Ww)if(o=e.get("WEBGL_compressed_texture_pvrtc"),o!==null){if(a===Bw)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(a===Hw)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(a===qw)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(a===Ww)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(a===Gw||a===Vw||a===jw||a===Yw||a===Xw||a===vg||a===Kw)if(o=e.get("WEBGL_compressed_texture_etc"),o!==null){if(a===Gw||a===Vw)return s===Ht?o.COMPRESSED_SRGB8_ETC2:o.COMPRESSED_RGB8_ETC2;if(a===jw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:o.COMPRESSED_RGBA8_ETC2_EAC;if(a===Yw)return o.COMPRESSED_R11_EAC;if(a===Xw)return o.COMPRESSED_SIGNED_R11_EAC;if(a===vg)return o.COMPRESSED_RG11_EAC;if(a===Kw)return o.COMPRESSED_SIGNED_RG11_EAC}else return null;if(a===Zw||a===Jw||a===Qw||a===e1||a===t1||a===n1||a===a1||a===i1||a===o1||a===s1||a===r1||a===l1||a===c1||a===d1)if(o=e.get("WEBGL_compressed_texture_astc"),o!==null){if(a===Zw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:o.COMPRESSED_RGBA_ASTC_4x4_KHR;if(a===Jw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:o.COMPRESSED_RGBA_ASTC_5x4_KHR;if(a===Qw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:o.COMPRESSED_RGBA_ASTC_5x5_KHR;if(a===e1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:o.COMPRESSED_RGBA_ASTC_6x5_KHR;if(a===t1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:o.COMPRESSED_RGBA_ASTC_6x6_KHR;if(a===n1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:o.COMPRESSED_RGBA_ASTC_8x5_KHR;if(a===a1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:o.COMPRESSED_RGBA_ASTC_8x6_KHR;if(a===i1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:o.COMPRESSED_RGBA_ASTC_8x8_KHR;if(a===o1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:o.COMPRESSED_RGBA_ASTC_10x5_KHR;if(a===s1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:o.COMPRESSED_RGBA_ASTC_10x6_KHR;if(a===r1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:o.COMPRESSED_RGBA_ASTC_10x8_KHR;if(a===l1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:o.COMPRESSED_RGBA_ASTC_10x10_KHR;if(a===c1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:o.COMPRESSED_RGBA_ASTC_12x10_KHR;if(a===d1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:o.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(a===p1||a===h1||a===u1)if(o=e.get("EXT_texture_compression_bptc"),o!==null){if(a===p1)return s===Ht?o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:o.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(a===h1)return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(a===u1)return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(a===f1||a===m1||a===xg||a===g1)if(o=e.get("EXT_texture_compression_rgtc"),o!==null){if(a===f1)return o.COMPRESSED_RED_RGTC1_EXT;if(a===m1)return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(a===xg)return o.COMPRESSED_RED_GREEN_RGTC2_EXT;if(a===g1)return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return a===Dh?t.UNSIGNED_INT_24_8:t[a]!==void 0?t[a]:null}return{convert:n}}const RG=`
|
|
11691
|
+
}`,AG=[new Q(1,0,0),new Q(-1,0,0),new Q(0,1,0),new Q(0,-1,0),new Q(0,0,1),new Q(0,0,-1)],TG=[new Q(0,-1,0),new Q(0,-1,0),new Q(0,0,1),new Q(0,0,-1),new Q(0,-1,0),new Q(0,-1,0)],oC=new fn,Kh=new Q,ek=new Q;function EG(t,e,n){let a=new u_;const i=new ut,o=new ut,s=new yn,r=new xq,l=new bq,c={},d=n.maxTextureSize,p={[nl]:Ea,[Ea]:nl,[es]:es},h=new na({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ut},radius:{value:4}},vertexShader:SG,fragmentShader:MG}),u=h.clone();u.defines.HORIZONTAL_PASS=1;const f=new Ln;f.setAttribute("position",new xo(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new hs(f,h),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=dg;let m=this.type;this.render=function(A,_,S){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||A.length===0)return;this.type===tH&&(it("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=dg);const T=t.getRenderTarget(),E=t.getActiveCubeFace(),P=t.getActiveMipmapLevel(),R=t.state;R.setBlending(ts),R.buffers.depth.getReversed()===!0?R.buffers.color.setClear(0,0,0,0):R.buffers.color.setClear(1,1,1,1),R.buffers.depth.setTest(!0),R.setScissorTest(!1);const B=m!==this.type;B&&_.traverse(function(D){D.material&&(Array.isArray(D.material)?D.material.forEach($=>$.needsUpdate=!0):D.material.needsUpdate=!0)});for(let D=0,$=A.length;D<$;D++){const G=A[D],O=G.shadow;if(O===void 0){it("WebGLShadowMap:",G,"has no shadow.");continue}if(O.autoUpdate===!1&&O.needsUpdate===!1)continue;i.copy(O.mapSize);const J=O.getFrameExtents();i.multiply(J),o.copy(O.mapSize),(i.x>d||i.y>d)&&(i.x>d&&(o.x=Math.floor(d/J.x),i.x=o.x*J.x,O.mapSize.x=o.x),i.y>d&&(o.y=Math.floor(d/J.y),i.y=o.y*J.y,O.mapSize.y=o.y));const ne=t.state.buffers.depth.getReversed();if(O.camera._reversedDepth=ne,O.map===null||B===!0){if(O.map!==null&&(O.map.depthTexture!==null&&(O.map.depthTexture.dispose(),O.map.depthTexture=null),O.map.dispose()),this.type===Ih){if(G.isPointLight){it("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}O.map=new Mi(i.x,i.y,{format:sl,type:go,minFilter:Qn,magFilter:Qn,generateMipmaps:!1}),O.map.texture.name=G.name+".shadowMap",O.map.depthTexture=new Vh(i.x,i.y,mo),O.map.depthTexture.name=G.name+".shadowMapDepth",O.map.depthTexture.format=is,O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Vn,O.map.depthTexture.magFilter=Vn}else G.isPointLight?(O.map=new $_(i.x),O.map.depthTexture=new hq(i.x,fo)):(O.map=new Mi(i.x,i.y),O.map.depthTexture=new Vh(i.x,i.y,fo)),O.map.depthTexture.name=G.name+".shadowMap",O.map.depthTexture.format=is,this.type===dg?(O.map.depthTexture.compareFunction=ne?b1:x1,O.map.depthTexture.minFilter=Qn,O.map.depthTexture.magFilter=Qn):(O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Vn,O.map.depthTexture.magFilter=Vn);O.camera.updateProjectionMatrix()}O.map.isWebGLCubeRenderTarget!==!0&&(O.map.width!==i.x||O.map.height!==i.y)&&O.map.setSize(i.x,i.y);const ae=O.map.isWebGLCubeRenderTarget?6:O.getViewportCount();G.isPointLight!==!0&&O.updateMatrices(G,S);for(let q=0;q<ae;q++){const we=O.getCamera(q);if(G.isPointLight){const Re=O.camera,ot=O.matrix,Qe=G.distance||Re.far;Qe!==Re.far&&(Re.far=Qe,Re.updateProjectionMatrix()),Kh.setFromMatrixPosition(G.matrixWorld),Re.position.copy(Kh),ek.copy(Re.position),ek.add(AG[q]),Re.up.copy(TG[q]),Re.lookAt(ek),Re.updateMatrixWorld(),ot.makeTranslation(-Kh.x,-Kh.y,-Kh.z),oC.multiplyMatrices(Re.projectionMatrix,Re.matrixWorldInverse),O._frustum.setFromProjectionMatrix(oC,Re.coordinateSystem,Re.reversedDepth)}if(O.map.isWebGLCubeRenderTarget)t.setRenderTarget(O.map,q),t.clear();else{q===0&&(t.setRenderTarget(O.map),t.clear());const Re=O.getViewport(q);s.set(o.x*Re.x,o.y*Re.y,o.x*Re.z,o.y*Re.w),R.viewport(s)}a=O.getFrustum(q),y(_,S,we,G,this.type)}O.isPointLightShadow!==!0&&this.type===Ih&&b(O,S),O.needsUpdate=!1}m=this.type,g.needsUpdate=!1,t.setRenderTarget(T,E,P)};function b(A,_){const S=e.update(v);h.defines.VSM_SAMPLES!==A.blurSamples&&(h.defines.VSM_SAMPLES=A.blurSamples,u.defines.VSM_SAMPLES=A.blurSamples,h.needsUpdate=!0,u.needsUpdate=!0),A.mapPass===null?A.mapPass=new Mi(i.x,i.y,{format:sl,type:go}):(A.mapPass.width!==A.map.width||A.mapPass.height!==A.map.height)&&A.mapPass.setSize(A.map.width,A.map.height),h.uniforms.shadow_pass.value=A.map.depthTexture,h.uniforms.resolution.value.set(A.map.width,A.map.height),h.uniforms.radius.value=A.radius,t.setRenderTarget(A.mapPass),t.clear(),t.renderBufferDirect(_,null,S,h,v,null),u.uniforms.shadow_pass.value=A.mapPass.texture,u.uniforms.resolution.value.set(A.map.width,A.map.height),u.uniforms.radius.value=A.radius,t.setRenderTarget(A.map),t.clear(),t.renderBufferDirect(_,null,S,u,v,null)}function k(A,_,S,T){let E=null;const P=S.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(P!==void 0)E=P;else if(E=S.isPointLight===!0?l:r,t.localClippingEnabled&&_.clipShadows===!0&&Array.isArray(_.clippingPlanes)&&_.clippingPlanes.length!==0||_.displacementMap&&_.displacementScale!==0||_.alphaMap&&_.alphaTest>0||_.map&&_.alphaTest>0||_.alphaToCoverage===!0){const R=E.uuid,B=_.uuid;let D=c[R];D===void 0&&(D={},c[R]=D);let $=D[B];$===void 0&&($=E.clone(),D[B]=$,_.addEventListener("dispose",w)),E=$}if(E.visible=_.visible,E.wireframe=_.wireframe,T===Ih?E.side=_.shadowSide!==null?_.shadowSide:_.side:E.side=_.shadowSide!==null?_.shadowSide:p[_.side],E.alphaMap=_.alphaMap,E.alphaTest=_.alphaToCoverage===!0?.5:_.alphaTest,E.map=_.map,E.clipShadows=_.clipShadows,E.clippingPlanes=_.clippingPlanes,E.clipIntersection=_.clipIntersection,E.displacementMap=_.displacementMap,E.displacementScale=_.displacementScale,E.displacementBias=_.displacementBias,E.wireframeLinewidth=_.wireframeLinewidth,E.linewidth=_.linewidth,S.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const R=t.properties.get(E);R.light=S}return E}function y(A,_,S,T,E){if(A.visible===!1)return;if(A.layers.test(_.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&E===Ih)&&(!A.frustumCulled||A.intersectsFrustum(a))){A.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,A.matrixWorld);const B=e.update(A),D=A.material;if(Array.isArray(D)){const $=B.groups;for(let G=0,O=$.length;G<O;G++){const J=$[G],ne=D[J.materialIndex];if(ne&&ne.visible){const ae=k(A,ne,T,E);A.onBeforeShadow(t,A,_,S,B,ae,J),t.renderBufferDirect(S,null,B,ae,A,J),A.onAfterShadow(t,A,_,S,B,ae,J)}}}else if(D.visible){const $=k(A,D,T,E);A.onBeforeShadow(t,A,_,S,B,$,null),t.renderBufferDirect(S,null,B,$,A,null),A.onAfterShadow(t,A,_,S,B,$,null)}}const R=A.children;for(let B=0,D=R.length;B<D;B++)y(R[B],_,S,T,E)}function w(A){A.target.removeEventListener("dispose",w);for(const S in c){const T=c[S],E=A.target.uuid;E in T&&(T[E].dispose(),delete T[E])}}}function _G(t,e){function n(){let W=!1;const _e=new yn;let fe=null;const Me=new yn(0,0,0,0);return{setMask:function(Pe){fe!==Pe&&!W&&(t.colorMask(Pe,Pe,Pe,Pe),fe=Pe)},setLocked:function(Pe){W=Pe},setClear:function(Pe,ke,Ce,Ee,at){at===!0&&(Pe*=Ee,ke*=Ee,Ce*=Ee),_e.set(Pe,ke,Ce,Ee),Me.equals(_e)===!1&&(t.clearColor(Pe,ke,Ce,Ee),Me.copy(_e))},reset:function(){W=!1,fe=null,Me.set(-1,0,0,0)}}}function a(){let W=!1,_e=!1,fe=null,Me=null,Pe=null;return{setReversed:function(ke){if(_e!==ke){const Ce=e.get("EXT_clip_control");ke?Ce.clipControlEXT(Ce.LOWER_LEFT_EXT,Ce.ZERO_TO_ONE_EXT):Ce.clipControlEXT(Ce.LOWER_LEFT_EXT,Ce.NEGATIVE_ONE_TO_ONE_EXT),_e=ke;const Ee=Pe;Pe=null,this.setClear(Ee)}},getReversed:function(){return _e},setTest:function(ke){ke?Z(t.DEPTH_TEST):Ne(t.DEPTH_TEST)},setMask:function(ke){fe!==ke&&!W&&(t.depthMask(ke),fe=ke)},setFunc:function(ke){if(_e&&(ke=OH[ke]),Me!==ke){switch(ke){case Sw:t.depthFunc(t.NEVER);break;case Mw:t.depthFunc(t.ALWAYS);break;case Aw:t.depthFunc(t.LESS);break;case Nh:t.depthFunc(t.LEQUAL);break;case Tw:t.depthFunc(t.EQUAL);break;case Ew:t.depthFunc(t.GEQUAL);break;case _w:t.depthFunc(t.GREATER);break;case Cw:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}Me=ke}},setLocked:function(ke){W=ke},setClear:function(ke){Pe!==ke&&(Pe=ke,_e&&(ke=1-ke),t.clearDepth(ke))},reset:function(){W=!1,fe=null,Me=null,Pe=null,_e=!1}}}function i(){let W=!1,_e=null,fe=null,Me=null,Pe=null,ke=null,Ce=null,Ee=null,at=null;return{setTest:function(dt){W||(dt?Z(t.STENCIL_TEST):Ne(t.STENCIL_TEST))},setMask:function(dt){_e!==dt&&!W&&(t.stencilMask(dt),_e=dt)},setFunc:function(dt,va,Ao){(fe!==dt||Me!==va||Pe!==Ao)&&(t.stencilFunc(dt,va,Ao),fe=dt,Me=va,Pe=Ao)},setOp:function(dt,va,Ao){(ke!==dt||Ce!==va||Ee!==Ao)&&(t.stencilOp(dt,va,Ao),ke=dt,Ce=va,Ee=Ao)},setLocked:function(dt){W=dt},setClear:function(dt){at!==dt&&(t.clearStencil(dt),at=dt)},reset:function(){W=!1,_e=null,fe=null,Me=null,Pe=null,ke=null,Ce=null,Ee=null,at=null}}}const o=new n,s=new a,r=new i,l=new WeakMap,c=new WeakMap;let d={},p={},h={},u=new WeakMap,f=[],v=null,g=!1,m=null,b=null,k=null,y=null,w=null,A=null,_=null,S=new $t(0,0,0),T=0,E=!1,P=null,R=null,B=null,D=null,$=null;const G=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let O=!1,J=0;const ne=t.getParameter(t.VERSION);ne.indexOf("WebGL")!==-1?(J=parseFloat(/^WebGL (\d)/.exec(ne)[1]),O=J>=1):ne.indexOf("OpenGL ES")!==-1&&(J=parseFloat(/^OpenGL ES (\d)/.exec(ne)[1]),O=J>=2);let ae=null,q={};const we=t.getParameter(t.SCISSOR_BOX),Re=t.getParameter(t.VIEWPORT),ot=new yn().fromArray(we),Qe=new yn().fromArray(Re);function st(W,_e,fe,Me){const Pe=new Uint8Array(4),ke=t.createTexture();t.bindTexture(W,ke),t.texParameteri(W,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(W,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Ce=0;Ce<fe;Ce++)W===t.TEXTURE_3D||W===t.TEXTURE_2D_ARRAY?t.texImage3D(_e,0,t.RGBA,1,1,Me,0,t.RGBA,t.UNSIGNED_BYTE,Pe):t.texImage2D(_e+Ce,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Pe);return ke}const de={};de[t.TEXTURE_2D]=st(t.TEXTURE_2D,t.TEXTURE_2D,1),de[t.TEXTURE_CUBE_MAP]=st(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),de[t.TEXTURE_2D_ARRAY]=st(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),de[t.TEXTURE_3D]=st(t.TEXTURE_3D,t.TEXTURE_3D,1,1),o.setClear(0,0,0,1),s.setClear(1),r.setClear(0),Z(t.DEPTH_TEST),s.setFunc(Nh),mt(!1),Gt(w5),Z(t.CULL_FACE),vt(ts);function Z(W){d[W]!==!0&&(t.enable(W),d[W]=!0)}function Ne(W){d[W]!==!1&&(t.disable(W),d[W]=!1)}function Xe(W,_e){return h[W]!==_e?(t.bindFramebuffer(W,_e),h[W]=_e,W===t.DRAW_FRAMEBUFFER&&(h[t.FRAMEBUFFER]=_e),W===t.FRAMEBUFFER&&(h[t.DRAW_FRAMEBUFFER]=_e),!0):!1}function De(W,_e){let fe=f,Me=!1;if(W){fe=u.get(_e),fe===void 0&&(fe=[],u.set(_e,fe));const Pe=W.textures;if(fe.length!==Pe.length||fe[0]!==t.COLOR_ATTACHMENT0){for(let ke=0,Ce=Pe.length;ke<Ce;ke++)fe[ke]=t.COLOR_ATTACHMENT0+ke;fe.length=Pe.length,Me=!0}}else fe[0]!==t.BACK&&(fe[0]=t.BACK,Me=!0);Me&&t.drawBuffers(fe)}function be(W){return v!==W?(t.useProgram(W),v=W,!0):!1}const ft={[Dc]:t.FUNC_ADD,[aH]:t.FUNC_SUBTRACT,[iH]:t.FUNC_REVERSE_SUBTRACT};ft[oH]=t.MIN,ft[sH]=t.MAX;const rt={[rH]:t.ZERO,[lH]:t.ONE,[cH]:t.SRC_COLOR,[M5]:t.SRC_ALPHA,[mH]:t.SRC_ALPHA_SATURATE,[uH]:t.DST_COLOR,[pH]:t.DST_ALPHA,[dH]:t.ONE_MINUS_SRC_COLOR,[A5]:t.ONE_MINUS_SRC_ALPHA,[fH]:t.ONE_MINUS_DST_COLOR,[hH]:t.ONE_MINUS_DST_ALPHA,[gH]:t.CONSTANT_COLOR,[vH]:t.ONE_MINUS_CONSTANT_COLOR,[xH]:t.CONSTANT_ALPHA,[bH]:t.ONE_MINUS_CONSTANT_ALPHA};function vt(W,_e,fe,Me,Pe,ke,Ce,Ee,at,dt){if(W===ts){g===!0&&(Ne(t.BLEND),g=!1);return}if(g===!1&&(Z(t.BLEND),g=!0),W!==nH){if(W!==m||dt!==E){if((b!==Dc||w!==Dc)&&(t.blendEquation(t.FUNC_ADD),b=Dc,w=Dc),dt)switch(W){case zc:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case ns:t.blendFunc(t.ONE,t.ONE);break;case k5:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case S5:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:Ot("WebGLState: Invalid blending: ",W);break}else switch(W){case zc:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case ns:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case k5:Ot("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case S5:Ot("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ot("WebGLState: Invalid blending: ",W);break}k=null,y=null,A=null,_=null,S.set(0,0,0),T=0,m=W,E=dt}return}Pe=Pe||_e,ke=ke||fe,Ce=Ce||Me,(_e!==b||Pe!==w)&&(t.blendEquationSeparate(ft[_e],ft[Pe]),b=_e,w=Pe),(fe!==k||Me!==y||ke!==A||Ce!==_)&&(t.blendFuncSeparate(rt[fe],rt[Me],rt[ke],rt[Ce]),k=fe,y=Me,A=ke,_=Ce),(Ee.equals(S)===!1||at!==T)&&(t.blendColor(Ee.r,Ee.g,Ee.b,at),S.copy(Ee),T=at),m=W,E=!1}function Rt(W,_e){W.side===es?Ne(t.CULL_FACE):Z(t.CULL_FACE);let fe=W.side===Ea;_e&&(fe=!fe),mt(fe),W.blending===zc&&W.transparent===!1?vt(ts):vt(W.blending,W.blendEquation,W.blendSrc,W.blendDst,W.blendEquationAlpha,W.blendSrcAlpha,W.blendDstAlpha,W.blendColor,W.blendAlpha,W.premultipliedAlpha),s.setFunc(W.depthFunc),s.setTest(W.depthTest),s.setMask(W.depthWrite),o.setMask(W.colorWrite);const Me=W.stencilWrite;r.setTest(Me),Me&&(r.setMask(W.stencilWriteMask),r.setFunc(W.stencilFunc,W.stencilRef,W.stencilFuncMask),r.setOp(W.stencilFail,W.stencilZFail,W.stencilZPass)),cn(W.polygonOffset,W.polygonOffsetFactor,W.polygonOffsetUnits),W.alphaToCoverage===!0?Z(t.SAMPLE_ALPHA_TO_COVERAGE):Ne(t.SAMPLE_ALPHA_TO_COVERAGE)}function mt(W){P!==W&&(W?t.frontFace(t.CW):t.frontFace(t.CCW),P=W)}function Gt(W){W!==QB?(Z(t.CULL_FACE),W!==R&&(W===w5?t.cullFace(t.BACK):W===eH?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):Ne(t.CULL_FACE),R=W}function ln(W){W!==B&&(O&&t.lineWidth(W),B=W)}function cn(W,_e,fe){W?(Z(t.POLYGON_OFFSET_FILL),(D!==_e||$!==fe)&&(D=_e,$=fe,s.getReversed()&&(_e=-_e),t.polygonOffset(_e,fe))):Ne(t.POLYGON_OFFSET_FILL)}function Ut(W){W?Z(t.SCISSOR_TEST):Ne(t.SCISSOR_TEST)}function Jt(W){W===void 0&&(W=t.TEXTURE0+G-1),ae!==W&&(t.activeTexture(W),ae=W)}function K(W,_e,fe){fe===void 0&&(ae===null?fe=t.TEXTURE0+G-1:fe=ae);let Me=q[fe];Me===void 0&&(Me={type:void 0,texture:void 0},q[fe]=Me),(Me.type!==W||Me.texture!==_e)&&(ae!==fe&&(t.activeTexture(fe),ae=fe),t.bindTexture(W,_e||de[W]),Me.type=W,Me.texture=_e)}function dn(){const W=q[ae];W!==void 0&&W.type!==void 0&&(t.bindTexture(W.type,null),W.type=void 0,W.texture=void 0)}function zt(){try{t.compressedTexImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function F(){try{t.compressedTexImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function M(){try{t.texSubImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function ee(){try{t.texSubImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function se(){try{t.compressedTexSubImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function he(){try{t.compressedTexSubImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function Le(){try{t.texStorage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function ze(){try{t.texStorage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function ge(){try{t.texImage2D(...arguments)}catch(W){Ot("WebGLState:",W)}}function z(){try{t.texImage3D(...arguments)}catch(W){Ot("WebGLState:",W)}}function j(W){return p[W]!==void 0?p[W]:t.getParameter(W)}function ce(W,_e){p[W]!==_e&&(t.pixelStorei(W,_e),p[W]=_e)}function I(W){ot.equals(W)===!1&&(t.scissor(W.x,W.y,W.z,W.w),ot.copy(W))}function U(W){Qe.equals(W)===!1&&(t.viewport(W.x,W.y,W.z,W.w),Qe.copy(W))}function Y(W,_e){let fe=c.get(_e);fe===void 0&&(fe=new WeakMap,c.set(_e,fe));let Me=fe.get(W);Me===void 0&&(Me=t.getUniformBlockIndex(_e,W.name),fe.set(W,Me))}function pe(W,_e){const Me=c.get(_e).get(W);l.get(_e)!==Me&&(t.uniformBlockBinding(_e,Me,W.__bindingPointIndex),l.set(_e,Me))}function Ie(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),s.setReversed(!1),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),t.pixelStorei(t.PACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.BROWSER_DEFAULT_WEBGL),t.pixelStorei(t.PACK_ROW_LENGTH,0),t.pixelStorei(t.PACK_SKIP_PIXELS,0),t.pixelStorei(t.PACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_ROW_LENGTH,0),t.pixelStorei(t.UNPACK_IMAGE_HEIGHT,0),t.pixelStorei(t.UNPACK_SKIP_PIXELS,0),t.pixelStorei(t.UNPACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_SKIP_IMAGES,0),d={},p={},ae=null,q={},h={},u=new WeakMap,f=[],v=null,g=!1,m=null,b=null,k=null,y=null,w=null,A=null,_=null,S=new $t(0,0,0),T=0,E=!1,P=null,R=null,B=null,D=null,$=null,ot.set(0,0,t.canvas.width,t.canvas.height),Qe.set(0,0,t.canvas.width,t.canvas.height),o.reset(),s.reset(),r.reset()}return{buffers:{color:o,depth:s,stencil:r},enable:Z,disable:Ne,bindFramebuffer:Xe,drawBuffers:De,useProgram:be,setBlending:vt,setMaterial:Rt,setFlipSided:mt,setCullFace:Gt,setLineWidth:ln,setPolygonOffset:cn,setScissorTest:Ut,activeTexture:Jt,bindTexture:K,unbindTexture:dn,compressedTexImage2D:zt,compressedTexImage3D:F,texImage2D:ge,texImage3D:z,pixelStorei:ce,getParameter:j,updateUBOMapping:Y,uniformBlockBinding:pe,texStorage2D:Le,texStorage3D:ze,texSubImage2D:M,texSubImage3D:ee,compressedTexSubImage2D:se,compressedTexSubImage3D:he,scissor:I,viewport:U,reset:Ie}}function CG(t,e,n,a,i,o,s){const r=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ut,d=new WeakMap,p=new Set;let h;const u=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(F,M){return f?new OffscreenCanvas(F,M):kg("canvas")}function g(F,M,ee){let se=1;const he=zt(F);if((he.width>ee||he.height>ee)&&(se=ee/Math.max(he.width,he.height)),se<1)if(typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&F instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&F instanceof ImageBitmap||typeof VideoFrame<"u"&&F instanceof VideoFrame){const Le=Math.floor(se*he.width),ze=Math.floor(se*he.height);h===void 0&&(h=v(Le,ze));const ge=M?v(Le,ze):h;return ge.width=Le,ge.height=ze,ge.getContext("2d").drawImage(F,0,0,Le,ze),it("WebGLRenderer: Texture has been resized from ("+he.width+"x"+he.height+") to ("+Le+"x"+ze+")."),ge}else return"data"in F&&it("WebGLRenderer: Image in DataTexture is too big ("+he.width+"x"+he.height+")."),F;return F}function m(F){return F.generateMipmaps}function b(F){t.generateMipmap(F)}function k(F){return F.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:F.isWebGL3DRenderTarget?t.TEXTURE_3D:F.isWebGLArrayRenderTarget||F.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function y(F,M,ee,se,he,Le=!1){if(F!==null){if(t[F]!==void 0)return t[F];it("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+F+"'")}let ze;se&&(ze=e.get("EXT_texture_norm16"),ze||it("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let ge=M;if(M===t.RED&&(ee===t.FLOAT&&(ge=t.R32F),ee===t.HALF_FLOAT&&(ge=t.R16F),ee===t.UNSIGNED_BYTE&&(ge=t.R8),ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.R16_EXT),ee===t.SHORT&&ze&&(ge=ze.R16_SNORM_EXT)),M===t.RED_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.R8UI),ee===t.UNSIGNED_SHORT&&(ge=t.R16UI),ee===t.UNSIGNED_INT&&(ge=t.R32UI),ee===t.BYTE&&(ge=t.R8I),ee===t.SHORT&&(ge=t.R16I),ee===t.INT&&(ge=t.R32I)),M===t.RG&&(ee===t.FLOAT&&(ge=t.RG32F),ee===t.HALF_FLOAT&&(ge=t.RG16F),ee===t.UNSIGNED_BYTE&&(ge=t.RG8),ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.RG16_EXT),ee===t.SHORT&&ze&&(ge=ze.RG16_SNORM_EXT)),M===t.RG_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.RG8UI),ee===t.UNSIGNED_SHORT&&(ge=t.RG16UI),ee===t.UNSIGNED_INT&&(ge=t.RG32UI),ee===t.BYTE&&(ge=t.RG8I),ee===t.SHORT&&(ge=t.RG16I),ee===t.INT&&(ge=t.RG32I)),M===t.RGB_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.RGB8UI),ee===t.UNSIGNED_SHORT&&(ge=t.RGB16UI),ee===t.UNSIGNED_INT&&(ge=t.RGB32UI),ee===t.BYTE&&(ge=t.RGB8I),ee===t.SHORT&&(ge=t.RGB16I),ee===t.INT&&(ge=t.RGB32I)),M===t.RGBA_INTEGER&&(ee===t.UNSIGNED_BYTE&&(ge=t.RGBA8UI),ee===t.UNSIGNED_SHORT&&(ge=t.RGBA16UI),ee===t.UNSIGNED_INT&&(ge=t.RGBA32UI),ee===t.BYTE&&(ge=t.RGBA8I),ee===t.SHORT&&(ge=t.RGBA16I),ee===t.INT&&(ge=t.RGBA32I)),M===t.RGB&&(ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.RGB16_EXT),ee===t.SHORT&&ze&&(ge=ze.RGB16_SNORM_EXT),ee===t.UNSIGNED_INT_5_9_9_9_REV&&(ge=t.RGB9_E5),ee===t.UNSIGNED_INT_10F_11F_11F_REV&&(ge=t.R11F_G11F_B10F)),M===t.RGBA){const z=Le?yg:Ct.getTransfer(he);ee===t.FLOAT&&(ge=t.RGBA32F),ee===t.HALF_FLOAT&&(ge=t.RGBA16F),ee===t.UNSIGNED_BYTE&&(ge=z===Ht?t.SRGB8_ALPHA8:t.RGBA8),ee===t.UNSIGNED_SHORT&&ze&&(ge=ze.RGBA16_EXT),ee===t.SHORT&&ze&&(ge=ze.RGBA16_SNORM_EXT),ee===t.UNSIGNED_SHORT_4_4_4_4&&(ge=t.RGBA4),ee===t.UNSIGNED_SHORT_5_5_5_1&&(ge=t.RGB5_A1)}return(ge===t.R16F||ge===t.R32F||ge===t.RG16F||ge===t.RG32F||ge===t.RGBA16F||ge===t.RGBA32F)&&e.get("EXT_color_buffer_float"),ge}function w(F,M){let ee;return F?M===null||M===fo||M===Dh?ee=t.DEPTH24_STENCIL8:M===mo?ee=t.DEPTH32F_STENCIL8:M===zh&&(ee=t.DEPTH24_STENCIL8,it("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):M===null||M===fo||M===Dh?ee=t.DEPTH_COMPONENT24:M===mo?ee=t.DEPTH_COMPONENT32F:M===zh&&(ee=t.DEPTH_COMPONENT16),ee}function A(F,M){return m(F)===!0||F.isFramebufferTexture&&F.minFilter!==Vn&&F.minFilter!==Qn?Math.log2(Math.max(M.width,M.height))+1:F.mipmaps!==void 0&&F.mipmaps.length>0?F.mipmaps.length:F.isCompressedTexture&&Array.isArray(F.image)?M.mipmaps.length:1}function _(F){const M=F.target;M.removeEventListener("dispose",_),T(M),M.isVideoTexture&&d.delete(M),M.isHTMLTexture&&p.delete(M)}function S(F){const M=F.target;M.removeEventListener("dispose",S),P(M)}function T(F){const M=a.get(F);if(M.__webglInit===void 0)return;const ee=F.source,se=u.get(ee);if(se){const he=se[M.__cacheKey];he.usedTimes--,he.usedTimes===0&&E(F),Object.keys(se).length===0&&u.delete(ee)}a.remove(F)}function E(F){const M=a.get(F);t.deleteTexture(M.__webglTexture);const ee=F.source,se=u.get(ee);delete se[M.__cacheKey],s.memory.textures--}function P(F){const M=a.get(F);if(F.depthTexture&&(F.depthTexture.dispose(),a.remove(F.depthTexture)),F.isWebGLCubeRenderTarget)for(let se=0;se<6;se++){if(Array.isArray(M.__webglFramebuffer[se]))for(let he=0;he<M.__webglFramebuffer[se].length;he++)t.deleteFramebuffer(M.__webglFramebuffer[se][he]);else t.deleteFramebuffer(M.__webglFramebuffer[se]);M.__webglDepthbuffer&&t.deleteRenderbuffer(M.__webglDepthbuffer[se])}else{if(Array.isArray(M.__webglFramebuffer))for(let se=0;se<M.__webglFramebuffer.length;se++)t.deleteFramebuffer(M.__webglFramebuffer[se]);else t.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer&&t.deleteRenderbuffer(M.__webglDepthbuffer),M.__webglMultisampledFramebuffer&&t.deleteFramebuffer(M.__webglMultisampledFramebuffer),M.__webglColorRenderbuffer)for(let se=0;se<M.__webglColorRenderbuffer.length;se++)M.__webglColorRenderbuffer[se]&&t.deleteRenderbuffer(M.__webglColorRenderbuffer[se]);M.__webglDepthRenderbuffer&&t.deleteRenderbuffer(M.__webglDepthRenderbuffer)}const ee=F.textures;for(let se=0,he=ee.length;se<he;se++){const Le=a.get(ee[se]);Le.__webglTexture&&(t.deleteTexture(Le.__webglTexture),s.memory.textures--),a.remove(ee[se])}a.remove(F)}let R=0;function B(){R=0}function D(){return R}function $(F){R=F}function G(){const F=R;return F>=i.maxTextures&&it("WebGLTextures: Trying to use "+(F+1)+" texture units while this GPU supports only "+i.maxTextures),R+=1,F}function O(F){const M=[];return M.push(F.wrapS),M.push(F.wrapT),M.push(F.wrapR||0),M.push(F.magFilter),M.push(F.minFilter),M.push(F.anisotropy),M.push(F.internalFormat),M.push(F.format),M.push(F.type),M.push(F.generateMipmaps),M.push(F.premultiplyAlpha),M.push(F.flipY),M.push(F.unpackAlignment),M.push(F.colorSpace),M.join()}function J(F,M){const ee=a.get(F);if(F.isVideoTexture&&K(F),F.isRenderTargetTexture===!1&&F.isExternalTexture!==!0&&F.version>0&&ee.__version!==F.version){const se=F.image;if(se===null)it("WebGLRenderer: Texture marked for update but no image data found.");else if(se.complete===!1)it("WebGLRenderer: Texture marked for update but image is incomplete");else{Ne(ee,F,M);return}}else F.isExternalTexture&&(ee.__webglTexture=F.sourceTexture?F.sourceTexture:null);n.bindTexture(t.TEXTURE_2D,ee.__webglTexture,t.TEXTURE0+M)}function ne(F,M){const ee=a.get(F);if(F.isRenderTargetTexture===!1&&F.version>0&&ee.__version!==F.version){Ne(ee,F,M);return}else F.isExternalTexture&&(ee.__webglTexture=F.sourceTexture?F.sourceTexture:null);n.bindTexture(t.TEXTURE_2D_ARRAY,ee.__webglTexture,t.TEXTURE0+M)}function ae(F,M){const ee=a.get(F);if(F.isRenderTargetTexture===!1&&F.version>0&&ee.__version!==F.version){Ne(ee,F,M);return}n.bindTexture(t.TEXTURE_3D,ee.__webglTexture,t.TEXTURE0+M)}function q(F,M){const ee=a.get(F);if(F.isCubeDepthTexture!==!0&&F.version>0&&ee.__version!==F.version){Xe(ee,F,M);return}n.bindTexture(t.TEXTURE_CUBE_MAP,ee.__webglTexture,t.TEXTURE0+M)}const we={[Pw]:t.REPEAT,[as]:t.CLAMP_TO_EDGE,[Iw]:t.MIRRORED_REPEAT},Re={[Vn]:t.NEAREST,[kH]:t.NEAREST_MIPMAP_NEAREST,[hg]:t.NEAREST_MIPMAP_LINEAR,[Qn]:t.LINEAR,[Nw]:t.LINEAR_MIPMAP_NEAREST,[il]:t.LINEAR_MIPMAP_LINEAR},ot={[TH]:t.NEVER,[RH]:t.ALWAYS,[EH]:t.LESS,[x1]:t.LEQUAL,[_H]:t.EQUAL,[b1]:t.GEQUAL,[CH]:t.GREATER,[LH]:t.NOTEQUAL};function Qe(F,M){if(M.type===mo&&e.has("OES_texture_float_linear")===!1&&(M.magFilter===Qn||M.magFilter===Nw||M.magFilter===hg||M.magFilter===il||M.minFilter===Qn||M.minFilter===Nw||M.minFilter===hg||M.minFilter===il)&&it("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(F,t.TEXTURE_WRAP_S,we[M.wrapS]),t.texParameteri(F,t.TEXTURE_WRAP_T,we[M.wrapT]),(F===t.TEXTURE_3D||F===t.TEXTURE_2D_ARRAY)&&t.texParameteri(F,t.TEXTURE_WRAP_R,we[M.wrapR]),t.texParameteri(F,t.TEXTURE_MAG_FILTER,Re[M.magFilter]),t.texParameteri(F,t.TEXTURE_MIN_FILTER,Re[M.minFilter]),M.compareFunction&&(t.texParameteri(F,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(F,t.TEXTURE_COMPARE_FUNC,ot[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===Vn||M.minFilter!==hg&&M.minFilter!==il||M.type===mo&&e.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||a.get(M).__currentAnisotropy){const ee=e.get("EXT_texture_filter_anisotropic");t.texParameterf(F,ee.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,i.getMaxAnisotropy())),a.get(M).__currentAnisotropy=M.anisotropy}}}function st(F,M){let ee=!1;F.__webglInit===void 0&&(F.__webglInit=!0,M.addEventListener("dispose",_));const se=M.source;let he=u.get(se);he===void 0&&(he={},u.set(se,he));const Le=O(M);if(Le!==F.__cacheKey){he[Le]===void 0&&(he[Le]={texture:t.createTexture(),usedTimes:0},s.memory.textures++,ee=!0),he[Le].usedTimes++;const ze=he[F.__cacheKey];ze!==void 0&&(he[F.__cacheKey].usedTimes--,ze.usedTimes===0&&E(M)),F.__cacheKey=Le,F.__webglTexture=he[Le].texture}return ee}function de(F,M,ee){return Math.floor(Math.floor(F/ee)/M)}function Z(F,M,ee,se){const Le=F.updateRanges;if(Le.length===0)n.texSubImage2D(t.TEXTURE_2D,0,0,0,M.width,M.height,ee,se,M.data);else{Le.sort((ce,I)=>ce.start-I.start);let ze=0;for(let ce=1;ce<Le.length;ce++){const I=Le[ze],U=Le[ce],Y=I.start+I.count,pe=de(U.start,M.width,4),Ie=de(I.start,M.width,4);U.start<=Y+1&&pe===Ie&&de(U.start+U.count-1,M.width,4)===pe?I.count=Math.max(I.count,U.start+U.count-I.start):(++ze,Le[ze]=U)}Le.length=ze+1;const ge=n.getParameter(t.UNPACK_ROW_LENGTH),z=n.getParameter(t.UNPACK_SKIP_PIXELS),j=n.getParameter(t.UNPACK_SKIP_ROWS);n.pixelStorei(t.UNPACK_ROW_LENGTH,M.width);for(let ce=0,I=Le.length;ce<I;ce++){const U=Le[ce],Y=Math.floor(U.start/4),pe=Math.ceil(U.count/4),Ie=Y%M.width,W=Math.floor(Y/M.width),_e=pe,fe=1;n.pixelStorei(t.UNPACK_SKIP_PIXELS,Ie),n.pixelStorei(t.UNPACK_SKIP_ROWS,W),n.texSubImage2D(t.TEXTURE_2D,0,Ie,W,_e,fe,ee,se,M.data)}F.clearUpdateRanges(),n.pixelStorei(t.UNPACK_ROW_LENGTH,ge),n.pixelStorei(t.UNPACK_SKIP_PIXELS,z),n.pixelStorei(t.UNPACK_SKIP_ROWS,j)}}function Ne(F,M,ee){let se=t.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(se=t.TEXTURE_2D_ARRAY),M.isData3DTexture&&(se=t.TEXTURE_3D);const he=st(F,M),Le=M.source;n.bindTexture(se,F.__webglTexture,t.TEXTURE0+ee);const ze=a.get(Le);if(Le.version!==ze.__version||he===!0){if(n.activeTexture(t.TEXTURE0+ee),(typeof ImageBitmap<"u"&&M.image instanceof ImageBitmap)===!1){const fe=Ct.getPrimaries(Ct.workingColorSpace),Me=M.colorSpace===Vs?null:Ct.getPrimaries(M.colorSpace),Pe=M.colorSpace===Vs||fe===Me?t.NONE:t.BROWSER_DEFAULT_WEBGL;n.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Pe)}n.pixelStorei(t.UNPACK_ALIGNMENT,M.unpackAlignment);let z=g(M.image,!1,i.maxTextureSize);z=dn(M,z);const j=o.convert(M.format,M.colorSpace),ce=o.convert(M.type);let I=y(M.internalFormat,j,ce,M.normalized,M.colorSpace,M.isVideoTexture);Qe(se,M);let U;const Y=M.mipmaps,pe=M.isVideoTexture!==!0,Ie=ze.__version===void 0||he===!0,W=Le.dataReady,_e=A(M,z);if(M.isDepthTexture)I=w(M.format===ol,M.type),Ie&&(pe?n.texStorage2D(t.TEXTURE_2D,1,I,z.width,z.height):n.texImage2D(t.TEXTURE_2D,0,I,z.width,z.height,0,j,ce,null));else if(M.isDataTexture)if(Y.length>0){pe&&Ie&&n.texStorage2D(t.TEXTURE_2D,_e,I,Y[0].width,Y[0].height);for(let fe=0,Me=Y.length;fe<Me;fe++)U=Y[fe],pe?W&&n.texSubImage2D(t.TEXTURE_2D,fe,0,0,U.width,U.height,j,ce,U.data):n.texImage2D(t.TEXTURE_2D,fe,I,U.width,U.height,0,j,ce,U.data);M.generateMipmaps=!1}else pe?(Ie&&n.texStorage2D(t.TEXTURE_2D,_e,I,z.width,z.height),W&&Z(M,z,j,ce)):n.texImage2D(t.TEXTURE_2D,0,I,z.width,z.height,0,j,ce,z.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){pe&&Ie&&n.texStorage3D(t.TEXTURE_2D_ARRAY,_e,I,Y[0].width,Y[0].height,z.depth);for(let fe=0,Me=Y.length;fe<Me;fe++)if(U=Y[fe],M.format!==Si)if(j!==null)if(pe){if(W)if(M.layerUpdates.size>0){const Pe=L_(U.width,U.height,M.format,M.type);for(const ke of M.layerUpdates){const Ce=U.data.subarray(ke*Pe/U.data.BYTES_PER_ELEMENT,(ke+1)*Pe/U.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,ke,U.width,U.height,1,j,Ce)}}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,0,U.width,U.height,z.depth,j,U.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,fe,I,U.width,U.height,z.depth,0,U.data,0,0);else it("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else pe?W&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,0,U.width,U.height,z.depth,j,ce,U.data):n.texImage3D(t.TEXTURE_2D_ARRAY,fe,I,U.width,U.height,z.depth,0,j,ce,U.data);M.layerUpdates.size>0&&M.clearLayerUpdates()}else{pe&&Ie&&n.texStorage2D(t.TEXTURE_2D,_e,I,Y[0].width,Y[0].height);for(let fe=0,Me=Y.length;fe<Me;fe++)U=Y[fe],M.format!==Si?j!==null?pe?W&&n.compressedTexSubImage2D(t.TEXTURE_2D,fe,0,0,U.width,U.height,j,U.data):n.compressedTexImage2D(t.TEXTURE_2D,fe,I,U.width,U.height,0,U.data):it("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):pe?W&&n.texSubImage2D(t.TEXTURE_2D,fe,0,0,U.width,U.height,j,ce,U.data):n.texImage2D(t.TEXTURE_2D,fe,I,U.width,U.height,0,j,ce,U.data)}else if(M.isDataArrayTexture)if(pe){if(Ie&&n.texStorage3D(t.TEXTURE_2D_ARRAY,_e,I,z.width,z.height,z.depth),W)if(M.layerUpdates.size>0){const fe=L_(z.width,z.height,M.format,M.type);for(const Me of M.layerUpdates){const Pe=z.data.subarray(Me*fe/z.data.BYTES_PER_ELEMENT,(Me+1)*fe/z.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,Me,z.width,z.height,1,j,ce,Pe)}M.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,z.width,z.height,z.depth,j,ce,z.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,I,z.width,z.height,z.depth,0,j,ce,z.data);else if(M.isData3DTexture)pe?(Ie&&n.texStorage3D(t.TEXTURE_3D,_e,I,z.width,z.height,z.depth),W&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,z.width,z.height,z.depth,j,ce,z.data)):n.texImage3D(t.TEXTURE_3D,0,I,z.width,z.height,z.depth,0,j,ce,z.data);else if(M.isFramebufferTexture){if(Ie)if(pe)n.texStorage2D(t.TEXTURE_2D,_e,I,z.width,z.height);else{let fe=z.width,Me=z.height;for(let Pe=0;Pe<_e;Pe++)n.texImage2D(t.TEXTURE_2D,Pe,I,fe,Me,0,j,ce,null),fe>>=1,Me>>=1}}else if(M.isHTMLTexture){if("texElementImage2D"in t){const fe=t.canvas;if(fe.hasAttribute("layoutsubtree")||fe.setAttribute("layoutsubtree","true"),z.parentNode!==fe){fe.appendChild(z),p.add(M),fe.onpaint=Me=>{const Pe=Me.changedElements;for(const ke of p)Pe.includes(ke.image)&&(ke.needsUpdate=!0)},fe.requestPaint();return}if(t.texElementImage2D.length===3)t.texElementImage2D(t.TEXTURE_2D,t.RGBA8,z);else{const Pe=t.RGBA,ke=t.RGBA,Ce=t.UNSIGNED_BYTE;t.texElementImage2D(t.TEXTURE_2D,0,Pe,ke,Ce,z)}t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}}else if(Y.length>0){if(pe&&Ie){const fe=zt(Y[0]);n.texStorage2D(t.TEXTURE_2D,_e,I,fe.width,fe.height)}for(let fe=0,Me=Y.length;fe<Me;fe++)U=Y[fe],pe?W&&n.texSubImage2D(t.TEXTURE_2D,fe,0,0,j,ce,U):n.texImage2D(t.TEXTURE_2D,fe,I,j,ce,U);M.generateMipmaps=!1}else if(pe){if(Ie){const fe=zt(z);n.texStorage2D(t.TEXTURE_2D,_e,I,fe.width,fe.height)}W&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,j,ce,z)}else n.texImage2D(t.TEXTURE_2D,0,I,j,ce,z);m(M)&&b(se),ze.__version=Le.version,M.onUpdate&&M.onUpdate(M)}F.__version=M.version}function Xe(F,M,ee){if(M.image.length!==6)return;const se=st(F,M),he=M.source;n.bindTexture(t.TEXTURE_CUBE_MAP,F.__webglTexture,t.TEXTURE0+ee);const Le=a.get(he);if(he.version!==Le.__version||se===!0){n.activeTexture(t.TEXTURE0+ee);const ze=Ct.getPrimaries(Ct.workingColorSpace),ge=M.colorSpace===Vs?null:Ct.getPrimaries(M.colorSpace),z=M.colorSpace===Vs||ze===ge?t.NONE:t.BROWSER_DEFAULT_WEBGL;n.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(t.UNPACK_ALIGNMENT,M.unpackAlignment),n.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,z);const j=M.isCompressedTexture||M.image[0].isCompressedTexture,ce=M.image[0]&&M.image[0].isDataTexture,I=[];for(let ke=0;ke<6;ke++)!j&&!ce?I[ke]=g(M.image[ke],!0,i.maxCubemapSize):I[ke]=ce?M.image[ke].image:M.image[ke],I[ke]=dn(M,I[ke]);const U=I[0],Y=o.convert(M.format,M.colorSpace),pe=o.convert(M.type),Ie=y(M.internalFormat,Y,pe,M.normalized,M.colorSpace),W=M.isVideoTexture!==!0,_e=Le.__version===void 0||se===!0,fe=he.dataReady;let Me=A(M,U);Qe(t.TEXTURE_CUBE_MAP,M);let Pe;if(j){W&&_e&&n.texStorage2D(t.TEXTURE_CUBE_MAP,Me,Ie,U.width,U.height);for(let ke=0;ke<6;ke++){Pe=I[ke].mipmaps;for(let Ce=0;Ce<Pe.length;Ce++){const Ee=Pe[Ce];M.format!==Si?Y!==null?W?fe&&n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,0,0,Ee.width,Ee.height,Y,Ee.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,Ie,Ee.width,Ee.height,0,Ee.data):it("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,0,0,Ee.width,Ee.height,Y,pe,Ee.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce,Ie,Ee.width,Ee.height,0,Y,pe,Ee.data)}}}else{if(Pe=M.mipmaps,W&&_e){Pe.length>0&&Me++;const ke=zt(I[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,Me,Ie,ke.width,ke.height)}for(let ke=0;ke<6;ke++)if(ce){W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,I[ke].width,I[ke].height,Y,pe,I[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ie,I[ke].width,I[ke].height,0,Y,pe,I[ke].data);for(let Ce=0;Ce<Pe.length;Ce++){const at=Pe[Ce].image[ke].image;W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,0,0,at.width,at.height,Y,pe,at.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,Ie,at.width,at.height,0,Y,pe,at.data)}}else{W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,Y,pe,I[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ie,Y,pe,I[ke]);for(let Ce=0;Ce<Pe.length;Ce++){const Ee=Pe[Ce];W?fe&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,0,0,Y,pe,Ee.image[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ce+1,Ie,Y,pe,Ee.image[ke])}}}m(M)&&b(t.TEXTURE_CUBE_MAP),Le.__version=he.version,M.onUpdate&&M.onUpdate(M)}F.__version=M.version}function De(F,M,ee,se,he,Le){const ze=o.convert(ee.format,ee.colorSpace),ge=o.convert(ee.type),z=y(ee.internalFormat,ze,ge,ee.normalized,ee.colorSpace),j=a.get(M),ce=a.get(ee);if(ce.__renderTarget=M,!j.__hasExternalTextures){const I=Math.max(1,M.width>>Le),U=Math.max(1,M.height>>Le);he===t.TEXTURE_3D||he===t.TEXTURE_2D_ARRAY?n.texImage3D(he,Le,z,I,U,M.depth,0,ze,ge,null):n.texImage2D(he,Le,z,I,U,0,ze,ge,null)}n.bindFramebuffer(t.FRAMEBUFFER,F),Jt(M)?r.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,se,he,ce.__webglTexture,0,Ut(M)):(he===t.TEXTURE_2D||he>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&he<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,se,he,ce.__webglTexture,Le),n.bindFramebuffer(t.FRAMEBUFFER,null)}function be(F,M,ee){if(t.bindRenderbuffer(t.RENDERBUFFER,F),M.depthBuffer){const se=M.depthTexture,he=se&&se.isDepthTexture?se.type:null,Le=w(M.stencilBuffer,he),ze=M.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;Jt(M)?r.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Ut(M),Le,M.width,M.height):ee?t.renderbufferStorageMultisample(t.RENDERBUFFER,Ut(M),Le,M.width,M.height):t.renderbufferStorage(t.RENDERBUFFER,Le,M.width,M.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,ze,t.RENDERBUFFER,F)}else{const se=M.textures;for(let he=0;he<se.length;he++){const Le=se[he],ze=o.convert(Le.format,Le.colorSpace),ge=o.convert(Le.type),z=y(Le.internalFormat,ze,ge,Le.normalized,Le.colorSpace);Jt(M)?r.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Ut(M),z,M.width,M.height):ee?t.renderbufferStorageMultisample(t.RENDERBUFFER,Ut(M),z,M.width,M.height):t.renderbufferStorage(t.RENDERBUFFER,z,M.width,M.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function ft(F,M,ee){const se=M.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(t.FRAMEBUFFER,F),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const he=a.get(M.depthTexture);if(he.__renderTarget=M,(!he.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),se){if(he.__webglInit===void 0&&(he.__webglInit=!0,M.depthTexture.addEventListener("dispose",_)),he.__webglTexture===void 0){he.__webglTexture=t.createTexture(),n.bindTexture(t.TEXTURE_CUBE_MAP,he.__webglTexture),Qe(t.TEXTURE_CUBE_MAP,M.depthTexture);const j=o.convert(M.depthTexture.format),ce=o.convert(M.depthTexture.type);let I;M.depthTexture.format===is?I=t.DEPTH_COMPONENT24:M.depthTexture.format===ol&&(I=t.DEPTH24_STENCIL8);for(let U=0;U<6;U++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+U,0,I,M.width,M.height,0,j,ce,null)}}else J(M.depthTexture,0);const Le=he.__webglTexture,ze=Ut(M),ge=se?t.TEXTURE_CUBE_MAP_POSITIVE_X+ee:t.TEXTURE_2D,z=M.depthTexture.format===ol?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(M.depthTexture.format===is)Jt(M)?r.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,z,ge,Le,0,ze):t.framebufferTexture2D(t.FRAMEBUFFER,z,ge,Le,0);else if(M.depthTexture.format===ol)Jt(M)?r.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,z,ge,Le,0,ze):t.framebufferTexture2D(t.FRAMEBUFFER,z,ge,Le,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function rt(F){const M=a.get(F),ee=F.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==F.depthTexture){const se=F.depthTexture;if(M.__depthDisposeCallback&&M.__depthDisposeCallback(),se){const he=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,se.removeEventListener("dispose",he)};se.addEventListener("dispose",he),M.__depthDisposeCallback=he}M.__boundDepthTexture=se}if(F.depthTexture&&!M.__autoAllocateDepthBuffer)if(ee)for(let se=0;se<6;se++)ft(M.__webglFramebuffer[se],F,se);else{const se=F.texture.mipmaps;se&&se.length>0?ft(M.__webglFramebuffer[0],F,0):ft(M.__webglFramebuffer,F,0)}else if(ee){M.__webglDepthbuffer=[];for(let se=0;se<6;se++)if(n.bindFramebuffer(t.FRAMEBUFFER,M.__webglFramebuffer[se]),M.__webglDepthbuffer[se]===void 0)M.__webglDepthbuffer[se]=t.createRenderbuffer(),be(M.__webglDepthbuffer[se],F,!1);else{const he=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Le=M.__webglDepthbuffer[se];t.bindRenderbuffer(t.RENDERBUFFER,Le),t.framebufferRenderbuffer(t.FRAMEBUFFER,he,t.RENDERBUFFER,Le)}}else{const se=F.texture.mipmaps;if(se&&se.length>0?n.bindFramebuffer(t.FRAMEBUFFER,M.__webglFramebuffer[0]):n.bindFramebuffer(t.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=t.createRenderbuffer(),be(M.__webglDepthbuffer,F,!1);else{const he=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Le=M.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,Le),t.framebufferRenderbuffer(t.FRAMEBUFFER,he,t.RENDERBUFFER,Le)}}n.bindFramebuffer(t.FRAMEBUFFER,null)}function vt(F,M,ee){const se=a.get(F);M!==void 0&&De(se.__webglFramebuffer,F,F.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),ee!==void 0&&rt(F)}function Rt(F){const M=F.texture,ee=a.get(F),se=a.get(M);F.addEventListener("dispose",S);const he=F.textures,Le=F.isWebGLCubeRenderTarget===!0,ze=he.length>1;if(ze||(se.__webglTexture===void 0&&(se.__webglTexture=t.createTexture()),se.__version=M.version,s.memory.textures++),Le){ee.__webglFramebuffer=[];for(let ge=0;ge<6;ge++)if(M.mipmaps&&M.mipmaps.length>0){ee.__webglFramebuffer[ge]=[];for(let z=0;z<M.mipmaps.length;z++)ee.__webglFramebuffer[ge][z]=t.createFramebuffer()}else ee.__webglFramebuffer[ge]=t.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){ee.__webglFramebuffer=[];for(let ge=0;ge<M.mipmaps.length;ge++)ee.__webglFramebuffer[ge]=t.createFramebuffer()}else ee.__webglFramebuffer=t.createFramebuffer();if(ze)for(let ge=0,z=he.length;ge<z;ge++){const j=a.get(he[ge]);j.__webglTexture===void 0&&(j.__webglTexture=t.createTexture(),s.memory.textures++)}if(F.samples>0&&Jt(F)===!1){ee.__webglMultisampledFramebuffer=t.createFramebuffer(),ee.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,ee.__webglMultisampledFramebuffer);for(let ge=0;ge<he.length;ge++){const z=he[ge];ee.__webglColorRenderbuffer[ge]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,ee.__webglColorRenderbuffer[ge]);const j=o.convert(z.format,z.colorSpace),ce=o.convert(z.type),I=y(z.internalFormat,j,ce,z.normalized,z.colorSpace,F.isXRRenderTarget===!0),U=Ut(F);t.renderbufferStorageMultisample(t.RENDERBUFFER,U,I,F.width,F.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+ge,t.RENDERBUFFER,ee.__webglColorRenderbuffer[ge])}t.bindRenderbuffer(t.RENDERBUFFER,null),F.depthBuffer&&(ee.__webglDepthRenderbuffer=t.createRenderbuffer(),be(ee.__webglDepthRenderbuffer,F,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(Le){n.bindTexture(t.TEXTURE_CUBE_MAP,se.__webglTexture),Qe(t.TEXTURE_CUBE_MAP,M);for(let ge=0;ge<6;ge++)if(M.mipmaps&&M.mipmaps.length>0)for(let z=0;z<M.mipmaps.length;z++)De(ee.__webglFramebuffer[ge][z],F,M,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,z);else De(ee.__webglFramebuffer[ge],F,M,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0);m(M)&&b(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(ze){for(let ge=0,z=he.length;ge<z;ge++){const j=he[ge],ce=a.get(j);let I=t.TEXTURE_2D;(F.isWebGL3DRenderTarget||F.isWebGLArrayRenderTarget)&&(I=F.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(I,ce.__webglTexture),Qe(I,j),De(ee.__webglFramebuffer,F,j,t.COLOR_ATTACHMENT0+ge,I,0),m(j)&&b(I)}n.unbindTexture()}else{let ge=t.TEXTURE_2D;if((F.isWebGL3DRenderTarget||F.isWebGLArrayRenderTarget)&&(ge=F.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(ge,se.__webglTexture),Qe(ge,M),M.mipmaps&&M.mipmaps.length>0)for(let z=0;z<M.mipmaps.length;z++)De(ee.__webglFramebuffer[z],F,M,t.COLOR_ATTACHMENT0,ge,z);else De(ee.__webglFramebuffer,F,M,t.COLOR_ATTACHMENT0,ge,0);m(M)&&b(ge),n.unbindTexture()}F.depthBuffer&&rt(F)}function mt(F){const M=F.textures;for(let ee=0,se=M.length;ee<se;ee++){const he=M[ee];if(m(he)){const Le=k(F),ze=a.get(he).__webglTexture;n.bindTexture(Le,ze),b(Le),n.unbindTexture()}}}const Gt=[],ln=[];function cn(F){if(F.samples>0){if(Jt(F)===!1){const M=F.textures,ee=F.width,se=F.height;let he=t.COLOR_BUFFER_BIT;const Le=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ze=a.get(F),ge=M.length>1;if(ge)for(let j=0;j<M.length;j++)n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,ze.__webglMultisampledFramebuffer);const z=F.texture.mipmaps;z&&z.length>0?n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ze.__webglFramebuffer[0]):n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ze.__webglFramebuffer);for(let j=0;j<M.length;j++){if(F.resolveDepthBuffer&&(F.depthBuffer&&(he|=t.DEPTH_BUFFER_BIT),F.stencilBuffer&&F.resolveStencilBuffer&&(he|=t.STENCIL_BUFFER_BIT)),ge){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,ze.__webglColorRenderbuffer[j]);const ce=a.get(M[j]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,ce,0)}t.blitFramebuffer(0,0,ee,se,0,0,ee,se,he,t.NEAREST),l===!0&&(Gt.length=0,ln.length=0,Gt.push(t.COLOR_ATTACHMENT0+j),F.depthBuffer&&F.storeMultisampledDepthBuffer===!1&&(Gt.push(Le),ln.push(Le),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,ln)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,Gt))}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),ge)for(let j=0;j<M.length;j++){n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.RENDERBUFFER,ze.__webglColorRenderbuffer[j]);const ce=a.get(M[j]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,ze.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+j,t.TEXTURE_2D,ce,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ze.__webglMultisampledFramebuffer)}else if(F.depthBuffer&&F.storeMultisampledDepthBuffer===!1&&l){const M=F.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[M])}}}function Ut(F){return Math.min(i.maxSamples,F.samples)}function Jt(F){const M=a.get(F);return F.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function K(F){const M=s.render.frame;d.get(F)!==M&&(d.set(F,M),F.update())}function dn(F,M){const ee=F.colorSpace,se=F.format,he=F.type;return F.isCompressedTexture===!0||F.isVideoTexture===!0||ee!==bg&&ee!==Vs&&(Ct.getTransfer(ee)===Ht?(se!==Si||he!==ai)&&it("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ot("WebGLTextures: Unsupported texture color space:",ee)),M}function zt(F){return typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement?(c.width=F.naturalWidth||F.width,c.height=F.naturalHeight||F.height):typeof VideoFrame<"u"&&F instanceof VideoFrame?(c.width=F.displayWidth,c.height=F.displayHeight):(c.width=F.width,c.height=F.height),c}this.allocateTextureUnit=G,this.resetTextureUnits=B,this.getTextureUnits=D,this.setTextureUnits=$,this.setTexture2D=J,this.setTexture2DArray=ne,this.setTexture3D=ae,this.setTextureCube=q,this.rebindTextures=vt,this.setupRenderTarget=Rt,this.updateRenderTargetMipmap=mt,this.updateMultisampleRenderTarget=cn,this.setupDepthRenderbuffer=rt,this.setupFrameBufferTexture=De,this.useMultisampledRTT=Jt,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function LG(t,e){function n(a,i=Vs){let o;const s=Ct.getTransfer(i);if(a===ai)return t.UNSIGNED_BYTE;if(a===Dw)return t.UNSIGNED_SHORT_4_4_4_4;if(a===Ow)return t.UNSIGNED_SHORT_5_5_5_1;if(a===O5)return t.UNSIGNED_INT_5_9_9_9_REV;if(a===$5)return t.UNSIGNED_INT_10F_11F_11F_REV;if(a===z5)return t.BYTE;if(a===D5)return t.SHORT;if(a===zh)return t.UNSIGNED_SHORT;if(a===zw)return t.INT;if(a===fo)return t.UNSIGNED_INT;if(a===mo)return t.FLOAT;if(a===go)return t.HALF_FLOAT;if(a===F5)return t.ALPHA;if(a===U5)return t.RGB;if(a===Si)return t.RGBA;if(a===is)return t.DEPTH_COMPONENT;if(a===ol)return t.DEPTH_STENCIL;if(a===B5)return t.RED;if(a===$w)return t.RED_INTEGER;if(a===sl)return t.RG;if(a===Fw)return t.RG_INTEGER;if(a===Uw)return t.RGBA_INTEGER;if(a===ug||a===fg||a===mg||a===gg)if(s===Ht)if(o=e.get("WEBGL_compressed_texture_s3tc_srgb"),o!==null){if(a===ug)return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(a===fg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(a===mg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(a===gg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(o=e.get("WEBGL_compressed_texture_s3tc"),o!==null){if(a===ug)return o.COMPRESSED_RGB_S3TC_DXT1_EXT;if(a===fg)return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(a===mg)return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(a===gg)return o.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(a===Bw||a===Hw||a===qw||a===Ww)if(o=e.get("WEBGL_compressed_texture_pvrtc"),o!==null){if(a===Bw)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(a===Hw)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(a===qw)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(a===Ww)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(a===Gw||a===Vw||a===jw||a===Yw||a===Xw||a===vg||a===Kw)if(o=e.get("WEBGL_compressed_texture_etc"),o!==null){if(a===Gw||a===Vw)return s===Ht?o.COMPRESSED_SRGB8_ETC2:o.COMPRESSED_RGB8_ETC2;if(a===jw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:o.COMPRESSED_RGBA8_ETC2_EAC;if(a===Yw)return o.COMPRESSED_R11_EAC;if(a===Xw)return o.COMPRESSED_SIGNED_R11_EAC;if(a===vg)return o.COMPRESSED_RG11_EAC;if(a===Kw)return o.COMPRESSED_SIGNED_RG11_EAC}else return null;if(a===Zw||a===Jw||a===Qw||a===e1||a===t1||a===n1||a===a1||a===i1||a===o1||a===s1||a===r1||a===l1||a===c1||a===d1)if(o=e.get("WEBGL_compressed_texture_astc"),o!==null){if(a===Zw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:o.COMPRESSED_RGBA_ASTC_4x4_KHR;if(a===Jw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:o.COMPRESSED_RGBA_ASTC_5x4_KHR;if(a===Qw)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:o.COMPRESSED_RGBA_ASTC_5x5_KHR;if(a===e1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:o.COMPRESSED_RGBA_ASTC_6x5_KHR;if(a===t1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:o.COMPRESSED_RGBA_ASTC_6x6_KHR;if(a===n1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:o.COMPRESSED_RGBA_ASTC_8x5_KHR;if(a===a1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:o.COMPRESSED_RGBA_ASTC_8x6_KHR;if(a===i1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:o.COMPRESSED_RGBA_ASTC_8x8_KHR;if(a===o1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:o.COMPRESSED_RGBA_ASTC_10x5_KHR;if(a===s1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:o.COMPRESSED_RGBA_ASTC_10x6_KHR;if(a===r1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:o.COMPRESSED_RGBA_ASTC_10x8_KHR;if(a===l1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:o.COMPRESSED_RGBA_ASTC_10x10_KHR;if(a===c1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:o.COMPRESSED_RGBA_ASTC_12x10_KHR;if(a===d1)return s===Ht?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:o.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(a===p1||a===h1||a===u1)if(o=e.get("EXT_texture_compression_bptc"),o!==null){if(a===p1)return s===Ht?o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:o.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(a===h1)return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(a===u1)return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(a===f1||a===m1||a===xg||a===g1)if(o=e.get("EXT_texture_compression_rgtc"),o!==null){if(a===f1)return o.COMPRESSED_RED_RGTC1_EXT;if(a===m1)return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(a===xg)return o.COMPRESSED_RED_GREEN_RGTC2_EXT;if(a===g1)return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return a===Dh?t.UNSIGNED_INT_24_8:t[a]!==void 0?t[a]:null}return{convert:n}}const RG=`
|
|
11672
11692
|
void main() {
|
|
11673
11693
|
|
|
11674
11694
|
gl_Position = vec4( position, 1.0 );
|
|
@@ -11692,7 +11712,7 @@ void main() {
|
|
|
11692
11712
|
|
|
11693
11713
|
}
|
|
11694
11714
|
|
|
11695
|
-
}`;class IG{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n){if(this.texture===null){const a=new w_(e.texture);(e.depthNear!==n.depthNear||e.depthFar!==n.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=a}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,a=new na({vertexShader:RG,fragmentShader:PG,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new hs(new Xg(20,20),a)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class NG extends js{constructor(e,n){super();const a=this;let i=null,o=1,s=null,r="local-floor",l=1,c=null,d=null,p=null,h=null,u=null,f=null;const v=typeof XRWebGLBinding<"u",g=new IG,m={},b=n.getContextAttributes();let k=null,y=null;const w=[],A=[],_=new ut;let S=null,T=null;const E=new si;E.viewport=new yn;const P=new si;P.viewport=new yn;const R=[E,P],B=new wq;let D=null,$=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(de){let Z=w[de];return Z===void 0&&(Z=new _1,w[de]=Z),Z.getTargetRaySpace()},this.getControllerGrip=function(de){let Z=w[de];return Z===void 0&&(Z=new _1,w[de]=Z),Z.getGripSpace()},this.getHand=function(de){let Z=w[de];return Z===void 0&&(Z=new _1,w[de]=Z),Z.getHandSpace()};function G(de){const Z=A.indexOf(de.inputSource);if(Z===-1)return;const Ne=w[Z];Ne!==void 0&&(Ne.update(de.inputSource,de.frame,c||s),Ne.dispatchEvent({type:de.type,data:de.inputSource}))}function O(){i.removeEventListener("select",G),i.removeEventListener("selectstart",G),i.removeEventListener("selectend",G),i.removeEventListener("squeeze",G),i.removeEventListener("squeezestart",G),i.removeEventListener("squeezeend",G),i.removeEventListener("end",O),i.removeEventListener("inputsourceschange",J);for(let de=0;de<w.length;de++){const Z=A[de];Z!==null&&(A[de]=null,w[de].disconnect(Z))}D=null,$=null,g.reset();for(const de in m)delete m[de];if(e.setRenderTarget(k),u=null,h=null,p=null,i=null,y=null,st.stop(),a.isPresenting=!1,e.setPixelRatio(S),e.setSize(_.width,_.height,!1),T!==null){const de=T.camera;de.fov=T.fov,de.zoom=T.zoom,de.updateProjectionMatrix(),T=null}a.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(de){o=de,a.isPresenting===!0&&it("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(de){r=de,a.isPresenting===!0&&it("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||s},this.setReferenceSpace=function(de){c=de},this.getBaseLayer=function(){return h!==null?h:u},this.getBinding=function(){return p===null&&v&&(p=new XRWebGLBinding(i,n)),p},this.getFrame=function(){return f},this.getSession=function(){return i},this.setSession=async function(de){if(i=de,i!==null){if(k=e.getRenderTarget(),i.addEventListener("select",G),i.addEventListener("selectstart",G),i.addEventListener("selectend",G),i.addEventListener("squeeze",G),i.addEventListener("squeezestart",G),i.addEventListener("squeezeend",G),i.addEventListener("end",O),i.addEventListener("inputsourceschange",J),b.xrCompatible!==!0&&await n.makeXRCompatible(),S=e.getPixelRatio(),e.getSize(_),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Ne=null,Xe=null,De=null;b.depth&&(De=b.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,Ne=b.stencil?ol:is,Xe=b.stencil?Dh:fo);const be={colorFormat:n.RGBA8,depthFormat:De,scaleFactor:o};p=this.getBinding(),h=p.createProjectionLayer(be),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new Mi(h.textureWidth,h.textureHeight,{format:Si,type:ai,depthTexture:new Vh(h.textureWidth,h.textureHeight,Xe,void 0,void 0,void 0,void 0,void 0,void 0,Ne),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1,storeMultisampledDepthBuffer:h.ignoreDepthValues===!1,storeMultisampledStencilBuffer:h.ignoreDepthValues===!1})}else{const Ne={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:o};u=new XRWebGLLayer(i,n,Ne),i.updateRenderState({baseLayer:u}),e.setPixelRatio(1),e.setSize(u.framebufferWidth,u.framebufferHeight,!1),y=new Mi(u.framebufferWidth,u.framebufferHeight,{format:Si,type:ai,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,storeMultisampledDepthBuffer:u.ignoreDepthValues===!1,storeMultisampledStencilBuffer:u.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(l),c=null,s=await i.requestReferenceSpace(r),st.setContext(i),st.start(),a.isPresenting=!0,a.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function J(de){for(let Z=0;Z<de.removed.length;Z++){const Ne=de.removed[Z],Xe=A.indexOf(Ne);Xe>=0&&(A[Xe]=null,w[Xe].disconnect(Ne))}for(let Z=0;Z<de.added.length;Z++){const Ne=de.added[Z];let Xe=A.indexOf(Ne);if(Xe===-1){for(let be=0;be<w.length;be++)if(be>=A.length){A.push(Ne),Xe=be;break}else if(A[be]===null){A[be]=Ne,Xe=be;break}if(Xe===-1)break}const De=w[Xe];De&&De.connect(Ne)}}const ne=new Q,ae=new Q;function q(de,Z,Ne){ne.setFromMatrixPosition(Z.matrixWorld),ae.setFromMatrixPosition(Ne.matrixWorld);const Xe=ne.distanceTo(ae),De=Z.projectionMatrix.elements,be=Ne.projectionMatrix.elements,ft=De[14]/(De[10]-1),rt=De[14]/(De[10]+1),vt=(De[9]+1)/De[5],Rt=(De[9]-1)/De[5],mt=(De[8]-1)/De[0],Gt=(be[8]+1)/be[0],rn=ft*mt,ln=ft*Gt,Ut=Xe/(-mt+Gt),Jt=Ut*-mt;if(Z.matrixWorld.decompose(de.position,de.quaternion,de.scale),de.translateX(Jt),de.translateZ(Ut),de.matrixWorld.compose(de.position,de.quaternion,de.scale),de.matrixWorldInverse.copy(de.matrixWorld).invert(),De[10]===-1)de.projectionMatrix.copy(Z.projectionMatrix),de.projectionMatrixInverse.copy(Z.projectionMatrixInverse);else{const K=ft+Ut,cn=rt+Ut,zt=rn-Jt,F=ln+(Xe-Jt),M=vt*rt/cn*K,ee=Rt*rt/cn*K;de.projectionMatrix.makePerspective(zt,F,M,ee,K,cn),de.projectionMatrixInverse.copy(de.projectionMatrix).invert()}}function we(de,Z){Z===null?de.matrixWorld.copy(de.matrix):de.matrixWorld.multiplyMatrices(Z.matrixWorld,de.matrix),de.matrixWorldInverse.copy(de.matrixWorld).invert()}this.updateCamera=function(de){if(i===null)return;let Z=de.near,Ne=de.far;g.texture!==null&&(g.depthNear>0&&(Z=g.depthNear),g.depthFar>0&&(Ne=g.depthFar)),B.near=P.near=E.near=Z,B.far=P.far=E.far=Ne,(D!==B.near||$!==B.far)&&(i.updateRenderState({depthNear:B.near,depthFar:B.far}),D=B.near,$=B.far),B.layers.mask=de.layers.mask|6,E.layers.mask=B.layers.mask&-5,P.layers.mask=B.layers.mask&-3;const Xe=de.parent,De=B.cameras;we(B,Xe);for(let be=0;be<De.length;be++)we(De[be],Xe);De.length===2?q(B,E,P):B.projectionMatrix.copy(E.projectionMatrix),T===null&&de.isPerspectiveCamera&&(T={camera:de,fov:de.fov,zoom:de.zoom}),Re(de,B,Xe)};function Re(de,Z,Ne){Ne===null?de.matrix.copy(Z.matrixWorld):(de.matrix.copy(Ne.matrixWorld),de.matrix.invert(),de.matrix.multiply(Z.matrixWorld)),de.matrix.decompose(de.position,de.quaternion,de.scale),de.updateMatrixWorld(!0),de.projectionMatrix.copy(Z.projectionMatrix),de.projectionMatrixInverse.copy(Z.projectionMatrixInverse),de.isPerspectiveCamera&&(de.fov=y1*2*Math.atan(1/de.projectionMatrix.elements[5]),de.zoom=1)}this.getCamera=function(){return B},this.getFoveation=function(){if(!(h===null&&u===null))return l},this.setFoveation=function(de){l=de,h!==null&&(h.fixedFoveation=de),u!==null&&u.fixedFoveation!==void 0&&(u.fixedFoveation=de)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(B)},this.getCameraTexture=function(de){return m[de]};let ot=null;function Qe(de,Z){if(d=Z.getViewerPose(c||s),f=Z,d!==null){const Ne=d.views;u!==null&&(e.setRenderTargetFramebuffer(y,u.framebuffer),e.setRenderTarget(y));let Xe=!1;Ne.length!==B.cameras.length&&(B.cameras.length=0,Xe=!0);for(let rt=0;rt<Ne.length;rt++){const vt=Ne[rt];let Rt=null;if(u!==null)Rt=u.getViewport(vt);else{const Gt=p.getViewSubImage(h,vt);Rt=Gt.viewport,rt===0&&(e.setRenderTargetTextures(y,Gt.colorTexture,Gt.depthStencilTexture),e.setRenderTarget(y))}let mt=R[rt];mt===void 0&&(mt=new si,mt.layers.enable(rt),mt.viewport=new yn,R[rt]=mt),mt.matrix.fromArray(vt.transform.matrix),mt.matrix.decompose(mt.position,mt.quaternion,mt.scale),mt.projectionMatrix.fromArray(vt.projectionMatrix),mt.projectionMatrixInverse.copy(mt.projectionMatrix).invert(),mt.viewport.set(Rt.x,Rt.y,Rt.width,Rt.height),rt===0&&(B.matrix.copy(mt.matrix),B.matrix.decompose(B.position,B.quaternion,B.scale)),Xe===!0&&B.cameras.push(mt)}const De=i.enabledFeatures;if(De&&De.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&v){p=a.getBinding();const rt=p.getDepthInformation(Ne[0]);rt&&rt.isValid&&rt.texture&&g.init(rt,i.renderState)}if(De&&De.includes("camera-access")&&v){e.state.unbindTexture(),p=a.getBinding();for(let rt=0;rt<Ne.length;rt++){const vt=Ne[rt].camera;if(vt){let Rt=m[vt];Rt||(Rt=new w_,m[vt]=Rt);const mt=p.getCameraImage(vt);Rt.sourceTexture=mt}}}}for(let Ne=0;Ne<w.length;Ne++){const Xe=A[Ne],De=w[Ne];Xe!==null&&De!==void 0&&De.update(Xe,Z,c||s)}ot&&ot(de,Z),Z.detectedPlanes&&a.dispatchEvent({type:"planesdetected",data:Z}),f=null}const st=new R_;st.setAnimationLoop(Qe),this.setAnimationLoop=function(de){ot=de},this.dispose=function(){}}}const zG=new fn,sC=new ht;sC.set(-1,0,0,0,1,0,0,0,1);function DG(t,e){function n(g,m){g.matrixAutoUpdate===!0&&g.updateMatrix(),m.value.copy(g.matrix)}function a(g,m){m.color.getRGB(g.fogColor.value,S_(t)),m.isFog?(g.fogNear.value=m.near,g.fogFar.value=m.far):m.isFogExp2&&(g.fogDensity.value=m.density)}function i(g,m,b,k,y){m.isNodeMaterial?m.uniformsNeedUpdate=!1:m.isMeshBasicMaterial?o(g,m):m.isMeshLambertMaterial?(o(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshToonMaterial?(o(g,m),p(g,m)):m.isMeshPhongMaterial?(o(g,m),d(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshStandardMaterial?(o(g,m),h(g,m),m.isMeshPhysicalMaterial&&u(g,m,y)):m.isMeshMatcapMaterial?(o(g,m),f(g,m)):m.isMeshDepthMaterial?o(g,m):m.isMeshDistanceMaterial?(o(g,m),v(g,m)):m.isMeshNormalMaterial?o(g,m):m.isLineBasicMaterial?(s(g,m),m.isLineDashedMaterial&&r(g,m)):m.isPointsMaterial?l(g,m,b,k):m.isSpriteMaterial?c(g,m):m.isShadowMaterial?(g.color.value.copy(m.color),g.opacity.value=m.opacity):m.isShaderMaterial&&(m.uniformsNeedUpdate=!1)}function o(g,m){g.opacity.value=m.opacity,m.color&&g.diffuse.value.copy(m.color),m.emissive&&g.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity),m.map&&(g.map.value=m.map,n(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,n(m.alphaMap,g.alphaMapTransform)),m.bumpMap&&(g.bumpMap.value=m.bumpMap,n(m.bumpMap,g.bumpMapTransform),g.bumpScale.value=m.bumpScale,m.side===Ea&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,n(m.normalMap,g.normalMapTransform),g.normalScale.value.copy(m.normalScale),m.side===Ea&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,n(m.displacementMap,g.displacementMapTransform),g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias),m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap,n(m.emissiveMap,g.emissiveMapTransform)),m.specularMap&&(g.specularMap.value=m.specularMap,n(m.specularMap,g.specularMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest);const b=e.get(m),k=b.envMap,y=b.envMapRotation;k&&(g.envMap.value=k,g.envMapRotation.value.setFromMatrix4(zG.makeRotationFromEuler(y)).transpose(),k.isCubeTexture&&k.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(sC),g.reflectivity.value=m.reflectivity,g.ior.value=m.ior,g.refractionRatio.value=m.refractionRatio),m.lightMap&&(g.lightMap.value=m.lightMap,g.lightMapIntensity.value=m.lightMapIntensity,n(m.lightMap,g.lightMapTransform)),m.aoMap&&(g.aoMap.value=m.aoMap,g.aoMapIntensity.value=m.aoMapIntensity,n(m.aoMap,g.aoMapTransform))}function s(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,m.map&&(g.map.value=m.map,n(m.map,g.mapTransform))}function r(g,m){g.dashSize.value=m.dashSize,g.totalSize.value=m.dashSize+m.gapSize,g.scale.value=m.scale}function l(g,m,b,k){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.size.value=m.size*b,g.scale.value=k*.5,m.map&&(g.map.value=m.map,n(m.map,g.uvTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,n(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function c(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.rotation.value=m.rotation,m.map&&(g.map.value=m.map,n(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,n(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function d(g,m){g.specular.value.copy(m.specular),g.shininess.value=Math.max(m.shininess,1e-4)}function p(g,m){m.gradientMap&&(g.gradientMap.value=m.gradientMap)}function h(g,m){g.metalness.value=m.metalness,m.metalnessMap&&(g.metalnessMap.value=m.metalnessMap,n(m.metalnessMap,g.metalnessMapTransform)),g.roughness.value=m.roughness,m.roughnessMap&&(g.roughnessMap.value=m.roughnessMap,n(m.roughnessMap,g.roughnessMapTransform)),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)}function u(g,m,b){g.ior.value=m.ior,m.sheen>0&&(g.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),g.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(g.sheenColorMap.value=m.sheenColorMap,n(m.sheenColorMap,g.sheenColorMapTransform)),m.sheenRoughnessMap&&(g.sheenRoughnessMap.value=m.sheenRoughnessMap,n(m.sheenRoughnessMap,g.sheenRoughnessMapTransform))),m.clearcoat>0&&(g.clearcoat.value=m.clearcoat,g.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(g.clearcoatMap.value=m.clearcoatMap,n(m.clearcoatMap,g.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,n(m.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(g.clearcoatNormalMap.value=m.clearcoatNormalMap,n(m.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===Ea&&g.clearcoatNormalScale.value.negate())),m.dispersion>0&&(g.dispersion.value=m.dispersion),m.retroreflectivity>0&&(g.retroreflectivity.value=m.retroreflectivity),m.iridescence>0&&(g.iridescence.value=m.iridescence,g.iridescenceIOR.value=m.iridescenceIOR,g.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(g.iridescenceMap.value=m.iridescenceMap,n(m.iridescenceMap,g.iridescenceMapTransform)),m.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=m.iridescenceThicknessMap,n(m.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),m.transmission>0&&(g.transmission.value=m.transmission,g.transmissionSamplerMap.value=b.texture,g.transmissionSamplerSize.value.set(b.width,b.height),m.transmissionMap&&(g.transmissionMap.value=m.transmissionMap,n(m.transmissionMap,g.transmissionMapTransform)),g.thickness.value=m.thickness,m.thicknessMap&&(g.thicknessMap.value=m.thicknessMap,n(m.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=m.attenuationDistance,g.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(g.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(g.anisotropyMap.value=m.anisotropyMap,n(m.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=m.specularIntensity,g.specularColor.value.copy(m.specularColor),m.specularColorMap&&(g.specularColorMap.value=m.specularColorMap,n(m.specularColorMap,g.specularColorMapTransform)),m.specularIntensityMap&&(g.specularIntensityMap.value=m.specularIntensityMap,n(m.specularIntensityMap,g.specularIntensityMapTransform))}function f(g,m){m.matcap&&(g.matcap.value=m.matcap)}function v(g,m){const b=e.get(m).light;g.referencePosition.value.setFromMatrixPosition(b.matrixWorld),g.nearDistance.value=b.shadow.camera.near,g.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:a,refreshMaterialUniforms:i}}function OG(t,e,n,a){let i={},o={},s=[];const r=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function l(y,w){const A=w.program;a.uniformBlockBinding(y,A)}function c(y,w){let A=i[y.id];A===void 0&&(g(y),A=d(y),i[y.id]=A,y.addEventListener("dispose",b));const _=w.program;a.updateUBOMapping(y,_);const S=e.render.frame;o[y.id]!==S&&(h(y),o[y.id]=S)}function d(y){const w=p();y.__bindingPointIndex=w;const A=t.createBuffer(),_=y.__size,S=y.usage;return t.bindBuffer(t.UNIFORM_BUFFER,A),t.bufferData(t.UNIFORM_BUFFER,_,S),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,w,A),A}function p(){for(let y=0;y<r;y++)if(s.indexOf(y)===-1)return s.push(y),y;return Ot("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(y){const w=i[y.id],A=y.uniforms,_=y.__cache;t.bindBuffer(t.UNIFORM_BUFFER,w);for(let S=0,T=A.length;S<T;S++){const E=A[S];if(Array.isArray(E))for(let P=0,R=E.length;P<R;P++)u(E[P],S,P,_);else u(E,S,0,_)}t.bindBuffer(t.UNIFORM_BUFFER,null)}function u(y,w,A,_){if(v(y,w,A,_)===!0){const S=y.__offset,T=y.value;if(Array.isArray(T)){let E=0;for(let P=0;P<T.length;P++){const R=T[P],B=m(R);f(R,y.__data,E),typeof R!="number"&&typeof R!="boolean"&&!R.isMatrix3&&!ArrayBuffer.isView(R)&&(E+=B.storage/Float32Array.BYTES_PER_ELEMENT)}}else f(T,y.__data,0);t.bufferSubData(t.UNIFORM_BUFFER,S,y.__data)}}function f(y,w,A){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,A)}function v(y,w,A,_){const S=y.value,T=w+"_"+A;if(_[T]===void 0)return typeof S=="number"||typeof S=="boolean"?_[T]=S:ArrayBuffer.isView(S)?_[T]=S.slice():_[T]=S.clone(),!0;{const E=_[T];if(typeof S=="number"||typeof S=="boolean"){if(E!==S)return _[T]=S,!0}else{if(ArrayBuffer.isView(S))return!0;if(E.equals(S)===!1)return E.copy(S),!0}}return!1}function g(y){const w=y.uniforms;let A=0;const _=16;for(let T=0,E=w.length;T<E;T++){const P=Array.isArray(w[T])?w[T]:[w[T]];for(let R=0,B=P.length;R<B;R++){const D=P[R],$=Array.isArray(D.value)?D.value:[D.value];for(let G=0,O=$.length;G<O;G++){const J=$[G],ne=m(J),ae=A%_,q=ae%ne.boundary,we=ae+q;A+=q,we!==0&&_-we<ne.storage&&(A+=_-we),D.__data=new Float32Array(ne.storage/Float32Array.BYTES_PER_ELEMENT),D.__offset=A,A+=ne.storage}}}const S=A%_;return S>0&&(A+=_-S),y.__size=A,y.__cache={},this}function m(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?it("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):it("WebGLRenderer: Unsupported uniform value type.",y),w}function b(y){const w=y.target;w.removeEventListener("dispose",b);const A=s.indexOf(w.__bindingPointIndex);s.splice(A,1),t.deleteBuffer(i[w.id]),delete i[w.id],delete o[w.id]}function k(){for(const y in i)t.deleteBuffer(i[y]);s=[],i={},o={}}return{bind:l,update:c,dispose:k}}const $G=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let wo=null;function FG(){return wo===null&&(wo=new rq($G,16,16,sl,go),wo.name="DFG_LUT",wo.minFilter=Qn,wo.magFilter=Qn,wo.wrapS=as,wo.wrapT=as,wo.generateMipmaps=!1,wo.needsUpdate=!0),wo}class UG{constructor(e={}){const{canvas:n=zH(),context:a=null,depth:i=!0,stencil:o=!1,alpha:s=!1,antialias:r=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:p=!1,reversedDepthBuffer:h=!1,outputBufferType:u=ai}=e;this.isWebGLRenderer=!0;let f;if(a!==null){if(typeof WebGLRenderingContext<"u"&&a instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=a.getContextAttributes().alpha}else f=s;const v=u,g=new Set([Uw,Fw,$w]),m=new Set([ai,fo,zh,Dh,Dw,Ow]),b=new Uint32Array(4),k=new Int32Array(4),y=new Q;let w=null,A=null;const _=[],S=[];let T=null;this.domElement=n,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=uo,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let P=!1,R=null,B=null,D=null,$=null;this._outputColorSpace=ii;let G=0,O=0,J=null,ne=-1,ae=null;const q=new yn,we=new yn;let Re=null;const ot=new $t(0);let Qe=0,st=n.width,de=n.height,Z=1,Ne=null,Xe=null;const De=new yn(0,0,st,de),be=new yn(0,0,st,de);let ft=!1;const rt=new u_;let vt=!1,Rt=!1;const mt=new fn,Gt=new Q,rn=new yn,ln={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ut=!1;function Jt(){return J===null?Z:1}let K=a;function cn(L,X){return n.getContext(L,X)}let zt,F,M,ee,se,he,Le,ze,ge,z,j,ce,I,U,Y,pe,Ie,W,_e,fe,Me,Pe,ke;try{const L={alpha:!0,depth:i,stencil:o,antialias:r,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:d,failIfMajorPerformanceCaveat:p};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${kw}`),n.addEventListener("webglcontextlost",at,!1),n.addEventListener("webglcontextrestored",dt,!1),n.addEventListener("webglcontextcreationerror",va,!1),K===null){const X="webgl2";if(K=cn(X,L),K===null)throw cn(X)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}Ce()}catch(L){throw n.removeEventListener("webglcontextlost",at,!1),n.removeEventListener("webglcontextrestored",dt,!1),n.removeEventListener("webglcontextcreationerror",va,!1),Ot("WebGLRenderer: "+L.message),L}function Ce(){zt=new F7(K),zt.init(),Me=new LG(K,zt),F=new C7(K,zt,e,Me),M=new _G(K,zt),F.reversedDepthBuffer&&h&&M.buffers.depth.setReversed(!0),B=K.createFramebuffer(),D=K.createFramebuffer(),$=K.createFramebuffer(),ee=new H7(K),se=new fG,he=new CG(K,zt,M,se,F,Me,ee),Le=new $7(E),ze=new Mq(K),Pe=new E7(K,ze),ge=new U7(K,ze,ee,Pe),z=new W7(K,ge,ze,Pe,ee),W=new q7(K,F,he),Y=new L7(se),j=new uG(E,Le,zt,F,Pe,Y),ce=new DG(E,se),I=new gG,U=new kG(zt),Ie=new T7(E,Le,M,z,f,l),pe=new EG(E,z,F),ke=new OG(K,ee,F,M),_e=new _7(K,zt,ee),fe=new B7(K,zt,ee),ee.programs=j.programs,E.capabilities=F,E.extensions=zt,E.properties=se,E.renderLists=I,E.shadowMap=pe,E.state=M,E.info=ee}v!==ai&&(T=new V7(v,n.width,n.height,r,i,o));const Ee=new NG(E,K);this.xr=Ee,this.getContext=function(){return K},this.getContextAttributes=function(){return K.getContextAttributes()},this.forceContextLoss=function(){const L=zt.get("WEBGL_lose_context");L&&L.loseContext()},this.forceContextRestore=function(){const L=zt.get("WEBGL_lose_context");L&&L.restoreContext()},this.getPixelRatio=function(){return Z},this.setPixelRatio=function(L){L!==void 0&&(Z=L,this.setSize(st,de,!1))},this.getSize=function(L){return L.set(st,de)},this.setSize=function(L,X,le=!0){if(Ee.isPresenting){it("WebGLRenderer: Can't change size while VR device is presenting.");return}st=L,de=X,n.width=Math.floor(L*Z),n.height=Math.floor(X*Z),le===!0&&(n.style.width=L+"px",n.style.height=X+"px"),T!==null&&T.setSize(n.width,n.height),this.setViewport(0,0,L,X)},this.getDrawingBufferSize=function(L){return L.set(st*Z,de*Z).floor()},this.setDrawingBufferSize=function(L,X,le){st=L,de=X,Z=le,n.width=Math.floor(L*le),n.height=Math.floor(X*le),this.setViewport(0,0,L,X)},this.setEffects=function(L){if(v===ai){Ot("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(L){for(let X=0;X<L.length;X++)if(L[X].isOutputPass===!0){it("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}T.setEffects(L||[])},this.getCurrentViewport=function(L){return L.copy(q)},this.getViewport=function(L){return L.copy(De)},this.setViewport=function(L,X,le,ie){L.isVector4?De.set(L.x,L.y,L.z,L.w):De.set(L,X,le,ie),M.viewport(q.copy(De).multiplyScalar(Z).round())},this.getScissor=function(L){return L.copy(be)},this.setScissor=function(L,X,le,ie){L.isVector4?be.set(L.x,L.y,L.z,L.w):be.set(L,X,le,ie),M.scissor(we.copy(be).multiplyScalar(Z).round())},this.getScissorTest=function(){return ft},this.setScissorTest=function(L){M.setScissorTest(ft=L)},this.setOpaqueSort=function(L){Ne=L},this.setTransparentSort=function(L){Xe=L},this.getClearColor=function(L){return L.copy(Ie.getClearColor())},this.setClearColor=function(){Ie.setClearColor(...arguments)},this.getClearAlpha=function(){return Ie.getClearAlpha()},this.setClearAlpha=function(){Ie.setClearAlpha(...arguments)},this.clear=function(L=!0,X=!0,le=!0){let ie=0;if(L){let oe=!1;if(J!==null){const He=J.texture.format;oe=g.has(He)}if(oe){const He=J.texture.type,Ye=m.has(He),Fe=Ie.getClearColor(),Ke=Ie.getClearAlpha(),et=Fe.r,yt=Fe.g,Mt=Fe.b;Ye?(b[0]=et,b[1]=yt,b[2]=Mt,b[3]=Ke,K.clearBufferuiv(K.COLOR,0,b)):(k[0]=et,k[1]=yt,k[2]=Mt,k[3]=Ke,K.clearBufferiv(K.COLOR,0,k))}else ie|=K.COLOR_BUFFER_BIT}X&&(ie|=K.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),le&&(ie|=K.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),ie!==0&&K.clear(ie)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(L){L.setRenderer(this),R=L},this.dispose=function(){n.removeEventListener("webglcontextlost",at,!1),n.removeEventListener("webglcontextrestored",dt,!1),n.removeEventListener("webglcontextcreationerror",va,!1),Ie.dispose(),I.dispose(),U.dispose(),se.dispose(),Le.dispose(),z.dispose(),Pe.dispose(),ke.dispose(),j.dispose(),Ee.dispose(),Ee.removeEventListener("sessionstart",_6),Ee.removeEventListener("sessionend",C6),yl.stop()};function at(L){L.preventDefault(),G5("WebGLRenderer: Context Lost."),P=!0}function dt(){G5("WebGLRenderer: Context Restored."),P=!1;const L=ee.autoReset,X=pe.enabled,le=pe.autoUpdate,ie=pe.needsUpdate,oe=pe.type;Ce(),ee.autoReset=L,pe.enabled=X,pe.autoUpdate=le,pe.needsUpdate=ie,pe.type=oe}function va(L){Ot("WebGLRenderer: A WebGL context could not be created. Reason: ",L.statusMessage)}function Ao(L){const X=L.target;X.removeEventListener("dispose",Ao),yX(X)}function yX(L){wX(L),se.remove(L)}function wX(L){const X=se.get(L).programs;X!==void 0&&(X.forEach(function(le){j.releaseProgram(le)}),L.isShaderMaterial&&j.releaseShaderCache(L))}this.renderBufferDirect=function(L,X,le,ie,oe,He){X===null&&(X=ln);const Ye=oe.isMesh&&oe.matrixWorld.determinantAffine()<0,Fe=MX(L,X,le,ie,oe);M.setMaterial(ie,Ye);let Ke=le.index,et=1;if(ie.wireframe===!0){if(Ke=ge.getWireframeAttribute(le),Ke===void 0)return;et=2}const yt=le.drawRange,Mt=le.attributes.position;let Ze=yt.start*et,Bt=(yt.start+yt.count)*et;He!==null&&(Ze=Math.max(Ze,He.start*et),Bt=Math.min(Bt,(He.start+He.count)*et)),Ke!==null?(Ze=Math.max(Ze,0),Bt=Math.min(Bt,Ke.count)):Mt!=null&&(Ze=Math.max(Ze,0),Bt=Math.min(Bt,Mt.count));const Rn=Bt-Ze;if(Rn<0||Rn===1/0)return;Pe.setup(oe,ie,Fe,le,Ke);let on,Kt=_e;if(Ke!==null&&(on=ze.get(Ke),Kt=fe,Kt.setIndex(on)),oe.isMesh)ie.wireframe===!0?(M.setLineWidth(ie.wireframeLinewidth*Jt()),Kt.setMode(K.LINES)):Kt.setMode(K.TRIANGLES);else if(oe.isLine){let oa=ie.linewidth;oa===void 0&&(oa=1),M.setLineWidth(oa*Jt()),oe.isLineSegments?Kt.setMode(K.LINES):oe.isLineLoop?Kt.setMode(K.LINE_LOOP):Kt.setMode(K.LINE_STRIP)}else oe.isPoints?Kt.setMode(K.POINTS):oe.isSprite&&Kt.setMode(K.TRIANGLES);if(oe.isBatchedMesh)if(zt.get("WEBGL_multi_draw"))Kt.renderMultiDraw(oe._multiDrawStarts,oe._multiDrawCounts,oe._multiDrawCount);else{const oa=oe._multiDrawStarts,je=oe._multiDrawCounts,xa=oe._multiDrawCount,Dt=Ke?ze.get(Ke).bytesPerElement:1,li=se.get(ie).currentProgram.getUniforms();for(let To=0;To<xa;To++)li.setValue(K,"_gl_DrawID",To),Kt.render(oa[To]/Dt,je[To])}else if(oe.isInstancedMesh)Kt.renderInstances(Ze,Rn,oe.count);else if(le.isInstancedBufferGeometry){const oa=le._maxInstanceCount!==void 0?le._maxInstanceCount:1/0,je=Math.min(le.instanceCount,oa);Kt.renderInstances(Ze,Rn,je)}else Kt.render(Ze,Rn)};function E6(L,X,le,ie){R!==null&&L.isNodeMaterial&&R.setObject(ie,L),vt===!0&&Y.setState(L,le,!1),L.transparent===!0&&L.side===es&&L.forceSinglePass===!1?(L.side=Ea,L.needsUpdate=!0,Pv(L,X,ie),L.side=nl,L.needsUpdate=!0,Pv(L,X,ie),L.side=es):Pv(L,X,ie)}this.compile=function(L,X,le=null){le===null&&(le=L),R!==null&&R.renderStart(L,X,le),A=U.get(le),A.init(X),S.push(A),le.traverseVisible(function(oe){oe.isLight&&oe.layers.test(X.layers)&&(A.pushLight(oe),oe.castShadow&&A.pushShadow(oe))}),L!==le&&L.traverseVisible(function(oe){oe.isLight&&oe.layers.test(X.layers)&&(A.pushLight(oe),oe.castShadow&&A.pushShadow(oe))}),A.setupLights(),R!==null&&R.updateLights(A.state.lightsArray),Rt=this.localClippingEnabled,vt=Y.init(this.clippingPlanes,Rt),vt===!0&&Y.setGlobalState(this.clippingPlanes,X),R!==null&&pe.render(A.state.shadowsArray,le,X);const ie=new Set;return L.traverse(function(oe){if(!(oe.isMesh||oe.isPoints||oe.isLine||oe.isSprite))return;const He=oe.material;if(He)if(Array.isArray(He))for(let Ye=0;Ye<He.length;Ye++){const Fe=He[Ye];E6(Fe,le,X,oe),ie.add(Fe)}else E6(He,le,X,oe),ie.add(He)}),A=S.pop(),R!==null&&R.renderEnd(),ie},this.compileAsync=function(L,X,le=null){const ie=this.compile(L,X,le);return new Promise(oe=>{function He(){if(ie.forEach(function(Ye){const Ke=se.get(Ye).currentProgram;(Ke===void 0||Ke.isReady())&&ie.delete(Ye)}),ie.size===0){oe(L);return}setTimeout(He,10)}zt.get("KHR_parallel_shader_compile")!==null?He():setTimeout(He,10)})};let Kk=null;function kX(L){Kk&&Kk(L)}function _6(){yl.stop()}function C6(){yl.start()}const yl=new R_;yl.setAnimationLoop(kX),typeof self<"u"&&yl.setContext(self),this.setAnimationLoop=function(L){Kk=L,Ee.setAnimationLoop(L),L===null?yl.stop():yl.start()},Ee.addEventListener("sessionstart",_6),Ee.addEventListener("sessionend",C6),this.render=function(L,X){if(X!==void 0&&X.isCamera!==!0){Ot("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(P===!0)return;R!==null&&R.renderStart(L,X);const le=Ee.enabled===!0&&Ee.isPresenting===!0,ie=T!==null&&(J===null||le)&&T.begin(E,J);if(L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),X.parent===null&&X.matrixWorldAutoUpdate===!0&&X.updateMatrixWorld(),Ee.enabled===!0&&Ee.isPresenting===!0&&(T===null||T.isCompositing()===!1)&&(Ee.cameraAutoUpdate===!0&&Ee.updateCamera(X),X=Ee.getCamera()),L.isScene===!0&&L.onBeforeRender(E,L,X,J),A=U.get(L,S.length),A.init(X),A.state.textureUnits=he.getTextureUnits(),S.push(A),mt.multiplyMatrices(X.projectionMatrix,X.matrixWorldInverse),rt.setFromProjectionMatrix(mt,vo,X.reversedDepth),Rt=this.localClippingEnabled,vt=Y.init(this.clippingPlanes,Rt),w=I.get(L,_.length),w.init(),_.push(w),Ee.enabled===!0&&Ee.isPresenting===!0){const Ye=E.xr.getDepthSensingMesh();Ye!==null&&Zk(Ye,X,-1/0,E.sortObjects)}Zk(L,X,0,E.sortObjects),w.finish(),R!==null&&R.updateLights(A.state.lightsArray),E.sortObjects===!0&&w.sort(Ne,Xe),Ut=Ee.enabled===!1||Ee.isPresenting===!1||Ee.hasDepthSensing()===!1,Ut&&Ie.addToRenderList(w,L),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),vt===!0&&Y.beginShadows();const oe=A.state.shadowsArray;if(pe.render(oe,L,X),vt===!0&&Y.endShadows(),(ie&&T.hasRenderPass())===!1){const Ye=w.opaque,Fe=w.transmissive;if(A.setupLights(),X.isArrayCamera){const Ke=X.cameras;if(Fe.length>0)for(let et=0,yt=Ke.length;et<yt;et++){const Mt=Ke[et];R6(Ye,Fe,L,Mt)}Ut&&Ie.render(L);for(let et=0,yt=Ke.length;et<yt;et++){const Mt=Ke[et];L6(w,L,Mt,Mt.viewport)}}else Fe.length>0&&R6(Ye,Fe,L,X),Ut&&Ie.render(L),L6(w,L,X)}J!==null&&O===0&&(he.updateMultisampleRenderTarget(J),he.updateRenderTargetMipmap(J)),ie&&T.end(E),L.isScene===!0&&L.onAfterRender(E,L,X),Pe.resetDefaultState(),ne=-1,ae=null,S.pop(),S.length>0?(A=S[S.length-1],he.setTextureUnits(A.state.textureUnits),vt===!0&&Y.setGlobalState(E.clippingPlanes,A.state.camera)):A=null,_.pop(),_.length>0?w=_[_.length-1]:w=null,R!==null&&R.renderEnd()};function Zk(L,X,le,ie){if(L.visible===!1)return;if(L.layers.test(X.layers)){if(L.isGroup)le=L.renderOrder;else if(L.isLOD)L.autoUpdate===!0&&L.update(X);else if(L.isLightProbeGrid)A.pushLightProbeGrid(L);else if(L.isLight)A.pushLight(L),L.castShadow&&A.pushShadow(L);else if(L.isSprite){if(!L.frustumCulled||L.intersectsFrustum(rt)){ie&&rn.setFromMatrixPosition(L.matrixWorld).applyMatrix4(mt);const Ye=z.update(L),Fe=L.material;Fe.visible&&w.push(L,Ye,Fe,le,rn.z,null,X)}}else if((L.isMesh||L.isLine||L.isPoints)&&(!L.frustumCulled||L.intersectsFrustum(rt))){const Ye=z.update(L),Fe=L.material;if(ie&&(L.boundingSphere!==void 0?(L.boundingSphere===null&&L.computeBoundingSphere(),rn.copy(L.boundingSphere.center)):(Ye.boundingSphere===null&&Ye.computeBoundingSphere(),rn.copy(Ye.boundingSphere.center)),rn.applyMatrix4(L.matrixWorld).applyMatrix4(mt)),Array.isArray(Fe)){const Ke=Ye.groups;for(let et=0,yt=Ke.length;et<yt;et++){const Mt=Ke[et],Ze=Fe[Mt.materialIndex];Ze&&Ze.visible&&w.push(L,Ye,Ze,le,rn.z,Mt,X)}}else Fe.visible&&w.push(L,Ye,Fe,le,rn.z,null,X)}}const He=L.children;for(let Ye=0,Fe=He.length;Ye<Fe;Ye++)Zk(He[Ye],X,le,ie)}function L6(L,X,le,ie){const{opaque:oe,transmissive:He,transparent:Ye}=L;A.setupLightsView(le),vt===!0&&Y.setGlobalState(E.clippingPlanes,le),ie&&M.viewport(q.copy(ie)),oe.length>0&&Rv(oe,X,le),He.length>0&&Rv(He,X,le),Ye.length>0&&Rv(Ye,X,le),M.buffers.depth.setTest(!0),M.buffers.depth.setMask(!0),M.buffers.color.setMask(!0),M.setPolygonOffset(!1)}function R6(L,X,le,ie){if((le.isScene===!0?le.overrideMaterial:null)!==null)return;if(A.state.transmissionRenderTarget[ie.id]===void 0){const Ze=zt.has("EXT_color_buffer_half_float")||zt.has("EXT_color_buffer_float");A.state.transmissionRenderTarget[ie.id]=new Mi(1,1,{generateMipmaps:!0,type:Ze?go:ai,minFilter:il,samples:Math.max(4,F.samples),stencilBuffer:o,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Ct.workingColorSpace})}const He=A.state.transmissionRenderTarget[ie.id],Ye=ie.viewport||q;He.setSize(Ye.z*E.transmissionResolutionScale,Ye.w*E.transmissionResolutionScale);const Fe=E.getRenderTarget(),Ke=E.getActiveCubeFace(),et=E.getActiveMipmapLevel();E.setRenderTarget(He),E.getClearColor(ot),Qe=E.getClearAlpha(),Qe<1&&E.setClearColor(16777215,.5),E.clear(),Ut&&Ie.render(le);const yt=E.toneMapping;E.toneMapping=uo;const Mt=ie.viewport;if(ie.viewport!==void 0&&(ie.viewport=void 0),A.setupLightsView(ie),vt===!0&&Y.setGlobalState(E.clippingPlanes,ie),Rv(L,le,ie),he.updateMultisampleRenderTarget(He),he.updateRenderTargetMipmap(He),zt.has("WEBGL_multisampled_render_to_texture")===!1){let Ze=!1;for(let Bt=0,Rn=X.length;Bt<Rn;Bt++){const on=X[Bt],{object:Kt,geometry:oa,material:je,group:xa}=on;if(je.side===es&&Kt.layers.test(ie.layers)){const Dt=je.side;je.side=Ea,je.needsUpdate=!0,P6(Kt,le,ie,oa,je,xa),je.side=Dt,je.needsUpdate=!0,Ze=!0}}Ze===!0&&(he.updateMultisampleRenderTarget(He),he.updateRenderTargetMipmap(He))}E.setRenderTarget(Fe,Ke,et),E.setClearColor(ot,Qe),Mt!==void 0&&(ie.viewport=Mt),E.toneMapping=yt}function Rv(L,X,le){const ie=X.isScene===!0?X.overrideMaterial:null;for(let oe=0,He=L.length;oe<He;oe++){const Ye=L[oe],{object:Fe,geometry:Ke,group:et}=Ye;let yt=Ye.material;yt.allowOverride===!0&&ie!==null&&(yt=ie),Fe.layers.test(le.layers)&&P6(Fe,X,le,Ke,yt,et)}}function P6(L,X,le,ie,oe,He){R!==null&&oe.isNodeMaterial&&R.setObject(L,oe),L.onBeforeRender(E,X,le,ie,oe,He),L.modelViewMatrix.multiplyMatrices(le.matrixWorldInverse,L.matrixWorld),L.normalMatrix.getNormalMatrix(L.modelViewMatrix),oe.onBeforeRender(E,X,le,ie,L,He),oe.transparent===!0&&oe.side===es&&oe.forceSinglePass===!1?(oe.side=Ea,oe.needsUpdate=!0,E.renderBufferDirect(le,X,ie,oe,L,He),oe.side=nl,oe.needsUpdate=!0,E.renderBufferDirect(le,X,ie,oe,L,He),oe.side=es):E.renderBufferDirect(le,X,ie,oe,L,He),L.onAfterRender(E,X,le,ie,oe,He)}function Pv(L,X,le){X.isScene!==!0&&(X=ln);const ie=se.get(L),oe=A.state.lights,He=A.state.shadowsArray,Ye=oe.state.version,Fe=j.getParameters(L,oe.state,He,X,le,A.state.lightProbeGridArray),Ke=j.getProgramCacheKey(Fe);let et=ie.programs;ie.environment=L.isMeshStandardMaterial||L.isMeshLambertMaterial||L.isMeshPhongMaterial?X.environment:null,ie.fog=X.fog;const yt=L.isMeshStandardMaterial||L.isMeshLambertMaterial&&!L.envMap||L.isMeshPhongMaterial&&!L.envMap;ie.envMap=Le.get(L.envMap||ie.environment,yt),ie.envMapRotation=ie.environment!==null&&L.envMap===null?X.environmentRotation:L.envMapRotation,et===void 0&&(L.addEventListener("dispose",Ao),et=new Map,ie.programs=et);let Mt=et.get(Ke);if(Mt!==void 0){if(ie.currentProgram===Mt&&ie.lightsStateVersion===Ye)return N6(L,Fe),Mt}else Fe.uniforms=j.getUniforms(L),R!==null&&L.isNodeMaterial&&R.build(L,le,Fe),L.onBeforeCompile(Fe,E),Mt=j.acquireProgram(Fe,Ke),et.set(Ke,Mt),ie.uniforms=Fe.uniforms;const Ze=ie.uniforms;return(!L.isShaderMaterial&&!L.isRawShaderMaterial||L.clipping===!0)&&(Ze.clippingPlanes=Y.uniform),N6(L,Fe),ie.needsLights=TX(L),ie.lightsStateVersion=Ye,ie.needsLights&&(Ze.ambientLightColor.value=oe.state.ambient,Ze.lightProbe.value=oe.state.probe,Ze.sunLights.value=oe.state.sun,Ze.sunLightShadows.value=oe.state.sunShadow,Ze.directionalLights.value=oe.state.directional,Ze.directionalLightShadows.value=oe.state.directionalShadow,Ze.spotLights.value=oe.state.spot,Ze.spotLightShadows.value=oe.state.spotShadow,Ze.rectAreaLights.value=oe.state.rectArea,Ze.ltc_1.value=oe.state.rectAreaLTC1,Ze.ltc_2.value=oe.state.rectAreaLTC2,Ze.pointLights.value=oe.state.point,Ze.pointLightShadows.value=oe.state.pointShadow,Ze.hemisphereLights.value=oe.state.hemi,Ze.sunShadowMatrix.value=oe.state.sunShadowMatrix,Ze.sunShadowCascade.value=oe.state.sunShadowCascade,Ze.directionalShadowMatrix.value=oe.state.directionalShadowMatrix,Ze.spotLightMatrix.value=oe.state.spotLightMatrix,Ze.spotLightMap.value=oe.state.spotLightMap,Ze.pointShadowMatrix.value=oe.state.pointShadowMatrix),ie.lightProbeGrid=A.state.lightProbeGridArray.length>0,ie.currentProgram=Mt,ie.uniformsList=null,Mt}function I6(L){if(L.uniformsList===null){const X=L.currentProgram.getUniforms();L.uniformsList=tv.seqWithValue(X.seq,L.uniforms)}return L.uniformsList}function N6(L,X){const le=se.get(L);le.outputColorSpace=X.outputColorSpace,le.batching=X.batching,le.batchingColor=X.batchingColor,le.instancing=X.instancing,le.instancingColor=X.instancingColor,le.instancingMorph=X.instancingMorph,le.skinning=X.skinning,le.morphTargets=X.morphTargets,le.morphNormals=X.morphNormals,le.morphColors=X.morphColors,le.morphTargetsCount=X.morphTargetsCount,le.numClippingPlanes=X.numClippingPlanes,le.numIntersection=X.numClipIntersection,le.vertexAlphas=X.vertexAlphas,le.vertexTangents=X.vertexTangents,le.toneMapping=X.toneMapping}function SX(L,X){if(L.length===0)return null;if(L.length===1)return L[0].texture!==null?L[0]:null;y.setFromMatrixPosition(X.matrixWorld);for(let le=0,ie=L.length;le<ie;le++){const oe=L[le];if(oe.texture!==null&&oe.boundingBox.containsPoint(y))return oe}return null}function MX(L,X,le,ie,oe){X.isScene!==!0&&(X=ln),he.resetTextureUnits();const He=X.fog,Ye=ie.isMeshStandardMaterial||ie.isMeshLambertMaterial||ie.isMeshPhongMaterial?X.environment:null,Fe=J===null?E.outputColorSpace:J.isXRRenderTarget===!0?J.texture.colorSpace:Ct.workingColorSpace,Ke=ie.isMeshStandardMaterial||ie.isMeshLambertMaterial&&!ie.envMap||ie.isMeshPhongMaterial&&!ie.envMap,et=Le.get(ie.envMap||Ye,Ke),yt=ie.vertexColors===!0&&!!le.attributes.color&&le.attributes.color.itemSize===4,Mt=!!le.attributes.tangent&&(!!ie.normalMap||ie.anisotropy>0),Ze=!!le.morphAttributes.position,Bt=!!le.morphAttributes.normal,Rn=!!le.morphAttributes.color;let on=uo;ie.toneMapped&&(J===null||J.isXRRenderTarget===!0)&&(on=E.toneMapping);const Kt=le.morphAttributes.position||le.morphAttributes.normal||le.morphAttributes.color,oa=Kt!==void 0?Kt.length:0,je=se.get(ie),xa=A.state.lights;if(vt===!0&&(Rt===!0||L!==ae)){const Qt=L===ae&&ie.id===ne;Y.setState(ie,L,Qt)}let Dt=!1;ie.version===je.__version?(je.needsLights&&je.lightsStateVersion!==xa.state.version||je.outputColorSpace!==Fe||oe.isBatchedMesh&&je.batching===!1||!oe.isBatchedMesh&&je.batching===!0||oe.isBatchedMesh&&je.batchingColor===!0&&oe._colorsTexture===null||oe.isBatchedMesh&&je.batchingColor===!1&&oe._colorsTexture!==null||oe.isInstancedMesh&&je.instancing===!1||!oe.isInstancedMesh&&je.instancing===!0||oe.isSkinnedMesh&&je.skinning===!1||!oe.isSkinnedMesh&&je.skinning===!0||oe.isInstancedMesh&&je.instancingColor===!0&&oe.instanceColor===null||oe.isInstancedMesh&&je.instancingColor===!1&&oe.instanceColor!==null||oe.isInstancedMesh&&je.instancingMorph===!0&&oe.morphTexture===null||oe.isInstancedMesh&&je.instancingMorph===!1&&oe.morphTexture!==null||je.envMap!==et||ie.fog===!0&&je.fog!==He||je.numClippingPlanes!==void 0&&(je.numClippingPlanes!==Y.numPlanes||je.numIntersection!==Y.numIntersection)||je.vertexAlphas!==yt||je.vertexTangents!==Mt||je.morphTargets!==Ze||je.morphNormals!==Bt||je.morphColors!==Rn||je.toneMapping!==on||je.morphTargetsCount!==oa||!!je.lightProbeGrid!=A.state.lightProbeGridArray.length>0)&&(Dt=!0):(Dt=!0,je.__version=ie.version);let li=je.currentProgram;Dt===!0&&(li=Pv(ie,X,oe),R&&ie.isNodeMaterial&&R.onUpdateProgram(ie,li,je));let To=!1,nr=!1,ud=!1;const jt=li.getUniforms(),Mn=je.uniforms;if(M.useProgram(li.program)&&(To=!0,nr=!0,ud=!0),ie.id!==ne&&(ne=ie.id,nr=!0),je.needsLights){const Qt=SX(A.state.lightProbeGridArray,oe);je.lightProbeGrid!==Qt&&(je.lightProbeGrid=Qt,nr=!0)}if(To||ae!==L){M.buffers.depth.getReversed()&&L.reversedDepth!==!0&&(L._reversedDepth=!0,L.updateProjectionMatrix()),jt.setValue(K,"projectionMatrix",L.projectionMatrix),jt.setValue(K,"viewMatrix",L.matrixWorldInverse);const ir=jt.map.cameraPosition;ir!==void 0&&ir.setValue(K,Gt.setFromMatrixPosition(L.matrixWorld)),F.logarithmicDepthBuffer&&jt.setValue(K,"logDepthBufFC",2/(Math.log(L.far+1)/Math.LN2)),(ie.isMeshPhongMaterial||ie.isMeshToonMaterial||ie.isMeshLambertMaterial||ie.isMeshBasicMaterial||ie.isMeshStandardMaterial||ie.isShaderMaterial)&&jt.setValue(K,"isOrthographic",L.isOrthographicCamera===!0),ae!==L&&(ae=L,nr=!0,ud=!0)}if(je.needsLights&&(xa.state.sunShadowMap.length>0&&jt.setValue(K,"sunShadowMap",xa.state.sunShadowMap,he),xa.state.directionalShadowMap.length>0&&jt.setValue(K,"directionalShadowMap",xa.state.directionalShadowMap,he),xa.state.spotShadowMap.length>0&&jt.setValue(K,"spotShadowMap",xa.state.spotShadowMap,he),xa.state.pointShadowMap.length>0&&jt.setValue(K,"pointShadowMap",xa.state.pointShadowMap,he)),oe.isSkinnedMesh){jt.setOptional(K,oe,"bindMatrix"),jt.setOptional(K,oe,"bindMatrixInverse");const Qt=oe.skeleton;Qt&&(Qt.boneTexture===null&&Qt.computeBoneTexture(),jt.setValue(K,"boneTexture",Qt.boneTexture,he))}oe.isBatchedMesh&&(jt.setOptional(K,oe,"batchingTexture"),jt.setValue(K,"batchingTexture",oe._matricesTexture,he),jt.setOptional(K,oe,"batchingIdTexture"),jt.setValue(K,"batchingIdTexture",oe._indirectTexture,he),jt.setOptional(K,oe,"batchingColorTexture"),oe._colorsTexture!==null&&jt.setValue(K,"batchingColorTexture",oe._colorsTexture,he));const ar=le.morphAttributes;if((ar.position!==void 0||ar.normal!==void 0||ar.color!==void 0)&&W.update(oe,le,li),(nr||je.receiveShadow!==oe.receiveShadow)&&(je.receiveShadow=oe.receiveShadow,jt.setValue(K,"receiveShadow",oe.receiveShadow)),(ie.isMeshStandardMaterial||ie.isMeshLambertMaterial||ie.isMeshPhongMaterial)&&ie.envMap===null&&X.environment!==null&&(Mn.envMapIntensity.value=X.environmentIntensity),Mn.dfgLUT!==void 0&&(Mn.dfgLUT.value=FG()),nr){if(jt.setValue(K,"toneMappingExposure",E.toneMappingExposure),je.needsLights&&AX(Mn,ud),He&&ie.fog===!0&&ce.refreshFogUniforms(Mn,He),ce.refreshMaterialUniforms(Mn,ie,Z,de,A.state.transmissionRenderTarget[L.id]),je.needsLights&&je.lightProbeGrid){const Qt=je.lightProbeGrid;Mn.probesSH.value=Qt.texture,Mn.probesMin.value.copy(Qt.boundingBox.min),Mn.probesMax.value.copy(Qt.boundingBox.max),Mn.probesResolution.value.copy(Qt.resolution)}tv.upload(K,I6(je),Mn,he)}if(ie.isShaderMaterial&&ie.uniformsNeedUpdate===!0&&(tv.upload(K,I6(je),Mn,he),ie.uniformsNeedUpdate=!1),ie.isSpriteMaterial&&jt.setValue(K,"center",oe.center),jt.setValue(K,"modelViewMatrix",oe.modelViewMatrix),jt.setValue(K,"normalMatrix",oe.normalMatrix),jt.setValue(K,"modelMatrix",oe.matrixWorld),ie.uniformsGroups!==void 0){const Qt=ie.uniformsGroups;for(let ir=0,fd=Qt.length;ir<fd;ir++){const D6=Qt[ir];ke.update(D6,li),ke.bind(D6,li)}}return li}function AX(L,X){L.ambientLightColor.needsUpdate=X,L.lightProbe.needsUpdate=X,L.sunLights.needsUpdate=X,L.sunLightShadows.needsUpdate=X,L.directionalLights.needsUpdate=X,L.directionalLightShadows.needsUpdate=X,L.pointLights.needsUpdate=X,L.pointLightShadows.needsUpdate=X,L.spotLights.needsUpdate=X,L.spotLightShadows.needsUpdate=X,L.rectAreaLights.needsUpdate=X,L.hemisphereLights.needsUpdate=X}function TX(L){return L.isMeshLambertMaterial||L.isMeshToonMaterial||L.isMeshPhongMaterial||L.isMeshStandardMaterial||L.isShadowMaterial||L.isShaderMaterial&&L.lights===!0}this.getActiveCubeFace=function(){return G},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return J},this.setRenderTargetTextures=function(L,X,le){const ie=se.get(L);ie.__autoAllocateDepthBuffer=L.resolveDepthBuffer===!1,ie.__autoAllocateDepthBuffer===!1&&(ie.__useRenderToTexture=!1),se.get(L.texture).__webglTexture=X,se.get(L.depthTexture).__webglTexture=ie.__autoAllocateDepthBuffer?void 0:le,ie.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(L,X){const le=se.get(L);le.__webglFramebuffer=X,le.__useDefaultFramebuffer=X===void 0},this.setRenderTarget=function(L,X=0,le=0){J=L,G=X,O=le;let ie=null,oe=!1,He=!1;if(L){const Fe=se.get(L);if(Fe.__useDefaultFramebuffer!==void 0){M.bindFramebuffer(K.FRAMEBUFFER,Fe.__webglFramebuffer),q.copy(L.viewport),we.copy(L.scissor),Re=L.scissorTest,M.viewport(q),M.scissor(we),M.setScissorTest(Re),ne=-1;return}else if(Fe.__webglFramebuffer===void 0)he.setupRenderTarget(L);else if(Fe.__hasExternalTextures)he.rebindTextures(L,se.get(L.texture).__webglTexture,se.get(L.depthTexture).__webglTexture);else if(L.depthBuffer){const yt=L.depthTexture;if(Fe.__boundDepthTexture!==yt){if(yt!==null&&se.has(yt)&&(L.width!==yt.image.width||L.height!==yt.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");he.setupDepthRenderbuffer(L)}}const Ke=L.texture;(Ke.isData3DTexture||Ke.isDataArrayTexture||Ke.isCompressedArrayTexture)&&(He=!0);const et=se.get(L).__webglFramebuffer;L.isWebGLCubeRenderTarget?(Array.isArray(et[X])?ie=et[X][le]:ie=et[X],oe=!0):L.samples>0&&he.useMultisampledRTT(L)===!1?ie=se.get(L).__webglMultisampledFramebuffer:Array.isArray(et)?ie=et[le]:ie=et,q.copy(L.viewport),we.copy(L.scissor),Re=L.scissorTest}else q.copy(De).multiplyScalar(Z).floor(),we.copy(be).multiplyScalar(Z).floor(),Re=ft;if(le!==0&&(ie=B),M.bindFramebuffer(K.FRAMEBUFFER,ie)&&M.drawBuffers(L,ie),M.viewport(q),M.scissor(we),M.setScissorTest(Re),oe){const Fe=se.get(L.texture);K.framebufferTexture2D(K.FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_CUBE_MAP_POSITIVE_X+X,Fe.__webglTexture,le)}else if(He){const Fe=X;for(let Ke=0;Ke<L.textures.length;Ke++){const et=se.get(L.textures[Ke]);K.framebufferTextureLayer(K.FRAMEBUFFER,K.COLOR_ATTACHMENT0+Ke,et.__webglTexture,le,Fe)}}else if(L!==null&&le!==0){const Fe=se.get(L.texture);K.framebufferTexture2D(K.FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_2D,Fe.__webglTexture,le)}ne=-1};function z6(L){const X=se.get(L);return(X.__readFormat!==L.format||X.__readType!==L.type)&&(X.__readFormat=L.format,X.__readType=L.type,X.__formatReadable=F.textureFormatReadable(L.format),X.__typeReadable=F.textureTypeReadable(L.type)),X}this.readRenderTargetPixels=function(L,X,le,ie,oe,He,Ye,Fe=0){if(!(L&&L.isWebGLRenderTarget)){Ot("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ke=se.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Ye!==void 0&&(Ke=Ke[Ye]),Ke){M.bindFramebuffer(K.FRAMEBUFFER,Ke);try{const et=L.textures[Fe],yt=et.format,Mt=et.type;L.textures.length>1&&K.readBuffer(K.COLOR_ATTACHMENT0+Fe);const Ze=z6(et);if(Ze.__formatReadable===!1){Ot("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(Ze.__typeReadable===!1){Ot("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}X>=0&&X<=L.width-ie&&le>=0&&le<=L.height-oe&&K.readPixels(X,le,ie,oe,Me.convert(yt),Me.convert(Mt),He)}finally{const et=J!==null?se.get(J).__webglFramebuffer:null;M.bindFramebuffer(K.FRAMEBUFFER,et)}}},this.readRenderTargetPixelsAsync=async function(L,X,le,ie,oe,He,Ye,Fe=0){if(!(L&&L.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ke=se.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Ye!==void 0&&(Ke=Ke[Ye]),Ke)if(X>=0&&X<=L.width-ie&&le>=0&&le<=L.height-oe){M.bindFramebuffer(K.FRAMEBUFFER,Ke);const et=L.textures[Fe],yt=et.format,Mt=et.type;L.textures.length>1&&K.readBuffer(K.COLOR_ATTACHMENT0+Fe);const Ze=z6(et);if(Ze.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(Ze.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Bt=K.createBuffer();K.bindBuffer(K.PIXEL_PACK_BUFFER,Bt),K.bufferData(K.PIXEL_PACK_BUFFER,He.byteLength,K.STREAM_READ),K.readPixels(X,le,ie,oe,Me.convert(yt),Me.convert(Mt),0),K.bindBuffer(K.PIXEL_PACK_BUFFER,null);const Rn=J!==null?se.get(J).__webglFramebuffer:null;M.bindFramebuffer(K.FRAMEBUFFER,Rn);const on=K.fenceSync(K.SYNC_GPU_COMMANDS_COMPLETE,0);return K.flush(),await DH(K,on,4),K.bindBuffer(K.PIXEL_PACK_BUFFER,Bt),K.getBufferSubData(K.PIXEL_PACK_BUFFER,0,He),K.bindBuffer(K.PIXEL_PACK_BUFFER,null),K.deleteBuffer(Bt),K.deleteSync(on),He}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(L,X=null,le=0){const ie=Math.pow(2,-le),oe=Math.floor(L.image.width*ie),He=Math.floor(L.image.height*ie),Ye=X!==null?X.x:0,Fe=X!==null?X.y:0;he.setTexture2D(L,0),K.copyTexSubImage2D(K.TEXTURE_2D,le,0,0,Ye,Fe,oe,He),M.unbindTexture()},this.copyTextureToTexture=function(L,X,le=null,ie=null,oe=0,He=0){let Ye,Fe,Ke,et,yt,Mt,Ze,Bt,Rn;const on=L.isCompressedTexture?L.mipmaps[He]:L.image;if(le!==null)Ye=le.max.x-le.min.x,Fe=le.max.y-le.min.y,Ke=le.isBox3?le.max.z-le.min.z:1,et=le.min.x,yt=le.min.y,Mt=le.isBox3?le.min.z:0;else{const Mn=Math.pow(2,-oe);Ye=Math.floor(on.width*Mn),Fe=Math.floor(on.height*Mn),L.isDataArrayTexture?Ke=on.depth:L.isData3DTexture?Ke=Math.floor(on.depth*Mn):Ke=1,et=0,yt=0,Mt=0}ie!==null?(Ze=ie.x,Bt=ie.y,Rn=ie.z):(Ze=0,Bt=0,Rn=0);const Kt=Me.convert(X.format),oa=Me.convert(X.type);let je;X.isData3DTexture?(he.setTexture3D(X,0),je=K.TEXTURE_3D):X.isDataArrayTexture||X.isCompressedArrayTexture?(he.setTexture2DArray(X,0),je=K.TEXTURE_2D_ARRAY):(he.setTexture2D(X,0),je=K.TEXTURE_2D),M.activeTexture(K.TEXTURE0),M.pixelStorei(K.UNPACK_FLIP_Y_WEBGL,X.flipY),M.pixelStorei(K.UNPACK_PREMULTIPLY_ALPHA_WEBGL,X.premultiplyAlpha),M.pixelStorei(K.UNPACK_ALIGNMENT,X.unpackAlignment);const xa=M.getParameter(K.UNPACK_ROW_LENGTH),Dt=M.getParameter(K.UNPACK_IMAGE_HEIGHT),li=M.getParameter(K.UNPACK_SKIP_PIXELS),To=M.getParameter(K.UNPACK_SKIP_ROWS),nr=M.getParameter(K.UNPACK_SKIP_IMAGES);M.pixelStorei(K.UNPACK_ROW_LENGTH,on.width),M.pixelStorei(K.UNPACK_IMAGE_HEIGHT,on.height),M.pixelStorei(K.UNPACK_SKIP_PIXELS,et),M.pixelStorei(K.UNPACK_SKIP_ROWS,yt),M.pixelStorei(K.UNPACK_SKIP_IMAGES,Mt);const ud=L.isDataArrayTexture||L.isData3DTexture,jt=X.isDataArrayTexture||X.isData3DTexture;if(L.isDepthTexture){const Mn=se.get(L),ar=se.get(X),Qt=se.get(Mn.__renderTarget),ir=se.get(ar.__renderTarget);M.bindFramebuffer(K.READ_FRAMEBUFFER,Qt.__webglFramebuffer),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,ir.__webglFramebuffer);for(let fd=0;fd<Ke;fd++)ud&&(K.framebufferTextureLayer(K.READ_FRAMEBUFFER,K.COLOR_ATTACHMENT0,se.get(L).__webglTexture,oe,Mt+fd),K.framebufferTextureLayer(K.DRAW_FRAMEBUFFER,K.COLOR_ATTACHMENT0,se.get(X).__webglTexture,He,Rn+fd)),K.blitFramebuffer(et,yt,Ye,Fe,Ze,Bt,Ye,Fe,K.DEPTH_BUFFER_BIT,K.NEAREST);M.bindFramebuffer(K.READ_FRAMEBUFFER,null),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,null)}else if(oe!==0||L.isRenderTargetTexture||se.has(L)){const Mn=se.get(L),ar=se.get(X);M.bindFramebuffer(K.READ_FRAMEBUFFER,D),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,$);for(let Qt=0;Qt<Ke;Qt++)ud?K.framebufferTextureLayer(K.READ_FRAMEBUFFER,K.COLOR_ATTACHMENT0,Mn.__webglTexture,oe,Mt+Qt):K.framebufferTexture2D(K.READ_FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_2D,Mn.__webglTexture,oe),jt?K.framebufferTextureLayer(K.DRAW_FRAMEBUFFER,K.COLOR_ATTACHMENT0,ar.__webglTexture,He,Rn+Qt):K.framebufferTexture2D(K.DRAW_FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_2D,ar.__webglTexture,He),oe!==0?K.blitFramebuffer(et,yt,Ye,Fe,Ze,Bt,Ye,Fe,K.COLOR_BUFFER_BIT,K.NEAREST):jt?K.copyTexSubImage3D(je,He,Ze,Bt,Rn+Qt,et,yt,Ye,Fe):K.copyTexSubImage2D(je,He,Ze,Bt,et,yt,Ye,Fe);M.bindFramebuffer(K.READ_FRAMEBUFFER,null),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,null)}else jt?L.isDataTexture||L.isData3DTexture?K.texSubImage3D(je,He,Ze,Bt,Rn,Ye,Fe,Ke,Kt,oa,on.data):X.isCompressedArrayTexture?K.compressedTexSubImage3D(je,He,Ze,Bt,Rn,Ye,Fe,Ke,Kt,on.data):K.texSubImage3D(je,He,Ze,Bt,Rn,Ye,Fe,Ke,Kt,oa,on):L.isDataTexture?K.texSubImage2D(K.TEXTURE_2D,He,Ze,Bt,Ye,Fe,Kt,oa,on.data):L.isCompressedTexture?K.compressedTexSubImage2D(K.TEXTURE_2D,He,Ze,Bt,on.width,on.height,Kt,on.data):K.texSubImage2D(K.TEXTURE_2D,He,Ze,Bt,Ye,Fe,Kt,oa,on);M.pixelStorei(K.UNPACK_ROW_LENGTH,xa),M.pixelStorei(K.UNPACK_IMAGE_HEIGHT,Dt),M.pixelStorei(K.UNPACK_SKIP_PIXELS,li),M.pixelStorei(K.UNPACK_SKIP_ROWS,To),M.pixelStorei(K.UNPACK_SKIP_IMAGES,nr),He===0&&X.generateMipmaps&&K.generateMipmap(je),M.unbindTexture()},this.initRenderTarget=function(L){se.get(L).__webglFramebuffer===void 0&&he.setupRenderTarget(L)},this.initTexture=function(L){L.isCubeTexture?he.setTextureCube(L,0):L.isData3DTexture?he.setTexture3D(L,0):L.isDataArrayTexture||L.isCompressedArrayTexture?he.setTexture2DArray(L,0):he.setTexture2D(L,0),M.unbindTexture()},this.resetState=function(){G=0,O=0,J=null,M.reset(),Pe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return vo}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=Ct._getDrawingBufferColorSpace(e),n.unpackColorSpace=Ct._getUnpackColorSpace()}}const rC={type:"change"},tk={type:"start"},lC={type:"end"},av=new Ng,cC=new ds,BG=Math.cos(70*FH.DEG2RAD),zn=new Q,Ca=2*Math.PI,qt={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},nk=1e-6;class HG extends kq{constructor(e,n=null){super(e,n),this.state=qt.NONE,this.target=new Q,this.cursor=new Q,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Ic.ROTATE,MIDDLE:Ic.DOLLY,RIGHT:Ic.PAN},this.touches={ONE:Nc.ROTATE,TWO:Nc.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new Q,this._lastQuaternion=new Ys,this._lastTargetPosition=new Q,this._quat=new Ys().setFromUnitVectors(e.up,new Q(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new __,this._sphericalDelta=new __,this._scale=1,this._panOffset=new Q,this._rotateStart=new ut,this._rotateEnd=new ut,this._rotateDelta=new ut,this._panStart=new ut,this._panEnd=new ut,this._panDelta=new ut,this._dollyStart=new ut,this._dollyEnd=new ut,this._dollyDelta=new ut,this._dollyDirection=new Q,this._mouse=new ut,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=WG.bind(this),this._onPointerDown=qG.bind(this),this._onPointerUp=GG.bind(this),this._onContextMenu=JG.bind(this),this._onMouseWheel=YG.bind(this),this._onKeyDown=XG.bind(this),this._onTouchStart=KG.bind(this),this._onTouchMove=ZG.bind(this),this._onMouseDown=VG.bind(this),this._onMouseMove=jG.bind(this),this._interceptControlDown=QG.bind(this),this._interceptControlUp=eV.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.state=qt.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();const e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(rC),this.update(),this.state=qt.NONE}pan(e,n){this._pan(e,n),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const n=this.object.position;zn.copy(n).sub(this.target),zn.applyQuaternion(this._quat),this._spherical.setFromVector3(zn),this.autoRotate&&this.state===qt.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let a=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(a)&&isFinite(i)&&(a<-Math.PI?a+=Ca:a>Math.PI&&(a-=Ca),i<-Math.PI?i+=Ca:i>Math.PI&&(i-=Ca),a<=i?this._spherical.theta=Math.max(a,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(a+i)/2?Math.max(a,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=s!=this._spherical.radius}if(zn.setFromSpherical(this._spherical),zn.applyQuaternion(this._quatInverse),n.copy(this.target).add(zn),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let s=null;if(this.object.isPerspectiveCamera){const r=zn.length();s=this._clampDistance(r*this._scale);const l=r-s;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),o=!!l}else if(this.object.isOrthographicCamera){const r=new Q(this._mouse.x,this._mouse.y,0);r.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=l!==this.object.zoom;const c=new Q(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(r),this.object.updateMatrixWorld(),s=zn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;s!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position):(av.origin.copy(this.object.position),av.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(av.direction))<BG?this.object.lookAt(this.target):(cC.setFromNormalAndCoplanarPoint(this.object.up,this.target),av.intersectPlane(cC,this.target))))}else if(this.object.isOrthographicCamera){const s=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>nk||8*(1-this._lastQuaternion.dot(this.object.quaternion))>nk||this._lastTargetPosition.distanceToSquared(this.target)>nk?(this.dispatchEvent(rC),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Ca/60*this.autoRotateSpeed*e:Ca/60/60*this.autoRotateSpeed}_getZoomScale(e){const n=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*n)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,n){zn.setFromMatrixColumn(n,0),zn.multiplyScalar(-e),this._panOffset.add(zn)}_panUp(e,n){this.screenSpacePanning===!0?zn.setFromMatrixColumn(n,1):(zn.setFromMatrixColumn(n,0),zn.crossVectors(this.object.up,zn)),zn.multiplyScalar(e),this._panOffset.add(zn)}_pan(e,n){const a=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;zn.copy(i).sub(this.target);let o=zn.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/a.clientHeight,this.object.matrix),this._panUp(2*n*o/a.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/a.clientWidth,this.object.matrix),this._panUp(n*(this.object.top-this.object.bottom)/this.object.zoom/a.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,n){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const a=this.domElement.getBoundingClientRect(),i=e-a.left,o=n-a.top,s=a.width,r=a.height;this._mouse.x=i/s*2-1,this._mouse.y=-(o/r)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Ca*this._rotateDelta.x/n.clientHeight),this._rotateUp(Ca*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let n=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),n=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),n=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),n=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),n=!0;break}n&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._rotateStart.set(a,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panStart.set(a,i)}}_handleTouchStartDolly(e){const n=this._getSecondPointerPosition(e),a=e.pageX-n.x,i=e.pageY-n.y,o=Math.sqrt(a*a+i*i);this._dollyStart.set(0,o)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const a=this._getSecondPointerPosition(e),i=.5*(e.pageX+a.x),o=.5*(e.pageY+a.y);this._rotateEnd.set(i,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Ca*this._rotateDelta.x/n.clientHeight),this._rotateUp(Ca*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panEnd.set(a,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const n=this._getSecondPointerPosition(e),a=e.pageX-n.x,i=e.pageY-n.y,o=Math.sqrt(a*a+i*i);this._dollyEnd.set(0,o),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=(e.pageX+n.x)*.5,r=(e.pageY+n.y)*.5;this._updateZoomParameters(s,r)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId){this._pointers.splice(n,1);return}}_isTrackingPointer(e){for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId)return!0;return!1}_trackPointer(e){let n=this._pointerPositions[e.pointerId];n===void 0&&(n=new ut,this._pointerPositions[e.pointerId]=n),n.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const n=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[n]}_customWheelEvent(e){const n=e.deltaMode,a={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(n){case 1:a.deltaY*=16;break;case 2:a.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(a.deltaY*=10),a}}function qG(t){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(t.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(t)&&(this._addPointer(t),t.pointerType==="touch"?this._onTouchStart(t):this._onMouseDown(t),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function WG(t){this.enabled!==!1&&(t.pointerType==="touch"?this._onTouchMove(t):this._onMouseMove(t))}function GG(t){switch(this._removePointer(t),this._pointers.length){case 0:this.domElement.releasePointerCapture(t.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(lC),this.state=qt.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],n=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:n.x,pageY:n.y});break}}function VG(t){let e;switch(t.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Ic.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(t),this.state=qt.DOLLY;break;case Ic.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=qt.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=qt.ROTATE}break;case Ic.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=qt.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=qt.PAN}break;default:this.state=qt.NONE}this.state!==qt.NONE&&this.dispatchEvent(tk)}function jG(t){switch(this.state){case qt.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(t);break;case qt.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(t);break;case qt.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(t);break}}function YG(t){this.enabled===!1||this.enableZoom===!1||this.state!==qt.NONE||(t.preventDefault(),this.dispatchEvent(tk),this._handleMouseWheel(this._customWheelEvent(t)),this.dispatchEvent(lC))}function XG(t){this.enabled!==!1&&this._handleKeyDown(t)}function KG(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case Nc.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(t),this.state=qt.TOUCH_ROTATE;break;case Nc.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(t),this.state=qt.TOUCH_PAN;break;default:this.state=qt.NONE}break;case 2:switch(this.touches.TWO){case Nc.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(t),this.state=qt.TOUCH_DOLLY_PAN;break;case Nc.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(t),this.state=qt.TOUCH_DOLLY_ROTATE;break;default:this.state=qt.NONE}break;default:this.state=qt.NONE}this.state!==qt.NONE&&this.dispatchEvent(tk)}function ZG(t){switch(this._trackPointer(t),this.state){case qt.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(t),this.update();break;case qt.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(t),this.update();break;case qt.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(t),this.update();break;case qt.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(t),this.update();break;default:this.state=qt.NONE}}function JG(t){this.enabled!==!1&&t.preventDefault()}function QG(t){t.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function eV(t){t.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const tV=6;function ak(t,e,n,a,i){switch(t){case"agent":return{l:e+14,t:n-i*1.3,r:e+14+a,b:n-i*.3};case"agent-flip":return{l:e-14-a,t:n-i*1.3,r:e-14,b:n-i*.3};case"region":return{l:e-a/2,t:n-6-i/2,r:e+a/2,b:n-6+i/2};case"note":return{l:e+10,t:n-i/2,r:e+10+a,b:n+i/2}}}function iv(t,e){for(const n of e)if(t.l<n.r&&t.r>n.l&&t.t<n.b&&t.b>n.t)return!1;return!0}function nV(t,e,n,a,i){return!i.length||iv(ak("agent",t,e,n,a),i)?"right":iv(ak("agent-flip",t,e,n,a),i)?"left":"hidden"}function aV(t,e,n=tV){const a=[];for(const i of e){const o=i.getBoundingClientRect();o.width<1||o.height<1||o.right<t.left||o.left>t.right||o.bottom<t.top||o.top>t.bottom||a.push({l:o.left-t.left-n,t:o.top-t.top-n,r:o.right-t.left+n,b:o.bottom-t.top+n})}return a}function ik(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}function Zh(t){let e=t>>>0||2654435769;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function ok(t){const e=Math.max(1e-9,t());return Math.sqrt(-2*Math.log(e))*Math.cos(2*Math.PI*t())}function er(t,e,n){let a=Math.imul(t,374761393)+Math.imul(e,668265263)+Math.imul(n,1274126177);return a=Math.imul(a^a>>>13,1274126177),((a^a>>>16)>>>0)/4294967296}function dC(t,e,n){const a=Math.floor(t),i=Math.floor(e),o=Math.floor(n),s=t-a,r=e-i,l=n-o,c=s*s*(3-2*s),d=r*r*(3-2*r),p=l*l*(3-2*l),h=(u,f,v)=>u+(f-u)*v;return h(h(h(er(a,i,o),er(a+1,i,o),c),h(er(a,i+1,o),er(a+1,i+1,o),c),d),h(h(er(a,i,o+1),er(a+1,i,o+1),c),h(er(a,i+1,o+1),er(a+1,i+1,o+1),c),d),p)}function iV(t,e,n){const i=1-Math.abs(2*dC(t*5.2+11.3,e*5.2*1.15,n*5.2)-1),o=1-Math.abs(2*dC(t*5.2*2.1,e*5.2*2.1+5.1,n*5.2*2.1-3.7)-1),s=Math.max(Math.pow(i,5),Math.pow(o,7)*.6);return Math.min(1,s*1.25)}const ad={c:[.4,.06,0],a:[.52,.62,1]},sk={c:[.52,-.27,.14],a:[.3,.25,.56]},pC={c:[.25,-.44,-.66],a:[.3,.2,.3]};function id(t,e,n,a){const i=1-.1*Math.max(0,a),o=(e-t.c[0])/(t.a[0]*i);let s=(n-t.c[1])/(t.a[1]*i);s<0&&t===ad&&(s*=1.35);const r=(a-t.c[2])/t.a[2];return Math.sqrt(o*o+s*s+r*r)}function ov(t,e,n){const a=Math.abs(t);return a<.035?9:Math.min(id(ad,a,e,n),id(sk,a,e,n))}function hC(t,e,n){const a=Math.abs(t);return a<.02?9:id(pC,a,e,n)}function oV(t,e,n,a=.9){return ov(t,e,n)<a||hC(t,e,n)<a*.9}function sV(t,e=7){const n=Zh(e),a=new Float32Array(t*3),i=new Float32Array(t*3),o=new Float32Array(t);let s=0,r=t*60;for(;s<t&&r-- >0;){const l=n();let c=ad,d=0;l<.78?c=ad:l<.9?c=sk:l<.97?(c=pC,d=1):d=2;let p,h,u,f,v,g;if(d===2){const R=n(),B=n()*Math.PI*2,D=.1-R*.025;if(f=Math.cos(B),g=Math.sin(B),v=0,p=f*D,h=-.28-R*.55,u=-.28-R*.12+g*D,ov(p,h,u)<1||hC(p,h,u)<1)continue;a.set([p,h,u],s*3),i.set([f,v,g],s*3),o[s]=.45+.2*n(),s++;continue}const m=n()*2-1,b=n()*Math.PI*2,k=Math.sqrt(1-m*m),y=n()<.5?-1:1;let w=k*Math.cos(b),A=k*Math.sin(b),_=m;p=c.c[0]+w*c.a[0],h=c.c[1]+A*c.a[1],u=c.c[2]+_*c.a[2];const S=id(c,p,h,u);if(p=c.c[0]+(p-c.c[0])/S,h=c.c[1]+(h-c.c[1])/S,u=c.c[2]+(u-c.c[2])/S,p<.035)continue;if(d===0){if(id(c===ad?sk:ad,p,h,u)<.985)continue}else if(ov(p,h,u)<1)continue;f=(p-c.c[0])/(c.a[0]*c.a[0]),v=(h-c.c[1])/(c.a[1]*c.a[1]),g=(u-c.c[2])/(c.a[2]*c.a[2]);const T=Math.hypot(f,v,g)||1;f/=T,v/=T,g/=T;let E,P;if(d===1){const R=Math.abs(Math.sin(h*70+u*12));E=.35+.65*R,P=(1-R)*.018}else{const R=iV(p,h,u);if(R>.55&&n()<.55)continue;E=1-.9*R,P=R*.05}p-=f*P,h-=v*P,u-=g*P,w=p*y,a.set([w,h,u],s*3),i.set([f*y,v,g],s*3),o[s]=E,s++}return{pos:a,nrm:i,shade:o,count:s}}function rV(t,e=3){const n=Zh(e),a=[];for(;a.length<1800;){const l=(n()*2-1)*.95,c=(n()*2-1)*.75,d=(n()*2-1)*1.05,p=ov(l,c,d);p>.42&&p<.72&&a.push([l,c,d])}const i=[];if(t<=0)return i;let o=0,s=-1/0;for(let l=0;l<a.length;l++){const c=a[l][2]+a[l][1]*.5-Math.abs(a[l][0])*.2;c>s&&(s=c,o=l)}i.push(a[o]);const r=a.map(l=>uC(l,a[o]));for(;i.length<t;){let l=0,c=-1;for(let d=0;d<a.length;d++)r[d]>c&&(c=r[d],l=d);if(c<=0){i.push(a[i.length*37%a.length]);continue}i.push(a[l]);for(let d=0;d<a.length;d++)r[d]=Math.min(r[d],uC(a[d],a[l]))}return i}function uC(t,e){const n=t[0]-e[0],a=t[1]-e[1],i=t[2]-e[2];return n*n+a*a+i*i}function lV(t,e,n){const a=Zh(ik(t));for(let i=0;i<40;i++){const o=n*(1+i*.03),s=e[0]+ok(a)*o*.8,r=e[1]+ok(a)*o*.8,l=e[2]+ok(a)*o*1.15;if(!(Math.sign(s)!==Math.sign(e[0])&&Math.abs(e[0])>.06)&&oV(s,r,l,.9))return[s,r,l]}return[e[0],e[1],e[2]]}function cV(t,e){const n=.62/Math.cbrt(Math.max(1,e));return Math.min(.3,Math.max(.045,n*(.22+.12*Math.cbrt(t))))}const fC=[3.05,1.35,1.55],Jh=[0,-.02,-.04],dV=42;function mC(t){return t<.9?5.2:t<1.3?4.1:3.6}const ko=110,Qh=6e3,sv=12*ko*2,pV=5*6e4,hV=5e3,uV=2e3,fV=`
|
|
11715
|
+
}`;class IG{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n){if(this.texture===null){const a=new w_(e.texture);(e.depthNear!==n.depthNear||e.depthFar!==n.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=a}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,a=new na({vertexShader:RG,fragmentShader:PG,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new hs(new Xg(20,20),a)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class NG extends js{constructor(e,n){super();const a=this;let i=null,o=1,s=null,r="local-floor",l=1,c=null,d=null,p=null,h=null,u=null,f=null;const v=typeof XRWebGLBinding<"u",g=new IG,m={},b=n.getContextAttributes();let k=null,y=null;const w=[],A=[],_=new ut;let S=null,T=null;const E=new si;E.viewport=new yn;const P=new si;P.viewport=new yn;const R=[E,P],B=new wq;let D=null,$=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(de){let Z=w[de];return Z===void 0&&(Z=new _1,w[de]=Z),Z.getTargetRaySpace()},this.getControllerGrip=function(de){let Z=w[de];return Z===void 0&&(Z=new _1,w[de]=Z),Z.getGripSpace()},this.getHand=function(de){let Z=w[de];return Z===void 0&&(Z=new _1,w[de]=Z),Z.getHandSpace()};function G(de){const Z=A.indexOf(de.inputSource);if(Z===-1)return;const Ne=w[Z];Ne!==void 0&&(Ne.update(de.inputSource,de.frame,c||s),Ne.dispatchEvent({type:de.type,data:de.inputSource}))}function O(){i.removeEventListener("select",G),i.removeEventListener("selectstart",G),i.removeEventListener("selectend",G),i.removeEventListener("squeeze",G),i.removeEventListener("squeezestart",G),i.removeEventListener("squeezeend",G),i.removeEventListener("end",O),i.removeEventListener("inputsourceschange",J);for(let de=0;de<w.length;de++){const Z=A[de];Z!==null&&(A[de]=null,w[de].disconnect(Z))}D=null,$=null,g.reset();for(const de in m)delete m[de];if(e.setRenderTarget(k),u=null,h=null,p=null,i=null,y=null,st.stop(),a.isPresenting=!1,e.setPixelRatio(S),e.setSize(_.width,_.height,!1),T!==null){const de=T.camera;de.fov=T.fov,de.zoom=T.zoom,de.updateProjectionMatrix(),T=null}a.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(de){o=de,a.isPresenting===!0&&it("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(de){r=de,a.isPresenting===!0&&it("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||s},this.setReferenceSpace=function(de){c=de},this.getBaseLayer=function(){return h!==null?h:u},this.getBinding=function(){return p===null&&v&&(p=new XRWebGLBinding(i,n)),p},this.getFrame=function(){return f},this.getSession=function(){return i},this.setSession=async function(de){if(i=de,i!==null){if(k=e.getRenderTarget(),i.addEventListener("select",G),i.addEventListener("selectstart",G),i.addEventListener("selectend",G),i.addEventListener("squeeze",G),i.addEventListener("squeezestart",G),i.addEventListener("squeezeend",G),i.addEventListener("end",O),i.addEventListener("inputsourceschange",J),b.xrCompatible!==!0&&await n.makeXRCompatible(),S=e.getPixelRatio(),e.getSize(_),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Ne=null,Xe=null,De=null;b.depth&&(De=b.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,Ne=b.stencil?ol:is,Xe=b.stencil?Dh:fo);const be={colorFormat:n.RGBA8,depthFormat:De,scaleFactor:o};p=this.getBinding(),h=p.createProjectionLayer(be),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new Mi(h.textureWidth,h.textureHeight,{format:Si,type:ai,depthTexture:new Vh(h.textureWidth,h.textureHeight,Xe,void 0,void 0,void 0,void 0,void 0,void 0,Ne),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1,storeMultisampledDepthBuffer:h.ignoreDepthValues===!1,storeMultisampledStencilBuffer:h.ignoreDepthValues===!1})}else{const Ne={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:o};u=new XRWebGLLayer(i,n,Ne),i.updateRenderState({baseLayer:u}),e.setPixelRatio(1),e.setSize(u.framebufferWidth,u.framebufferHeight,!1),y=new Mi(u.framebufferWidth,u.framebufferHeight,{format:Si,type:ai,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,storeMultisampledDepthBuffer:u.ignoreDepthValues===!1,storeMultisampledStencilBuffer:u.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(l),c=null,s=await i.requestReferenceSpace(r),st.setContext(i),st.start(),a.isPresenting=!0,a.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function J(de){for(let Z=0;Z<de.removed.length;Z++){const Ne=de.removed[Z],Xe=A.indexOf(Ne);Xe>=0&&(A[Xe]=null,w[Xe].disconnect(Ne))}for(let Z=0;Z<de.added.length;Z++){const Ne=de.added[Z];let Xe=A.indexOf(Ne);if(Xe===-1){for(let be=0;be<w.length;be++)if(be>=A.length){A.push(Ne),Xe=be;break}else if(A[be]===null){A[be]=Ne,Xe=be;break}if(Xe===-1)break}const De=w[Xe];De&&De.connect(Ne)}}const ne=new Q,ae=new Q;function q(de,Z,Ne){ne.setFromMatrixPosition(Z.matrixWorld),ae.setFromMatrixPosition(Ne.matrixWorld);const Xe=ne.distanceTo(ae),De=Z.projectionMatrix.elements,be=Ne.projectionMatrix.elements,ft=De[14]/(De[10]-1),rt=De[14]/(De[10]+1),vt=(De[9]+1)/De[5],Rt=(De[9]-1)/De[5],mt=(De[8]-1)/De[0],Gt=(be[8]+1)/be[0],ln=ft*mt,cn=ft*Gt,Ut=Xe/(-mt+Gt),Jt=Ut*-mt;if(Z.matrixWorld.decompose(de.position,de.quaternion,de.scale),de.translateX(Jt),de.translateZ(Ut),de.matrixWorld.compose(de.position,de.quaternion,de.scale),de.matrixWorldInverse.copy(de.matrixWorld).invert(),De[10]===-1)de.projectionMatrix.copy(Z.projectionMatrix),de.projectionMatrixInverse.copy(Z.projectionMatrixInverse);else{const K=ft+Ut,dn=rt+Ut,zt=ln-Jt,F=cn+(Xe-Jt),M=vt*rt/dn*K,ee=Rt*rt/dn*K;de.projectionMatrix.makePerspective(zt,F,M,ee,K,dn),de.projectionMatrixInverse.copy(de.projectionMatrix).invert()}}function we(de,Z){Z===null?de.matrixWorld.copy(de.matrix):de.matrixWorld.multiplyMatrices(Z.matrixWorld,de.matrix),de.matrixWorldInverse.copy(de.matrixWorld).invert()}this.updateCamera=function(de){if(i===null)return;let Z=de.near,Ne=de.far;g.texture!==null&&(g.depthNear>0&&(Z=g.depthNear),g.depthFar>0&&(Ne=g.depthFar)),B.near=P.near=E.near=Z,B.far=P.far=E.far=Ne,(D!==B.near||$!==B.far)&&(i.updateRenderState({depthNear:B.near,depthFar:B.far}),D=B.near,$=B.far),B.layers.mask=de.layers.mask|6,E.layers.mask=B.layers.mask&-5,P.layers.mask=B.layers.mask&-3;const Xe=de.parent,De=B.cameras;we(B,Xe);for(let be=0;be<De.length;be++)we(De[be],Xe);De.length===2?q(B,E,P):B.projectionMatrix.copy(E.projectionMatrix),T===null&&de.isPerspectiveCamera&&(T={camera:de,fov:de.fov,zoom:de.zoom}),Re(de,B,Xe)};function Re(de,Z,Ne){Ne===null?de.matrix.copy(Z.matrixWorld):(de.matrix.copy(Ne.matrixWorld),de.matrix.invert(),de.matrix.multiply(Z.matrixWorld)),de.matrix.decompose(de.position,de.quaternion,de.scale),de.updateMatrixWorld(!0),de.projectionMatrix.copy(Z.projectionMatrix),de.projectionMatrixInverse.copy(Z.projectionMatrixInverse),de.isPerspectiveCamera&&(de.fov=y1*2*Math.atan(1/de.projectionMatrix.elements[5]),de.zoom=1)}this.getCamera=function(){return B},this.getFoveation=function(){if(!(h===null&&u===null))return l},this.setFoveation=function(de){l=de,h!==null&&(h.fixedFoveation=de),u!==null&&u.fixedFoveation!==void 0&&(u.fixedFoveation=de)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(B)},this.getCameraTexture=function(de){return m[de]};let ot=null;function Qe(de,Z){if(d=Z.getViewerPose(c||s),f=Z,d!==null){const Ne=d.views;u!==null&&(e.setRenderTargetFramebuffer(y,u.framebuffer),e.setRenderTarget(y));let Xe=!1;Ne.length!==B.cameras.length&&(B.cameras.length=0,Xe=!0);for(let rt=0;rt<Ne.length;rt++){const vt=Ne[rt];let Rt=null;if(u!==null)Rt=u.getViewport(vt);else{const Gt=p.getViewSubImage(h,vt);Rt=Gt.viewport,rt===0&&(e.setRenderTargetTextures(y,Gt.colorTexture,Gt.depthStencilTexture),e.setRenderTarget(y))}let mt=R[rt];mt===void 0&&(mt=new si,mt.layers.enable(rt),mt.viewport=new yn,R[rt]=mt),mt.matrix.fromArray(vt.transform.matrix),mt.matrix.decompose(mt.position,mt.quaternion,mt.scale),mt.projectionMatrix.fromArray(vt.projectionMatrix),mt.projectionMatrixInverse.copy(mt.projectionMatrix).invert(),mt.viewport.set(Rt.x,Rt.y,Rt.width,Rt.height),rt===0&&(B.matrix.copy(mt.matrix),B.matrix.decompose(B.position,B.quaternion,B.scale)),Xe===!0&&B.cameras.push(mt)}const De=i.enabledFeatures;if(De&&De.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&v){p=a.getBinding();const rt=p.getDepthInformation(Ne[0]);rt&&rt.isValid&&rt.texture&&g.init(rt,i.renderState)}if(De&&De.includes("camera-access")&&v){e.state.unbindTexture(),p=a.getBinding();for(let rt=0;rt<Ne.length;rt++){const vt=Ne[rt].camera;if(vt){let Rt=m[vt];Rt||(Rt=new w_,m[vt]=Rt);const mt=p.getCameraImage(vt);Rt.sourceTexture=mt}}}}for(let Ne=0;Ne<w.length;Ne++){const Xe=A[Ne],De=w[Ne];Xe!==null&&De!==void 0&&De.update(Xe,Z,c||s)}ot&&ot(de,Z),Z.detectedPlanes&&a.dispatchEvent({type:"planesdetected",data:Z}),f=null}const st=new R_;st.setAnimationLoop(Qe),this.setAnimationLoop=function(de){ot=de},this.dispose=function(){}}}const zG=new fn,sC=new ht;sC.set(-1,0,0,0,1,0,0,0,1);function DG(t,e){function n(g,m){g.matrixAutoUpdate===!0&&g.updateMatrix(),m.value.copy(g.matrix)}function a(g,m){m.color.getRGB(g.fogColor.value,S_(t)),m.isFog?(g.fogNear.value=m.near,g.fogFar.value=m.far):m.isFogExp2&&(g.fogDensity.value=m.density)}function i(g,m,b,k,y){m.isNodeMaterial?m.uniformsNeedUpdate=!1:m.isMeshBasicMaterial?o(g,m):m.isMeshLambertMaterial?(o(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshToonMaterial?(o(g,m),p(g,m)):m.isMeshPhongMaterial?(o(g,m),d(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshStandardMaterial?(o(g,m),h(g,m),m.isMeshPhysicalMaterial&&u(g,m,y)):m.isMeshMatcapMaterial?(o(g,m),f(g,m)):m.isMeshDepthMaterial?o(g,m):m.isMeshDistanceMaterial?(o(g,m),v(g,m)):m.isMeshNormalMaterial?o(g,m):m.isLineBasicMaterial?(s(g,m),m.isLineDashedMaterial&&r(g,m)):m.isPointsMaterial?l(g,m,b,k):m.isSpriteMaterial?c(g,m):m.isShadowMaterial?(g.color.value.copy(m.color),g.opacity.value=m.opacity):m.isShaderMaterial&&(m.uniformsNeedUpdate=!1)}function o(g,m){g.opacity.value=m.opacity,m.color&&g.diffuse.value.copy(m.color),m.emissive&&g.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity),m.map&&(g.map.value=m.map,n(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,n(m.alphaMap,g.alphaMapTransform)),m.bumpMap&&(g.bumpMap.value=m.bumpMap,n(m.bumpMap,g.bumpMapTransform),g.bumpScale.value=m.bumpScale,m.side===Ea&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,n(m.normalMap,g.normalMapTransform),g.normalScale.value.copy(m.normalScale),m.side===Ea&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,n(m.displacementMap,g.displacementMapTransform),g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias),m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap,n(m.emissiveMap,g.emissiveMapTransform)),m.specularMap&&(g.specularMap.value=m.specularMap,n(m.specularMap,g.specularMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest);const b=e.get(m),k=b.envMap,y=b.envMapRotation;k&&(g.envMap.value=k,g.envMapRotation.value.setFromMatrix4(zG.makeRotationFromEuler(y)).transpose(),k.isCubeTexture&&k.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(sC),g.reflectivity.value=m.reflectivity,g.ior.value=m.ior,g.refractionRatio.value=m.refractionRatio),m.lightMap&&(g.lightMap.value=m.lightMap,g.lightMapIntensity.value=m.lightMapIntensity,n(m.lightMap,g.lightMapTransform)),m.aoMap&&(g.aoMap.value=m.aoMap,g.aoMapIntensity.value=m.aoMapIntensity,n(m.aoMap,g.aoMapTransform))}function s(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,m.map&&(g.map.value=m.map,n(m.map,g.mapTransform))}function r(g,m){g.dashSize.value=m.dashSize,g.totalSize.value=m.dashSize+m.gapSize,g.scale.value=m.scale}function l(g,m,b,k){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.size.value=m.size*b,g.scale.value=k*.5,m.map&&(g.map.value=m.map,n(m.map,g.uvTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,n(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function c(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.rotation.value=m.rotation,m.map&&(g.map.value=m.map,n(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,n(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function d(g,m){g.specular.value.copy(m.specular),g.shininess.value=Math.max(m.shininess,1e-4)}function p(g,m){m.gradientMap&&(g.gradientMap.value=m.gradientMap)}function h(g,m){g.metalness.value=m.metalness,m.metalnessMap&&(g.metalnessMap.value=m.metalnessMap,n(m.metalnessMap,g.metalnessMapTransform)),g.roughness.value=m.roughness,m.roughnessMap&&(g.roughnessMap.value=m.roughnessMap,n(m.roughnessMap,g.roughnessMapTransform)),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)}function u(g,m,b){g.ior.value=m.ior,m.sheen>0&&(g.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),g.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(g.sheenColorMap.value=m.sheenColorMap,n(m.sheenColorMap,g.sheenColorMapTransform)),m.sheenRoughnessMap&&(g.sheenRoughnessMap.value=m.sheenRoughnessMap,n(m.sheenRoughnessMap,g.sheenRoughnessMapTransform))),m.clearcoat>0&&(g.clearcoat.value=m.clearcoat,g.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(g.clearcoatMap.value=m.clearcoatMap,n(m.clearcoatMap,g.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,n(m.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(g.clearcoatNormalMap.value=m.clearcoatNormalMap,n(m.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===Ea&&g.clearcoatNormalScale.value.negate())),m.dispersion>0&&(g.dispersion.value=m.dispersion),m.retroreflectivity>0&&(g.retroreflectivity.value=m.retroreflectivity),m.iridescence>0&&(g.iridescence.value=m.iridescence,g.iridescenceIOR.value=m.iridescenceIOR,g.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(g.iridescenceMap.value=m.iridescenceMap,n(m.iridescenceMap,g.iridescenceMapTransform)),m.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=m.iridescenceThicknessMap,n(m.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),m.transmission>0&&(g.transmission.value=m.transmission,g.transmissionSamplerMap.value=b.texture,g.transmissionSamplerSize.value.set(b.width,b.height),m.transmissionMap&&(g.transmissionMap.value=m.transmissionMap,n(m.transmissionMap,g.transmissionMapTransform)),g.thickness.value=m.thickness,m.thicknessMap&&(g.thicknessMap.value=m.thicknessMap,n(m.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=m.attenuationDistance,g.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(g.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(g.anisotropyMap.value=m.anisotropyMap,n(m.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=m.specularIntensity,g.specularColor.value.copy(m.specularColor),m.specularColorMap&&(g.specularColorMap.value=m.specularColorMap,n(m.specularColorMap,g.specularColorMapTransform)),m.specularIntensityMap&&(g.specularIntensityMap.value=m.specularIntensityMap,n(m.specularIntensityMap,g.specularIntensityMapTransform))}function f(g,m){m.matcap&&(g.matcap.value=m.matcap)}function v(g,m){const b=e.get(m).light;g.referencePosition.value.setFromMatrixPosition(b.matrixWorld),g.nearDistance.value=b.shadow.camera.near,g.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:a,refreshMaterialUniforms:i}}function OG(t,e,n,a){let i={},o={},s=[];const r=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function l(y,w){const A=w.program;a.uniformBlockBinding(y,A)}function c(y,w){let A=i[y.id];A===void 0&&(g(y),A=d(y),i[y.id]=A,y.addEventListener("dispose",b));const _=w.program;a.updateUBOMapping(y,_);const S=e.render.frame;o[y.id]!==S&&(h(y),o[y.id]=S)}function d(y){const w=p();y.__bindingPointIndex=w;const A=t.createBuffer(),_=y.__size,S=y.usage;return t.bindBuffer(t.UNIFORM_BUFFER,A),t.bufferData(t.UNIFORM_BUFFER,_,S),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,w,A),A}function p(){for(let y=0;y<r;y++)if(s.indexOf(y)===-1)return s.push(y),y;return Ot("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(y){const w=i[y.id],A=y.uniforms,_=y.__cache;t.bindBuffer(t.UNIFORM_BUFFER,w);for(let S=0,T=A.length;S<T;S++){const E=A[S];if(Array.isArray(E))for(let P=0,R=E.length;P<R;P++)u(E[P],S,P,_);else u(E,S,0,_)}t.bindBuffer(t.UNIFORM_BUFFER,null)}function u(y,w,A,_){if(v(y,w,A,_)===!0){const S=y.__offset,T=y.value;if(Array.isArray(T)){let E=0;for(let P=0;P<T.length;P++){const R=T[P],B=m(R);f(R,y.__data,E),typeof R!="number"&&typeof R!="boolean"&&!R.isMatrix3&&!ArrayBuffer.isView(R)&&(E+=B.storage/Float32Array.BYTES_PER_ELEMENT)}}else f(T,y.__data,0);t.bufferSubData(t.UNIFORM_BUFFER,S,y.__data)}}function f(y,w,A){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,A)}function v(y,w,A,_){const S=y.value,T=w+"_"+A;if(_[T]===void 0)return typeof S=="number"||typeof S=="boolean"?_[T]=S:ArrayBuffer.isView(S)?_[T]=S.slice():_[T]=S.clone(),!0;{const E=_[T];if(typeof S=="number"||typeof S=="boolean"){if(E!==S)return _[T]=S,!0}else{if(ArrayBuffer.isView(S))return!0;if(E.equals(S)===!1)return E.copy(S),!0}}return!1}function g(y){const w=y.uniforms;let A=0;const _=16;for(let T=0,E=w.length;T<E;T++){const P=Array.isArray(w[T])?w[T]:[w[T]];for(let R=0,B=P.length;R<B;R++){const D=P[R],$=Array.isArray(D.value)?D.value:[D.value];for(let G=0,O=$.length;G<O;G++){const J=$[G],ne=m(J),ae=A%_,q=ae%ne.boundary,we=ae+q;A+=q,we!==0&&_-we<ne.storage&&(A+=_-we),D.__data=new Float32Array(ne.storage/Float32Array.BYTES_PER_ELEMENT),D.__offset=A,A+=ne.storage}}}const S=A%_;return S>0&&(A+=_-S),y.__size=A,y.__cache={},this}function m(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?it("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):it("WebGLRenderer: Unsupported uniform value type.",y),w}function b(y){const w=y.target;w.removeEventListener("dispose",b);const A=s.indexOf(w.__bindingPointIndex);s.splice(A,1),t.deleteBuffer(i[w.id]),delete i[w.id],delete o[w.id]}function k(){for(const y in i)t.deleteBuffer(i[y]);s=[],i={},o={}}return{bind:l,update:c,dispose:k}}const $G=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let wo=null;function FG(){return wo===null&&(wo=new rq($G,16,16,sl,go),wo.name="DFG_LUT",wo.minFilter=Qn,wo.magFilter=Qn,wo.wrapS=as,wo.wrapT=as,wo.generateMipmaps=!1,wo.needsUpdate=!0),wo}class UG{constructor(e={}){const{canvas:n=zH(),context:a=null,depth:i=!0,stencil:o=!1,alpha:s=!1,antialias:r=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:p=!1,reversedDepthBuffer:h=!1,outputBufferType:u=ai}=e;this.isWebGLRenderer=!0;let f;if(a!==null){if(typeof WebGLRenderingContext<"u"&&a instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=a.getContextAttributes().alpha}else f=s;const v=u,g=new Set([Uw,Fw,$w]),m=new Set([ai,fo,zh,Dh,Dw,Ow]),b=new Uint32Array(4),k=new Int32Array(4),y=new Q;let w=null,A=null;const _=[],S=[];let T=null;this.domElement=n,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=uo,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let P=!1,R=null,B=null,D=null,$=null;this._outputColorSpace=ii;let G=0,O=0,J=null,ne=-1,ae=null;const q=new yn,we=new yn;let Re=null;const ot=new $t(0);let Qe=0,st=n.width,de=n.height,Z=1,Ne=null,Xe=null;const De=new yn(0,0,st,de),be=new yn(0,0,st,de);let ft=!1;const rt=new u_;let vt=!1,Rt=!1;const mt=new fn,Gt=new Q,ln=new yn,cn={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ut=!1;function Jt(){return J===null?Z:1}let K=a;function dn(L,X){return n.getContext(L,X)}let zt,F,M,ee,se,he,Le,ze,ge,z,j,ce,I,U,Y,pe,Ie,W,_e,fe,Me,Pe,ke;try{const L={alpha:!0,depth:i,stencil:o,antialias:r,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:d,failIfMajorPerformanceCaveat:p};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${kw}`),n.addEventListener("webglcontextlost",at,!1),n.addEventListener("webglcontextrestored",dt,!1),n.addEventListener("webglcontextcreationerror",va,!1),K===null){const X="webgl2";if(K=dn(X,L),K===null)throw dn(X)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}Ce()}catch(L){throw n.removeEventListener("webglcontextlost",at,!1),n.removeEventListener("webglcontextrestored",dt,!1),n.removeEventListener("webglcontextcreationerror",va,!1),Ot("WebGLRenderer: "+L.message),L}function Ce(){zt=new F7(K),zt.init(),Me=new LG(K,zt),F=new C7(K,zt,e,Me),M=new _G(K,zt),F.reversedDepthBuffer&&h&&M.buffers.depth.setReversed(!0),B=K.createFramebuffer(),D=K.createFramebuffer(),$=K.createFramebuffer(),ee=new H7(K),se=new fG,he=new CG(K,zt,M,se,F,Me,ee),Le=new $7(E),ze=new Mq(K),Pe=new E7(K,ze),ge=new U7(K,ze,ee,Pe),z=new W7(K,ge,ze,Pe,ee),W=new q7(K,F,he),Y=new L7(se),j=new uG(E,Le,zt,F,Pe,Y),ce=new DG(E,se),I=new gG,U=new kG(zt),Ie=new T7(E,Le,M,z,f,l),pe=new EG(E,z,F),ke=new OG(K,ee,F,M),_e=new _7(K,zt,ee),fe=new B7(K,zt,ee),ee.programs=j.programs,E.capabilities=F,E.extensions=zt,E.properties=se,E.renderLists=I,E.shadowMap=pe,E.state=M,E.info=ee}v!==ai&&(T=new V7(v,n.width,n.height,r,i,o));const Ee=new NG(E,K);this.xr=Ee,this.getContext=function(){return K},this.getContextAttributes=function(){return K.getContextAttributes()},this.forceContextLoss=function(){const L=zt.get("WEBGL_lose_context");L&&L.loseContext()},this.forceContextRestore=function(){const L=zt.get("WEBGL_lose_context");L&&L.restoreContext()},this.getPixelRatio=function(){return Z},this.setPixelRatio=function(L){L!==void 0&&(Z=L,this.setSize(st,de,!1))},this.getSize=function(L){return L.set(st,de)},this.setSize=function(L,X,le=!0){if(Ee.isPresenting){it("WebGLRenderer: Can't change size while VR device is presenting.");return}st=L,de=X,n.width=Math.floor(L*Z),n.height=Math.floor(X*Z),le===!0&&(n.style.width=L+"px",n.style.height=X+"px"),T!==null&&T.setSize(n.width,n.height),this.setViewport(0,0,L,X)},this.getDrawingBufferSize=function(L){return L.set(st*Z,de*Z).floor()},this.setDrawingBufferSize=function(L,X,le){st=L,de=X,Z=le,n.width=Math.floor(L*le),n.height=Math.floor(X*le),this.setViewport(0,0,L,X)},this.setEffects=function(L){if(v===ai){Ot("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(L){for(let X=0;X<L.length;X++)if(L[X].isOutputPass===!0){it("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}T.setEffects(L||[])},this.getCurrentViewport=function(L){return L.copy(q)},this.getViewport=function(L){return L.copy(De)},this.setViewport=function(L,X,le,ie){L.isVector4?De.set(L.x,L.y,L.z,L.w):De.set(L,X,le,ie),M.viewport(q.copy(De).multiplyScalar(Z).round())},this.getScissor=function(L){return L.copy(be)},this.setScissor=function(L,X,le,ie){L.isVector4?be.set(L.x,L.y,L.z,L.w):be.set(L,X,le,ie),M.scissor(we.copy(be).multiplyScalar(Z).round())},this.getScissorTest=function(){return ft},this.setScissorTest=function(L){M.setScissorTest(ft=L)},this.setOpaqueSort=function(L){Ne=L},this.setTransparentSort=function(L){Xe=L},this.getClearColor=function(L){return L.copy(Ie.getClearColor())},this.setClearColor=function(){Ie.setClearColor(...arguments)},this.getClearAlpha=function(){return Ie.getClearAlpha()},this.setClearAlpha=function(){Ie.setClearAlpha(...arguments)},this.clear=function(L=!0,X=!0,le=!0){let ie=0;if(L){let oe=!1;if(J!==null){const qe=J.texture.format;oe=g.has(qe)}if(oe){const qe=J.texture.type,Ye=m.has(qe),Fe=Ie.getClearColor(),Ke=Ie.getClearAlpha(),et=Fe.r,yt=Fe.g,Mt=Fe.b;Ye?(b[0]=et,b[1]=yt,b[2]=Mt,b[3]=Ke,K.clearBufferuiv(K.COLOR,0,b)):(k[0]=et,k[1]=yt,k[2]=Mt,k[3]=Ke,K.clearBufferiv(K.COLOR,0,k))}else ie|=K.COLOR_BUFFER_BIT}X&&(ie|=K.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),le&&(ie|=K.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),ie!==0&&K.clear(ie)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(L){L.setRenderer(this),R=L},this.dispose=function(){n.removeEventListener("webglcontextlost",at,!1),n.removeEventListener("webglcontextrestored",dt,!1),n.removeEventListener("webglcontextcreationerror",va,!1),Ie.dispose(),I.dispose(),U.dispose(),se.dispose(),Le.dispose(),z.dispose(),Pe.dispose(),ke.dispose(),j.dispose(),Ee.dispose(),Ee.removeEventListener("sessionstart",_6),Ee.removeEventListener("sessionend",C6),yl.stop()};function at(L){L.preventDefault(),G5("WebGLRenderer: Context Lost."),P=!0}function dt(){G5("WebGLRenderer: Context Restored."),P=!1;const L=ee.autoReset,X=pe.enabled,le=pe.autoUpdate,ie=pe.needsUpdate,oe=pe.type;Ce(),ee.autoReset=L,pe.enabled=X,pe.autoUpdate=le,pe.needsUpdate=ie,pe.type=oe}function va(L){Ot("WebGLRenderer: A WebGL context could not be created. Reason: ",L.statusMessage)}function Ao(L){const X=L.target;X.removeEventListener("dispose",Ao),yX(X)}function yX(L){wX(L),se.remove(L)}function wX(L){const X=se.get(L).programs;X!==void 0&&(X.forEach(function(le){j.releaseProgram(le)}),L.isShaderMaterial&&j.releaseShaderCache(L))}this.renderBufferDirect=function(L,X,le,ie,oe,qe){X===null&&(X=cn);const Ye=oe.isMesh&&oe.matrixWorld.determinantAffine()<0,Fe=MX(L,X,le,ie,oe);M.setMaterial(ie,Ye);let Ke=le.index,et=1;if(ie.wireframe===!0){if(Ke=ge.getWireframeAttribute(le),Ke===void 0)return;et=2}const yt=le.drawRange,Mt=le.attributes.position;let Ze=yt.start*et,Bt=(yt.start+yt.count)*et;qe!==null&&(Ze=Math.max(Ze,qe.start*et),Bt=Math.min(Bt,(qe.start+qe.count)*et)),Ke!==null?(Ze=Math.max(Ze,0),Bt=Math.min(Bt,Ke.count)):Mt!=null&&(Ze=Math.max(Ze,0),Bt=Math.min(Bt,Mt.count));const Rn=Bt-Ze;if(Rn<0||Rn===1/0)return;Pe.setup(oe,ie,Fe,le,Ke);let on,Kt=_e;if(Ke!==null&&(on=ze.get(Ke),Kt=fe,Kt.setIndex(on)),oe.isMesh)ie.wireframe===!0?(M.setLineWidth(ie.wireframeLinewidth*Jt()),Kt.setMode(K.LINES)):Kt.setMode(K.TRIANGLES);else if(oe.isLine){let oa=ie.linewidth;oa===void 0&&(oa=1),M.setLineWidth(oa*Jt()),oe.isLineSegments?Kt.setMode(K.LINES):oe.isLineLoop?Kt.setMode(K.LINE_LOOP):Kt.setMode(K.LINE_STRIP)}else oe.isPoints?Kt.setMode(K.POINTS):oe.isSprite&&Kt.setMode(K.TRIANGLES);if(oe.isBatchedMesh)if(zt.get("WEBGL_multi_draw"))Kt.renderMultiDraw(oe._multiDrawStarts,oe._multiDrawCounts,oe._multiDrawCount);else{const oa=oe._multiDrawStarts,je=oe._multiDrawCounts,xa=oe._multiDrawCount,Dt=Ke?ze.get(Ke).bytesPerElement:1,li=se.get(ie).currentProgram.getUniforms();for(let To=0;To<xa;To++)li.setValue(K,"_gl_DrawID",To),Kt.render(oa[To]/Dt,je[To])}else if(oe.isInstancedMesh)Kt.renderInstances(Ze,Rn,oe.count);else if(le.isInstancedBufferGeometry){const oa=le._maxInstanceCount!==void 0?le._maxInstanceCount:1/0,je=Math.min(le.instanceCount,oa);Kt.renderInstances(Ze,Rn,je)}else Kt.render(Ze,Rn)};function E6(L,X,le,ie){R!==null&&L.isNodeMaterial&&R.setObject(ie,L),vt===!0&&Y.setState(L,le,!1),L.transparent===!0&&L.side===es&&L.forceSinglePass===!1?(L.side=Ea,L.needsUpdate=!0,Pv(L,X,ie),L.side=nl,L.needsUpdate=!0,Pv(L,X,ie),L.side=es):Pv(L,X,ie)}this.compile=function(L,X,le=null){le===null&&(le=L),R!==null&&R.renderStart(L,X,le),A=U.get(le),A.init(X),S.push(A),le.traverseVisible(function(oe){oe.isLight&&oe.layers.test(X.layers)&&(A.pushLight(oe),oe.castShadow&&A.pushShadow(oe))}),L!==le&&L.traverseVisible(function(oe){oe.isLight&&oe.layers.test(X.layers)&&(A.pushLight(oe),oe.castShadow&&A.pushShadow(oe))}),A.setupLights(),R!==null&&R.updateLights(A.state.lightsArray),Rt=this.localClippingEnabled,vt=Y.init(this.clippingPlanes,Rt),vt===!0&&Y.setGlobalState(this.clippingPlanes,X),R!==null&&pe.render(A.state.shadowsArray,le,X);const ie=new Set;return L.traverse(function(oe){if(!(oe.isMesh||oe.isPoints||oe.isLine||oe.isSprite))return;const qe=oe.material;if(qe)if(Array.isArray(qe))for(let Ye=0;Ye<qe.length;Ye++){const Fe=qe[Ye];E6(Fe,le,X,oe),ie.add(Fe)}else E6(qe,le,X,oe),ie.add(qe)}),A=S.pop(),R!==null&&R.renderEnd(),ie},this.compileAsync=function(L,X,le=null){const ie=this.compile(L,X,le);return new Promise(oe=>{function qe(){if(ie.forEach(function(Ye){const Ke=se.get(Ye).currentProgram;(Ke===void 0||Ke.isReady())&&ie.delete(Ye)}),ie.size===0){oe(L);return}setTimeout(qe,10)}zt.get("KHR_parallel_shader_compile")!==null?qe():setTimeout(qe,10)})};let Kk=null;function kX(L){Kk&&Kk(L)}function _6(){yl.stop()}function C6(){yl.start()}const yl=new R_;yl.setAnimationLoop(kX),typeof self<"u"&&yl.setContext(self),this.setAnimationLoop=function(L){Kk=L,Ee.setAnimationLoop(L),L===null?yl.stop():yl.start()},Ee.addEventListener("sessionstart",_6),Ee.addEventListener("sessionend",C6),this.render=function(L,X){if(X!==void 0&&X.isCamera!==!0){Ot("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(P===!0)return;R!==null&&R.renderStart(L,X);const le=Ee.enabled===!0&&Ee.isPresenting===!0,ie=T!==null&&(J===null||le)&&T.begin(E,J);if(L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),X.parent===null&&X.matrixWorldAutoUpdate===!0&&X.updateMatrixWorld(),Ee.enabled===!0&&Ee.isPresenting===!0&&(T===null||T.isCompositing()===!1)&&(Ee.cameraAutoUpdate===!0&&Ee.updateCamera(X),X=Ee.getCamera()),L.isScene===!0&&L.onBeforeRender(E,L,X,J),A=U.get(L,S.length),A.init(X),A.state.textureUnits=he.getTextureUnits(),S.push(A),mt.multiplyMatrices(X.projectionMatrix,X.matrixWorldInverse),rt.setFromProjectionMatrix(mt,vo,X.reversedDepth),Rt=this.localClippingEnabled,vt=Y.init(this.clippingPlanes,Rt),w=I.get(L,_.length),w.init(),_.push(w),Ee.enabled===!0&&Ee.isPresenting===!0){const Ye=E.xr.getDepthSensingMesh();Ye!==null&&Zk(Ye,X,-1/0,E.sortObjects)}Zk(L,X,0,E.sortObjects),w.finish(),R!==null&&R.updateLights(A.state.lightsArray),E.sortObjects===!0&&w.sort(Ne,Xe),Ut=Ee.enabled===!1||Ee.isPresenting===!1||Ee.hasDepthSensing()===!1,Ut&&Ie.addToRenderList(w,L),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),vt===!0&&Y.beginShadows();const oe=A.state.shadowsArray;if(pe.render(oe,L,X),vt===!0&&Y.endShadows(),(ie&&T.hasRenderPass())===!1){const Ye=w.opaque,Fe=w.transmissive;if(A.setupLights(),X.isArrayCamera){const Ke=X.cameras;if(Fe.length>0)for(let et=0,yt=Ke.length;et<yt;et++){const Mt=Ke[et];R6(Ye,Fe,L,Mt)}Ut&&Ie.render(L);for(let et=0,yt=Ke.length;et<yt;et++){const Mt=Ke[et];L6(w,L,Mt,Mt.viewport)}}else Fe.length>0&&R6(Ye,Fe,L,X),Ut&&Ie.render(L),L6(w,L,X)}J!==null&&O===0&&(he.updateMultisampleRenderTarget(J),he.updateRenderTargetMipmap(J)),ie&&T.end(E),L.isScene===!0&&L.onAfterRender(E,L,X),Pe.resetDefaultState(),ne=-1,ae=null,S.pop(),S.length>0?(A=S[S.length-1],he.setTextureUnits(A.state.textureUnits),vt===!0&&Y.setGlobalState(E.clippingPlanes,A.state.camera)):A=null,_.pop(),_.length>0?w=_[_.length-1]:w=null,R!==null&&R.renderEnd()};function Zk(L,X,le,ie){if(L.visible===!1)return;if(L.layers.test(X.layers)){if(L.isGroup)le=L.renderOrder;else if(L.isLOD)L.autoUpdate===!0&&L.update(X);else if(L.isLightProbeGrid)A.pushLightProbeGrid(L);else if(L.isLight)A.pushLight(L),L.castShadow&&A.pushShadow(L);else if(L.isSprite){if(!L.frustumCulled||L.intersectsFrustum(rt)){ie&&ln.setFromMatrixPosition(L.matrixWorld).applyMatrix4(mt);const Ye=z.update(L),Fe=L.material;Fe.visible&&w.push(L,Ye,Fe,le,ln.z,null,X)}}else if((L.isMesh||L.isLine||L.isPoints)&&(!L.frustumCulled||L.intersectsFrustum(rt))){const Ye=z.update(L),Fe=L.material;if(ie&&(L.boundingSphere!==void 0?(L.boundingSphere===null&&L.computeBoundingSphere(),ln.copy(L.boundingSphere.center)):(Ye.boundingSphere===null&&Ye.computeBoundingSphere(),ln.copy(Ye.boundingSphere.center)),ln.applyMatrix4(L.matrixWorld).applyMatrix4(mt)),Array.isArray(Fe)){const Ke=Ye.groups;for(let et=0,yt=Ke.length;et<yt;et++){const Mt=Ke[et],Ze=Fe[Mt.materialIndex];Ze&&Ze.visible&&w.push(L,Ye,Ze,le,ln.z,Mt,X)}}else Fe.visible&&w.push(L,Ye,Fe,le,ln.z,null,X)}}const qe=L.children;for(let Ye=0,Fe=qe.length;Ye<Fe;Ye++)Zk(qe[Ye],X,le,ie)}function L6(L,X,le,ie){const{opaque:oe,transmissive:qe,transparent:Ye}=L;A.setupLightsView(le),vt===!0&&Y.setGlobalState(E.clippingPlanes,le),ie&&M.viewport(q.copy(ie)),oe.length>0&&Rv(oe,X,le),qe.length>0&&Rv(qe,X,le),Ye.length>0&&Rv(Ye,X,le),M.buffers.depth.setTest(!0),M.buffers.depth.setMask(!0),M.buffers.color.setMask(!0),M.setPolygonOffset(!1)}function R6(L,X,le,ie){if((le.isScene===!0?le.overrideMaterial:null)!==null)return;if(A.state.transmissionRenderTarget[ie.id]===void 0){const Ze=zt.has("EXT_color_buffer_half_float")||zt.has("EXT_color_buffer_float");A.state.transmissionRenderTarget[ie.id]=new Mi(1,1,{generateMipmaps:!0,type:Ze?go:ai,minFilter:il,samples:Math.max(4,F.samples),stencilBuffer:o,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Ct.workingColorSpace})}const qe=A.state.transmissionRenderTarget[ie.id],Ye=ie.viewport||q;qe.setSize(Ye.z*E.transmissionResolutionScale,Ye.w*E.transmissionResolutionScale);const Fe=E.getRenderTarget(),Ke=E.getActiveCubeFace(),et=E.getActiveMipmapLevel();E.setRenderTarget(qe),E.getClearColor(ot),Qe=E.getClearAlpha(),Qe<1&&E.setClearColor(16777215,.5),E.clear(),Ut&&Ie.render(le);const yt=E.toneMapping;E.toneMapping=uo;const Mt=ie.viewport;if(ie.viewport!==void 0&&(ie.viewport=void 0),A.setupLightsView(ie),vt===!0&&Y.setGlobalState(E.clippingPlanes,ie),Rv(L,le,ie),he.updateMultisampleRenderTarget(qe),he.updateRenderTargetMipmap(qe),zt.has("WEBGL_multisampled_render_to_texture")===!1){let Ze=!1;for(let Bt=0,Rn=X.length;Bt<Rn;Bt++){const on=X[Bt],{object:Kt,geometry:oa,material:je,group:xa}=on;if(je.side===es&&Kt.layers.test(ie.layers)){const Dt=je.side;je.side=Ea,je.needsUpdate=!0,P6(Kt,le,ie,oa,je,xa),je.side=Dt,je.needsUpdate=!0,Ze=!0}}Ze===!0&&(he.updateMultisampleRenderTarget(qe),he.updateRenderTargetMipmap(qe))}E.setRenderTarget(Fe,Ke,et),E.setClearColor(ot,Qe),Mt!==void 0&&(ie.viewport=Mt),E.toneMapping=yt}function Rv(L,X,le){const ie=X.isScene===!0?X.overrideMaterial:null;for(let oe=0,qe=L.length;oe<qe;oe++){const Ye=L[oe],{object:Fe,geometry:Ke,group:et}=Ye;let yt=Ye.material;yt.allowOverride===!0&&ie!==null&&(yt=ie),Fe.layers.test(le.layers)&&P6(Fe,X,le,Ke,yt,et)}}function P6(L,X,le,ie,oe,qe){R!==null&&oe.isNodeMaterial&&R.setObject(L,oe),L.onBeforeRender(E,X,le,ie,oe,qe),L.modelViewMatrix.multiplyMatrices(le.matrixWorldInverse,L.matrixWorld),L.normalMatrix.getNormalMatrix(L.modelViewMatrix),oe.onBeforeRender(E,X,le,ie,L,qe),oe.transparent===!0&&oe.side===es&&oe.forceSinglePass===!1?(oe.side=Ea,oe.needsUpdate=!0,E.renderBufferDirect(le,X,ie,oe,L,qe),oe.side=nl,oe.needsUpdate=!0,E.renderBufferDirect(le,X,ie,oe,L,qe),oe.side=es):E.renderBufferDirect(le,X,ie,oe,L,qe),L.onAfterRender(E,X,le,ie,oe,qe)}function Pv(L,X,le){X.isScene!==!0&&(X=cn);const ie=se.get(L),oe=A.state.lights,qe=A.state.shadowsArray,Ye=oe.state.version,Fe=j.getParameters(L,oe.state,qe,X,le,A.state.lightProbeGridArray),Ke=j.getProgramCacheKey(Fe);let et=ie.programs;ie.environment=L.isMeshStandardMaterial||L.isMeshLambertMaterial||L.isMeshPhongMaterial?X.environment:null,ie.fog=X.fog;const yt=L.isMeshStandardMaterial||L.isMeshLambertMaterial&&!L.envMap||L.isMeshPhongMaterial&&!L.envMap;ie.envMap=Le.get(L.envMap||ie.environment,yt),ie.envMapRotation=ie.environment!==null&&L.envMap===null?X.environmentRotation:L.envMapRotation,et===void 0&&(L.addEventListener("dispose",Ao),et=new Map,ie.programs=et);let Mt=et.get(Ke);if(Mt!==void 0){if(ie.currentProgram===Mt&&ie.lightsStateVersion===Ye)return N6(L,Fe),Mt}else Fe.uniforms=j.getUniforms(L),R!==null&&L.isNodeMaterial&&R.build(L,le,Fe),L.onBeforeCompile(Fe,E),Mt=j.acquireProgram(Fe,Ke),et.set(Ke,Mt),ie.uniforms=Fe.uniforms;const Ze=ie.uniforms;return(!L.isShaderMaterial&&!L.isRawShaderMaterial||L.clipping===!0)&&(Ze.clippingPlanes=Y.uniform),N6(L,Fe),ie.needsLights=TX(L),ie.lightsStateVersion=Ye,ie.needsLights&&(Ze.ambientLightColor.value=oe.state.ambient,Ze.lightProbe.value=oe.state.probe,Ze.sunLights.value=oe.state.sun,Ze.sunLightShadows.value=oe.state.sunShadow,Ze.directionalLights.value=oe.state.directional,Ze.directionalLightShadows.value=oe.state.directionalShadow,Ze.spotLights.value=oe.state.spot,Ze.spotLightShadows.value=oe.state.spotShadow,Ze.rectAreaLights.value=oe.state.rectArea,Ze.ltc_1.value=oe.state.rectAreaLTC1,Ze.ltc_2.value=oe.state.rectAreaLTC2,Ze.pointLights.value=oe.state.point,Ze.pointLightShadows.value=oe.state.pointShadow,Ze.hemisphereLights.value=oe.state.hemi,Ze.sunShadowMatrix.value=oe.state.sunShadowMatrix,Ze.sunShadowCascade.value=oe.state.sunShadowCascade,Ze.directionalShadowMatrix.value=oe.state.directionalShadowMatrix,Ze.spotLightMatrix.value=oe.state.spotLightMatrix,Ze.spotLightMap.value=oe.state.spotLightMap,Ze.pointShadowMatrix.value=oe.state.pointShadowMatrix),ie.lightProbeGrid=A.state.lightProbeGridArray.length>0,ie.currentProgram=Mt,ie.uniformsList=null,Mt}function I6(L){if(L.uniformsList===null){const X=L.currentProgram.getUniforms();L.uniformsList=tv.seqWithValue(X.seq,L.uniforms)}return L.uniformsList}function N6(L,X){const le=se.get(L);le.outputColorSpace=X.outputColorSpace,le.batching=X.batching,le.batchingColor=X.batchingColor,le.instancing=X.instancing,le.instancingColor=X.instancingColor,le.instancingMorph=X.instancingMorph,le.skinning=X.skinning,le.morphTargets=X.morphTargets,le.morphNormals=X.morphNormals,le.morphColors=X.morphColors,le.morphTargetsCount=X.morphTargetsCount,le.numClippingPlanes=X.numClippingPlanes,le.numIntersection=X.numClipIntersection,le.vertexAlphas=X.vertexAlphas,le.vertexTangents=X.vertexTangents,le.toneMapping=X.toneMapping}function SX(L,X){if(L.length===0)return null;if(L.length===1)return L[0].texture!==null?L[0]:null;y.setFromMatrixPosition(X.matrixWorld);for(let le=0,ie=L.length;le<ie;le++){const oe=L[le];if(oe.texture!==null&&oe.boundingBox.containsPoint(y))return oe}return null}function MX(L,X,le,ie,oe){X.isScene!==!0&&(X=cn),he.resetTextureUnits();const qe=X.fog,Ye=ie.isMeshStandardMaterial||ie.isMeshLambertMaterial||ie.isMeshPhongMaterial?X.environment:null,Fe=J===null?E.outputColorSpace:J.isXRRenderTarget===!0?J.texture.colorSpace:Ct.workingColorSpace,Ke=ie.isMeshStandardMaterial||ie.isMeshLambertMaterial&&!ie.envMap||ie.isMeshPhongMaterial&&!ie.envMap,et=Le.get(ie.envMap||Ye,Ke),yt=ie.vertexColors===!0&&!!le.attributes.color&&le.attributes.color.itemSize===4,Mt=!!le.attributes.tangent&&(!!ie.normalMap||ie.anisotropy>0),Ze=!!le.morphAttributes.position,Bt=!!le.morphAttributes.normal,Rn=!!le.morphAttributes.color;let on=uo;ie.toneMapped&&(J===null||J.isXRRenderTarget===!0)&&(on=E.toneMapping);const Kt=le.morphAttributes.position||le.morphAttributes.normal||le.morphAttributes.color,oa=Kt!==void 0?Kt.length:0,je=se.get(ie),xa=A.state.lights;if(vt===!0&&(Rt===!0||L!==ae)){const Qt=L===ae&&ie.id===ne;Y.setState(ie,L,Qt)}let Dt=!1;ie.version===je.__version?(je.needsLights&&je.lightsStateVersion!==xa.state.version||je.outputColorSpace!==Fe||oe.isBatchedMesh&&je.batching===!1||!oe.isBatchedMesh&&je.batching===!0||oe.isBatchedMesh&&je.batchingColor===!0&&oe._colorsTexture===null||oe.isBatchedMesh&&je.batchingColor===!1&&oe._colorsTexture!==null||oe.isInstancedMesh&&je.instancing===!1||!oe.isInstancedMesh&&je.instancing===!0||oe.isSkinnedMesh&&je.skinning===!1||!oe.isSkinnedMesh&&je.skinning===!0||oe.isInstancedMesh&&je.instancingColor===!0&&oe.instanceColor===null||oe.isInstancedMesh&&je.instancingColor===!1&&oe.instanceColor!==null||oe.isInstancedMesh&&je.instancingMorph===!0&&oe.morphTexture===null||oe.isInstancedMesh&&je.instancingMorph===!1&&oe.morphTexture!==null||je.envMap!==et||ie.fog===!0&&je.fog!==qe||je.numClippingPlanes!==void 0&&(je.numClippingPlanes!==Y.numPlanes||je.numIntersection!==Y.numIntersection)||je.vertexAlphas!==yt||je.vertexTangents!==Mt||je.morphTargets!==Ze||je.morphNormals!==Bt||je.morphColors!==Rn||je.toneMapping!==on||je.morphTargetsCount!==oa||!!je.lightProbeGrid!=A.state.lightProbeGridArray.length>0)&&(Dt=!0):(Dt=!0,je.__version=ie.version);let li=je.currentProgram;Dt===!0&&(li=Pv(ie,X,oe),R&&ie.isNodeMaterial&&R.onUpdateProgram(ie,li,je));let To=!1,nr=!1,ud=!1;const jt=li.getUniforms(),Mn=je.uniforms;if(M.useProgram(li.program)&&(To=!0,nr=!0,ud=!0),ie.id!==ne&&(ne=ie.id,nr=!0),je.needsLights){const Qt=SX(A.state.lightProbeGridArray,oe);je.lightProbeGrid!==Qt&&(je.lightProbeGrid=Qt,nr=!0)}if(To||ae!==L){M.buffers.depth.getReversed()&&L.reversedDepth!==!0&&(L._reversedDepth=!0,L.updateProjectionMatrix()),jt.setValue(K,"projectionMatrix",L.projectionMatrix),jt.setValue(K,"viewMatrix",L.matrixWorldInverse);const ir=jt.map.cameraPosition;ir!==void 0&&ir.setValue(K,Gt.setFromMatrixPosition(L.matrixWorld)),F.logarithmicDepthBuffer&&jt.setValue(K,"logDepthBufFC",2/(Math.log(L.far+1)/Math.LN2)),(ie.isMeshPhongMaterial||ie.isMeshToonMaterial||ie.isMeshLambertMaterial||ie.isMeshBasicMaterial||ie.isMeshStandardMaterial||ie.isShaderMaterial)&&jt.setValue(K,"isOrthographic",L.isOrthographicCamera===!0),ae!==L&&(ae=L,nr=!0,ud=!0)}if(je.needsLights&&(xa.state.sunShadowMap.length>0&&jt.setValue(K,"sunShadowMap",xa.state.sunShadowMap,he),xa.state.directionalShadowMap.length>0&&jt.setValue(K,"directionalShadowMap",xa.state.directionalShadowMap,he),xa.state.spotShadowMap.length>0&&jt.setValue(K,"spotShadowMap",xa.state.spotShadowMap,he),xa.state.pointShadowMap.length>0&&jt.setValue(K,"pointShadowMap",xa.state.pointShadowMap,he)),oe.isSkinnedMesh){jt.setOptional(K,oe,"bindMatrix"),jt.setOptional(K,oe,"bindMatrixInverse");const Qt=oe.skeleton;Qt&&(Qt.boneTexture===null&&Qt.computeBoneTexture(),jt.setValue(K,"boneTexture",Qt.boneTexture,he))}oe.isBatchedMesh&&(jt.setOptional(K,oe,"batchingTexture"),jt.setValue(K,"batchingTexture",oe._matricesTexture,he),jt.setOptional(K,oe,"batchingIdTexture"),jt.setValue(K,"batchingIdTexture",oe._indirectTexture,he),jt.setOptional(K,oe,"batchingColorTexture"),oe._colorsTexture!==null&&jt.setValue(K,"batchingColorTexture",oe._colorsTexture,he));const ar=le.morphAttributes;if((ar.position!==void 0||ar.normal!==void 0||ar.color!==void 0)&&W.update(oe,le,li),(nr||je.receiveShadow!==oe.receiveShadow)&&(je.receiveShadow=oe.receiveShadow,jt.setValue(K,"receiveShadow",oe.receiveShadow)),(ie.isMeshStandardMaterial||ie.isMeshLambertMaterial||ie.isMeshPhongMaterial)&&ie.envMap===null&&X.environment!==null&&(Mn.envMapIntensity.value=X.environmentIntensity),Mn.dfgLUT!==void 0&&(Mn.dfgLUT.value=FG()),nr){if(jt.setValue(K,"toneMappingExposure",E.toneMappingExposure),je.needsLights&&AX(Mn,ud),qe&&ie.fog===!0&&ce.refreshFogUniforms(Mn,qe),ce.refreshMaterialUniforms(Mn,ie,Z,de,A.state.transmissionRenderTarget[L.id]),je.needsLights&&je.lightProbeGrid){const Qt=je.lightProbeGrid;Mn.probesSH.value=Qt.texture,Mn.probesMin.value.copy(Qt.boundingBox.min),Mn.probesMax.value.copy(Qt.boundingBox.max),Mn.probesResolution.value.copy(Qt.resolution)}tv.upload(K,I6(je),Mn,he)}if(ie.isShaderMaterial&&ie.uniformsNeedUpdate===!0&&(tv.upload(K,I6(je),Mn,he),ie.uniformsNeedUpdate=!1),ie.isSpriteMaterial&&jt.setValue(K,"center",oe.center),jt.setValue(K,"modelViewMatrix",oe.modelViewMatrix),jt.setValue(K,"normalMatrix",oe.normalMatrix),jt.setValue(K,"modelMatrix",oe.matrixWorld),ie.uniformsGroups!==void 0){const Qt=ie.uniformsGroups;for(let ir=0,fd=Qt.length;ir<fd;ir++){const D6=Qt[ir];ke.update(D6,li),ke.bind(D6,li)}}return li}function AX(L,X){L.ambientLightColor.needsUpdate=X,L.lightProbe.needsUpdate=X,L.sunLights.needsUpdate=X,L.sunLightShadows.needsUpdate=X,L.directionalLights.needsUpdate=X,L.directionalLightShadows.needsUpdate=X,L.pointLights.needsUpdate=X,L.pointLightShadows.needsUpdate=X,L.spotLights.needsUpdate=X,L.spotLightShadows.needsUpdate=X,L.rectAreaLights.needsUpdate=X,L.hemisphereLights.needsUpdate=X}function TX(L){return L.isMeshLambertMaterial||L.isMeshToonMaterial||L.isMeshPhongMaterial||L.isMeshStandardMaterial||L.isShadowMaterial||L.isShaderMaterial&&L.lights===!0}this.getActiveCubeFace=function(){return G},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return J},this.setRenderTargetTextures=function(L,X,le){const ie=se.get(L);ie.__autoAllocateDepthBuffer=L.resolveDepthBuffer===!1,ie.__autoAllocateDepthBuffer===!1&&(ie.__useRenderToTexture=!1),se.get(L.texture).__webglTexture=X,se.get(L.depthTexture).__webglTexture=ie.__autoAllocateDepthBuffer?void 0:le,ie.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(L,X){const le=se.get(L);le.__webglFramebuffer=X,le.__useDefaultFramebuffer=X===void 0},this.setRenderTarget=function(L,X=0,le=0){J=L,G=X,O=le;let ie=null,oe=!1,qe=!1;if(L){const Fe=se.get(L);if(Fe.__useDefaultFramebuffer!==void 0){M.bindFramebuffer(K.FRAMEBUFFER,Fe.__webglFramebuffer),q.copy(L.viewport),we.copy(L.scissor),Re=L.scissorTest,M.viewport(q),M.scissor(we),M.setScissorTest(Re),ne=-1;return}else if(Fe.__webglFramebuffer===void 0)he.setupRenderTarget(L);else if(Fe.__hasExternalTextures)he.rebindTextures(L,se.get(L.texture).__webglTexture,se.get(L.depthTexture).__webglTexture);else if(L.depthBuffer){const yt=L.depthTexture;if(Fe.__boundDepthTexture!==yt){if(yt!==null&&se.has(yt)&&(L.width!==yt.image.width||L.height!==yt.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");he.setupDepthRenderbuffer(L)}}const Ke=L.texture;(Ke.isData3DTexture||Ke.isDataArrayTexture||Ke.isCompressedArrayTexture)&&(qe=!0);const et=se.get(L).__webglFramebuffer;L.isWebGLCubeRenderTarget?(Array.isArray(et[X])?ie=et[X][le]:ie=et[X],oe=!0):L.samples>0&&he.useMultisampledRTT(L)===!1?ie=se.get(L).__webglMultisampledFramebuffer:Array.isArray(et)?ie=et[le]:ie=et,q.copy(L.viewport),we.copy(L.scissor),Re=L.scissorTest}else q.copy(De).multiplyScalar(Z).floor(),we.copy(be).multiplyScalar(Z).floor(),Re=ft;if(le!==0&&(ie=B),M.bindFramebuffer(K.FRAMEBUFFER,ie)&&M.drawBuffers(L,ie),M.viewport(q),M.scissor(we),M.setScissorTest(Re),oe){const Fe=se.get(L.texture);K.framebufferTexture2D(K.FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_CUBE_MAP_POSITIVE_X+X,Fe.__webglTexture,le)}else if(qe){const Fe=X;for(let Ke=0;Ke<L.textures.length;Ke++){const et=se.get(L.textures[Ke]);K.framebufferTextureLayer(K.FRAMEBUFFER,K.COLOR_ATTACHMENT0+Ke,et.__webglTexture,le,Fe)}}else if(L!==null&&le!==0){const Fe=se.get(L.texture);K.framebufferTexture2D(K.FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_2D,Fe.__webglTexture,le)}ne=-1};function z6(L){const X=se.get(L);return(X.__readFormat!==L.format||X.__readType!==L.type)&&(X.__readFormat=L.format,X.__readType=L.type,X.__formatReadable=F.textureFormatReadable(L.format),X.__typeReadable=F.textureTypeReadable(L.type)),X}this.readRenderTargetPixels=function(L,X,le,ie,oe,qe,Ye,Fe=0){if(!(L&&L.isWebGLRenderTarget)){Ot("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ke=se.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Ye!==void 0&&(Ke=Ke[Ye]),Ke){M.bindFramebuffer(K.FRAMEBUFFER,Ke);try{const et=L.textures[Fe],yt=et.format,Mt=et.type;L.textures.length>1&&K.readBuffer(K.COLOR_ATTACHMENT0+Fe);const Ze=z6(et);if(Ze.__formatReadable===!1){Ot("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(Ze.__typeReadable===!1){Ot("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}X>=0&&X<=L.width-ie&&le>=0&&le<=L.height-oe&&K.readPixels(X,le,ie,oe,Me.convert(yt),Me.convert(Mt),qe)}finally{const et=J!==null?se.get(J).__webglFramebuffer:null;M.bindFramebuffer(K.FRAMEBUFFER,et)}}},this.readRenderTargetPixelsAsync=async function(L,X,le,ie,oe,qe,Ye,Fe=0){if(!(L&&L.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ke=se.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Ye!==void 0&&(Ke=Ke[Ye]),Ke)if(X>=0&&X<=L.width-ie&&le>=0&&le<=L.height-oe){M.bindFramebuffer(K.FRAMEBUFFER,Ke);const et=L.textures[Fe],yt=et.format,Mt=et.type;L.textures.length>1&&K.readBuffer(K.COLOR_ATTACHMENT0+Fe);const Ze=z6(et);if(Ze.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(Ze.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Bt=K.createBuffer();K.bindBuffer(K.PIXEL_PACK_BUFFER,Bt),K.bufferData(K.PIXEL_PACK_BUFFER,qe.byteLength,K.STREAM_READ),K.readPixels(X,le,ie,oe,Me.convert(yt),Me.convert(Mt),0),K.bindBuffer(K.PIXEL_PACK_BUFFER,null);const Rn=J!==null?se.get(J).__webglFramebuffer:null;M.bindFramebuffer(K.FRAMEBUFFER,Rn);const on=K.fenceSync(K.SYNC_GPU_COMMANDS_COMPLETE,0);return K.flush(),await DH(K,on,4),K.bindBuffer(K.PIXEL_PACK_BUFFER,Bt),K.getBufferSubData(K.PIXEL_PACK_BUFFER,0,qe),K.bindBuffer(K.PIXEL_PACK_BUFFER,null),K.deleteBuffer(Bt),K.deleteSync(on),qe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(L,X=null,le=0){const ie=Math.pow(2,-le),oe=Math.floor(L.image.width*ie),qe=Math.floor(L.image.height*ie),Ye=X!==null?X.x:0,Fe=X!==null?X.y:0;he.setTexture2D(L,0),K.copyTexSubImage2D(K.TEXTURE_2D,le,0,0,Ye,Fe,oe,qe),M.unbindTexture()},this.copyTextureToTexture=function(L,X,le=null,ie=null,oe=0,qe=0){let Ye,Fe,Ke,et,yt,Mt,Ze,Bt,Rn;const on=L.isCompressedTexture?L.mipmaps[qe]:L.image;if(le!==null)Ye=le.max.x-le.min.x,Fe=le.max.y-le.min.y,Ke=le.isBox3?le.max.z-le.min.z:1,et=le.min.x,yt=le.min.y,Mt=le.isBox3?le.min.z:0;else{const Mn=Math.pow(2,-oe);Ye=Math.floor(on.width*Mn),Fe=Math.floor(on.height*Mn),L.isDataArrayTexture?Ke=on.depth:L.isData3DTexture?Ke=Math.floor(on.depth*Mn):Ke=1,et=0,yt=0,Mt=0}ie!==null?(Ze=ie.x,Bt=ie.y,Rn=ie.z):(Ze=0,Bt=0,Rn=0);const Kt=Me.convert(X.format),oa=Me.convert(X.type);let je;X.isData3DTexture?(he.setTexture3D(X,0),je=K.TEXTURE_3D):X.isDataArrayTexture||X.isCompressedArrayTexture?(he.setTexture2DArray(X,0),je=K.TEXTURE_2D_ARRAY):(he.setTexture2D(X,0),je=K.TEXTURE_2D),M.activeTexture(K.TEXTURE0),M.pixelStorei(K.UNPACK_FLIP_Y_WEBGL,X.flipY),M.pixelStorei(K.UNPACK_PREMULTIPLY_ALPHA_WEBGL,X.premultiplyAlpha),M.pixelStorei(K.UNPACK_ALIGNMENT,X.unpackAlignment);const xa=M.getParameter(K.UNPACK_ROW_LENGTH),Dt=M.getParameter(K.UNPACK_IMAGE_HEIGHT),li=M.getParameter(K.UNPACK_SKIP_PIXELS),To=M.getParameter(K.UNPACK_SKIP_ROWS),nr=M.getParameter(K.UNPACK_SKIP_IMAGES);M.pixelStorei(K.UNPACK_ROW_LENGTH,on.width),M.pixelStorei(K.UNPACK_IMAGE_HEIGHT,on.height),M.pixelStorei(K.UNPACK_SKIP_PIXELS,et),M.pixelStorei(K.UNPACK_SKIP_ROWS,yt),M.pixelStorei(K.UNPACK_SKIP_IMAGES,Mt);const ud=L.isDataArrayTexture||L.isData3DTexture,jt=X.isDataArrayTexture||X.isData3DTexture;if(L.isDepthTexture){const Mn=se.get(L),ar=se.get(X),Qt=se.get(Mn.__renderTarget),ir=se.get(ar.__renderTarget);M.bindFramebuffer(K.READ_FRAMEBUFFER,Qt.__webglFramebuffer),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,ir.__webglFramebuffer);for(let fd=0;fd<Ke;fd++)ud&&(K.framebufferTextureLayer(K.READ_FRAMEBUFFER,K.COLOR_ATTACHMENT0,se.get(L).__webglTexture,oe,Mt+fd),K.framebufferTextureLayer(K.DRAW_FRAMEBUFFER,K.COLOR_ATTACHMENT0,se.get(X).__webglTexture,qe,Rn+fd)),K.blitFramebuffer(et,yt,Ye,Fe,Ze,Bt,Ye,Fe,K.DEPTH_BUFFER_BIT,K.NEAREST);M.bindFramebuffer(K.READ_FRAMEBUFFER,null),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,null)}else if(oe!==0||L.isRenderTargetTexture||se.has(L)){const Mn=se.get(L),ar=se.get(X);M.bindFramebuffer(K.READ_FRAMEBUFFER,D),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,$);for(let Qt=0;Qt<Ke;Qt++)ud?K.framebufferTextureLayer(K.READ_FRAMEBUFFER,K.COLOR_ATTACHMENT0,Mn.__webglTexture,oe,Mt+Qt):K.framebufferTexture2D(K.READ_FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_2D,Mn.__webglTexture,oe),jt?K.framebufferTextureLayer(K.DRAW_FRAMEBUFFER,K.COLOR_ATTACHMENT0,ar.__webglTexture,qe,Rn+Qt):K.framebufferTexture2D(K.DRAW_FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_2D,ar.__webglTexture,qe),oe!==0?K.blitFramebuffer(et,yt,Ye,Fe,Ze,Bt,Ye,Fe,K.COLOR_BUFFER_BIT,K.NEAREST):jt?K.copyTexSubImage3D(je,qe,Ze,Bt,Rn+Qt,et,yt,Ye,Fe):K.copyTexSubImage2D(je,qe,Ze,Bt,et,yt,Ye,Fe);M.bindFramebuffer(K.READ_FRAMEBUFFER,null),M.bindFramebuffer(K.DRAW_FRAMEBUFFER,null)}else jt?L.isDataTexture||L.isData3DTexture?K.texSubImage3D(je,qe,Ze,Bt,Rn,Ye,Fe,Ke,Kt,oa,on.data):X.isCompressedArrayTexture?K.compressedTexSubImage3D(je,qe,Ze,Bt,Rn,Ye,Fe,Ke,Kt,on.data):K.texSubImage3D(je,qe,Ze,Bt,Rn,Ye,Fe,Ke,Kt,oa,on):L.isDataTexture?K.texSubImage2D(K.TEXTURE_2D,qe,Ze,Bt,Ye,Fe,Kt,oa,on.data):L.isCompressedTexture?K.compressedTexSubImage2D(K.TEXTURE_2D,qe,Ze,Bt,on.width,on.height,Kt,on.data):K.texSubImage2D(K.TEXTURE_2D,qe,Ze,Bt,Ye,Fe,Kt,oa,on);M.pixelStorei(K.UNPACK_ROW_LENGTH,xa),M.pixelStorei(K.UNPACK_IMAGE_HEIGHT,Dt),M.pixelStorei(K.UNPACK_SKIP_PIXELS,li),M.pixelStorei(K.UNPACK_SKIP_ROWS,To),M.pixelStorei(K.UNPACK_SKIP_IMAGES,nr),qe===0&&X.generateMipmaps&&K.generateMipmap(je),M.unbindTexture()},this.initRenderTarget=function(L){se.get(L).__webglFramebuffer===void 0&&he.setupRenderTarget(L)},this.initTexture=function(L){L.isCubeTexture?he.setTextureCube(L,0):L.isData3DTexture?he.setTexture3D(L,0):L.isDataArrayTexture||L.isCompressedArrayTexture?he.setTexture2DArray(L,0):he.setTexture2D(L,0),M.unbindTexture()},this.resetState=function(){G=0,O=0,J=null,M.reset(),Pe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return vo}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=Ct._getDrawingBufferColorSpace(e),n.unpackColorSpace=Ct._getUnpackColorSpace()}}const rC={type:"change"},tk={type:"start"},lC={type:"end"},av=new Ng,cC=new ds,BG=Math.cos(70*FH.DEG2RAD),zn=new Q,Ca=2*Math.PI,qt={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},nk=1e-6;class HG extends kq{constructor(e,n=null){super(e,n),this.state=qt.NONE,this.target=new Q,this.cursor=new Q,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Ic.ROTATE,MIDDLE:Ic.DOLLY,RIGHT:Ic.PAN},this.touches={ONE:Nc.ROTATE,TWO:Nc.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new Q,this._lastQuaternion=new Ys,this._lastTargetPosition=new Q,this._quat=new Ys().setFromUnitVectors(e.up,new Q(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new __,this._sphericalDelta=new __,this._scale=1,this._panOffset=new Q,this._rotateStart=new ut,this._rotateEnd=new ut,this._rotateDelta=new ut,this._panStart=new ut,this._panEnd=new ut,this._panDelta=new ut,this._dollyStart=new ut,this._dollyEnd=new ut,this._dollyDelta=new ut,this._dollyDirection=new Q,this._mouse=new ut,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=WG.bind(this),this._onPointerDown=qG.bind(this),this._onPointerUp=GG.bind(this),this._onContextMenu=JG.bind(this),this._onMouseWheel=YG.bind(this),this._onKeyDown=XG.bind(this),this._onTouchStart=KG.bind(this),this._onTouchMove=ZG.bind(this),this._onMouseDown=VG.bind(this),this._onMouseMove=jG.bind(this),this._interceptControlDown=QG.bind(this),this._interceptControlUp=eV.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.state=qt.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();const e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(rC),this.update(),this.state=qt.NONE}pan(e,n){this._pan(e,n),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const n=this.object.position;zn.copy(n).sub(this.target),zn.applyQuaternion(this._quat),this._spherical.setFromVector3(zn),this.autoRotate&&this.state===qt.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let a=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(a)&&isFinite(i)&&(a<-Math.PI?a+=Ca:a>Math.PI&&(a-=Ca),i<-Math.PI?i+=Ca:i>Math.PI&&(i-=Ca),a<=i?this._spherical.theta=Math.max(a,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(a+i)/2?Math.max(a,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let o=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),o=s!=this._spherical.radius}if(zn.setFromSpherical(this._spherical),zn.applyQuaternion(this._quatInverse),n.copy(this.target).add(zn),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let s=null;if(this.object.isPerspectiveCamera){const r=zn.length();s=this._clampDistance(r*this._scale);const l=r-s;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),o=!!l}else if(this.object.isOrthographicCamera){const r=new Q(this._mouse.x,this._mouse.y,0);r.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),o=l!==this.object.zoom;const c=new Q(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(r),this.object.updateMatrixWorld(),s=zn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;s!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position):(av.origin.copy(this.object.position),av.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(av.direction))<BG?this.object.lookAt(this.target):(cC.setFromNormalAndCoplanarPoint(this.object.up,this.target),av.intersectPlane(cC,this.target))))}else if(this.object.isOrthographicCamera){const s=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom&&(this.object.updateProjectionMatrix(),o=!0)}return this._scale=1,this._performCursorZoom=!1,o||this._lastPosition.distanceToSquared(this.object.position)>nk||8*(1-this._lastQuaternion.dot(this.object.quaternion))>nk||this._lastTargetPosition.distanceToSquared(this.target)>nk?(this.dispatchEvent(rC),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Ca/60*this.autoRotateSpeed*e:Ca/60/60*this.autoRotateSpeed}_getZoomScale(e){const n=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*n)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,n){zn.setFromMatrixColumn(n,0),zn.multiplyScalar(-e),this._panOffset.add(zn)}_panUp(e,n){this.screenSpacePanning===!0?zn.setFromMatrixColumn(n,1):(zn.setFromMatrixColumn(n,0),zn.crossVectors(this.object.up,zn)),zn.multiplyScalar(e),this._panOffset.add(zn)}_pan(e,n){const a=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;zn.copy(i).sub(this.target);let o=zn.length();o*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*o/a.clientHeight,this.object.matrix),this._panUp(2*n*o/a.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/a.clientWidth,this.object.matrix),this._panUp(n*(this.object.top-this.object.bottom)/this.object.zoom/a.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,n){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const a=this.domElement.getBoundingClientRect(),i=e-a.left,o=n-a.top,s=a.width,r=a.height;this._mouse.x=i/s*2-1,this._mouse.y=-(o/r)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Ca*this._rotateDelta.x/n.clientHeight),this._rotateUp(Ca*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let n=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),n=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),n=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),n=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Ca*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),n=!0;break}n&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._rotateStart.set(a,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panStart.set(a,i)}}_handleTouchStartDolly(e){const n=this._getSecondPointerPosition(e),a=e.pageX-n.x,i=e.pageY-n.y,o=Math.sqrt(a*a+i*i);this._dollyStart.set(0,o)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const a=this._getSecondPointerPosition(e),i=.5*(e.pageX+a.x),o=.5*(e.pageY+a.y);this._rotateEnd.set(i,o)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Ca*this._rotateDelta.x/n.clientHeight),this._rotateUp(Ca*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panEnd.set(a,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const n=this._getSecondPointerPosition(e),a=e.pageX-n.x,i=e.pageY-n.y,o=Math.sqrt(a*a+i*i);this._dollyEnd.set(0,o),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=(e.pageX+n.x)*.5,r=(e.pageY+n.y)*.5;this._updateZoomParameters(s,r)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId){this._pointers.splice(n,1);return}}_isTrackingPointer(e){for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId)return!0;return!1}_trackPointer(e){let n=this._pointerPositions[e.pointerId];n===void 0&&(n=new ut,this._pointerPositions[e.pointerId]=n),n.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const n=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[n]}_customWheelEvent(e){const n=e.deltaMode,a={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(n){case 1:a.deltaY*=16;break;case 2:a.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(a.deltaY*=10),a}}function qG(t){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(t.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(t)&&(this._addPointer(t),t.pointerType==="touch"?this._onTouchStart(t):this._onMouseDown(t),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function WG(t){this.enabled!==!1&&(t.pointerType==="touch"?this._onTouchMove(t):this._onMouseMove(t))}function GG(t){switch(this._removePointer(t),this._pointers.length){case 0:this.domElement.releasePointerCapture(t.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(lC),this.state=qt.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],n=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:n.x,pageY:n.y});break}}function VG(t){let e;switch(t.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Ic.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(t),this.state=qt.DOLLY;break;case Ic.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=qt.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=qt.ROTATE}break;case Ic.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=qt.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=qt.PAN}break;default:this.state=qt.NONE}this.state!==qt.NONE&&this.dispatchEvent(tk)}function jG(t){switch(this.state){case qt.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(t);break;case qt.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(t);break;case qt.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(t);break}}function YG(t){this.enabled===!1||this.enableZoom===!1||this.state!==qt.NONE||(t.preventDefault(),this.dispatchEvent(tk),this._handleMouseWheel(this._customWheelEvent(t)),this.dispatchEvent(lC))}function XG(t){this.enabled!==!1&&this._handleKeyDown(t)}function KG(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case Nc.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(t),this.state=qt.TOUCH_ROTATE;break;case Nc.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(t),this.state=qt.TOUCH_PAN;break;default:this.state=qt.NONE}break;case 2:switch(this.touches.TWO){case Nc.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(t),this.state=qt.TOUCH_DOLLY_PAN;break;case Nc.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(t),this.state=qt.TOUCH_DOLLY_ROTATE;break;default:this.state=qt.NONE}break;default:this.state=qt.NONE}this.state!==qt.NONE&&this.dispatchEvent(tk)}function ZG(t){switch(this._trackPointer(t),this.state){case qt.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(t),this.update();break;case qt.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(t),this.update();break;case qt.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(t),this.update();break;case qt.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(t),this.update();break;default:this.state=qt.NONE}}function JG(t){this.enabled!==!1&&t.preventDefault()}function QG(t){t.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function eV(t){t.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const tV=6;function ak(t,e,n,a,i){switch(t){case"agent":return{l:e+14,t:n-i*1.3,r:e+14+a,b:n-i*.3};case"agent-flip":return{l:e-14-a,t:n-i*1.3,r:e-14,b:n-i*.3};case"region":return{l:e-a/2,t:n-6-i/2,r:e+a/2,b:n-6+i/2};case"note":return{l:e+10,t:n-i/2,r:e+10+a,b:n+i/2}}}function iv(t,e){for(const n of e)if(t.l<n.r&&t.r>n.l&&t.t<n.b&&t.b>n.t)return!1;return!0}function nV(t,e,n,a,i){return!i.length||iv(ak("agent",t,e,n,a),i)?"right":iv(ak("agent-flip",t,e,n,a),i)?"left":"hidden"}function aV(t,e,n=tV){const a=[];for(const i of e){const o=i.getBoundingClientRect();o.width<1||o.height<1||o.right<t.left||o.left>t.right||o.bottom<t.top||o.top>t.bottom||a.push({l:o.left-t.left-n,t:o.top-t.top-n,r:o.right-t.left+n,b:o.bottom-t.top+n})}return a}function ik(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}function Zh(t){let e=t>>>0||2654435769;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function ok(t){const e=Math.max(1e-9,t());return Math.sqrt(-2*Math.log(e))*Math.cos(2*Math.PI*t())}function er(t,e,n){let a=Math.imul(t,374761393)+Math.imul(e,668265263)+Math.imul(n,1274126177);return a=Math.imul(a^a>>>13,1274126177),((a^a>>>16)>>>0)/4294967296}function dC(t,e,n){const a=Math.floor(t),i=Math.floor(e),o=Math.floor(n),s=t-a,r=e-i,l=n-o,c=s*s*(3-2*s),d=r*r*(3-2*r),p=l*l*(3-2*l),h=(u,f,v)=>u+(f-u)*v;return h(h(h(er(a,i,o),er(a+1,i,o),c),h(er(a,i+1,o),er(a+1,i+1,o),c),d),h(h(er(a,i,o+1),er(a+1,i,o+1),c),h(er(a,i+1,o+1),er(a+1,i+1,o+1),c),d),p)}function iV(t,e,n){const i=1-Math.abs(2*dC(t*5.2+11.3,e*5.2*1.15,n*5.2)-1),o=1-Math.abs(2*dC(t*5.2*2.1,e*5.2*2.1+5.1,n*5.2*2.1-3.7)-1),s=Math.max(Math.pow(i,5),Math.pow(o,7)*.6);return Math.min(1,s*1.25)}const ad={c:[.4,.06,0],a:[.52,.62,1]},sk={c:[.52,-.27,.14],a:[.3,.25,.56]},pC={c:[.25,-.44,-.66],a:[.3,.2,.3]};function id(t,e,n,a){const i=1-.1*Math.max(0,a),o=(e-t.c[0])/(t.a[0]*i);let s=(n-t.c[1])/(t.a[1]*i);s<0&&t===ad&&(s*=1.35);const r=(a-t.c[2])/t.a[2];return Math.sqrt(o*o+s*s+r*r)}function ov(t,e,n){const a=Math.abs(t);return a<.035?9:Math.min(id(ad,a,e,n),id(sk,a,e,n))}function hC(t,e,n){const a=Math.abs(t);return a<.02?9:id(pC,a,e,n)}function oV(t,e,n,a=.9){return ov(t,e,n)<a||hC(t,e,n)<a*.9}function sV(t,e=7){const n=Zh(e),a=new Float32Array(t*3),i=new Float32Array(t*3),o=new Float32Array(t);let s=0,r=t*60;for(;s<t&&r-- >0;){const l=n();let c=ad,d=0;l<.78?c=ad:l<.9?c=sk:l<.97?(c=pC,d=1):d=2;let p,h,u,f,v,g;if(d===2){const R=n(),B=n()*Math.PI*2,D=.1-R*.025;if(f=Math.cos(B),g=Math.sin(B),v=0,p=f*D,h=-.28-R*.55,u=-.28-R*.12+g*D,ov(p,h,u)<1||hC(p,h,u)<1)continue;a.set([p,h,u],s*3),i.set([f,v,g],s*3),o[s]=.45+.2*n(),s++;continue}const m=n()*2-1,b=n()*Math.PI*2,k=Math.sqrt(1-m*m),y=n()<.5?-1:1;let w=k*Math.cos(b),A=k*Math.sin(b),_=m;p=c.c[0]+w*c.a[0],h=c.c[1]+A*c.a[1],u=c.c[2]+_*c.a[2];const S=id(c,p,h,u);if(p=c.c[0]+(p-c.c[0])/S,h=c.c[1]+(h-c.c[1])/S,u=c.c[2]+(u-c.c[2])/S,p<.035)continue;if(d===0){if(id(c===ad?sk:ad,p,h,u)<.985)continue}else if(ov(p,h,u)<1)continue;f=(p-c.c[0])/(c.a[0]*c.a[0]),v=(h-c.c[1])/(c.a[1]*c.a[1]),g=(u-c.c[2])/(c.a[2]*c.a[2]);const T=Math.hypot(f,v,g)||1;f/=T,v/=T,g/=T;let E,P;if(d===1){const R=Math.abs(Math.sin(h*70+u*12));E=.35+.65*R,P=(1-R)*.018}else{const R=iV(p,h,u);if(R>.55&&n()<.55)continue;E=1-.9*R,P=R*.05}p-=f*P,h-=v*P,u-=g*P,w=p*y,a.set([w,h,u],s*3),i.set([f*y,v,g],s*3),o[s]=E,s++}return{pos:a,nrm:i,shade:o,count:s}}function rV(t,e=3){const n=Zh(e),a=[];for(;a.length<1800;){const l=(n()*2-1)*.95,c=(n()*2-1)*.75,d=(n()*2-1)*1.05,p=ov(l,c,d);p>.42&&p<.72&&a.push([l,c,d])}const i=[];if(t<=0)return i;let o=0,s=-1/0;for(let l=0;l<a.length;l++){const c=a[l][2]+a[l][1]*.5-Math.abs(a[l][0])*.2;c>s&&(s=c,o=l)}i.push(a[o]);const r=a.map(l=>uC(l,a[o]));for(;i.length<t;){let l=0,c=-1;for(let d=0;d<a.length;d++)r[d]>c&&(c=r[d],l=d);if(c<=0){i.push(a[i.length*37%a.length]);continue}i.push(a[l]);for(let d=0;d<a.length;d++)r[d]=Math.min(r[d],uC(a[d],a[l]))}return i}function uC(t,e){const n=t[0]-e[0],a=t[1]-e[1],i=t[2]-e[2];return n*n+a*a+i*i}function lV(t,e,n){const a=Zh(ik(t));for(let i=0;i<40;i++){const o=n*(1+i*.03),s=e[0]+ok(a)*o*.8,r=e[1]+ok(a)*o*.8,l=e[2]+ok(a)*o*1.15;if(!(Math.sign(s)!==Math.sign(e[0])&&Math.abs(e[0])>.06)&&oV(s,r,l,.9))return[s,r,l]}return[e[0],e[1],e[2]]}function cV(t,e){const n=.62/Math.cbrt(Math.max(1,e));return Math.min(.3,Math.max(.045,n*(.22+.12*Math.cbrt(t))))}const fC=[3.05,1.35,1.55],Jh=[0,-.02,-.04],dV=42;function mC(t){return t<.9?5.2:t<1.3?4.1:3.6}const ko=110,Qh=6e3,sv=12*ko*2,pV=5*6e4,hV=5e3,uV=2e3,fV=`
|
|
11696
11716
|
attribute vec3 aColor; attribute float aSize; attribute float aFlare; attribute float aDim; attribute float aPhase;
|
|
11697
11717
|
uniform float uTime; uniform float uScale;
|
|
11698
11718
|
varying vec3 vColor; varying float vAlpha; varying float vFlare;
|
|
@@ -11863,12 +11883,12 @@ void main() {
|
|
|
11863
11883
|
<div class="brain-tip hidden" data-el="tip"></div>
|
|
11864
11884
|
<div class="brain-foot"><span class="brain-hint" data-el="hint">Drag to turn · scroll to zoom · click a point to open its note</span></div>`}wireUi(){const e=this.els;this.chrome=new lw({page:"brain",root:this.root,search:{placeholder:"Find a note, #tag or in:folder",find:{items:()=>this.notes.map(n=>({id:n.path,name:n.name,folder:n.folder,region:n.folder,color:this.regions.get(n.folder)?.color||"#888",tags:n.tags,degree:n.degree})),hidden:n=>this.hidden.has(n),highlight:n=>{this.findHit=n,this.applyFilter()},pick:n=>{const a=this.notes.findIndex(i=>i.path===n.id);a>=0&&this.select(a,!0)},folder:n=>this.openFolder(n)}},labels:{get:()=>({nodes:this.prefs.labels,folders:this.prefs.regionLabels}),set:(n,a)=>{n==="nodes"?this.prefs.labels=a:this.prefs.regionLabels=a,lv(this.prefs),this.scene?.setLabels(this.prefs.labels,this.prefs.regionLabels)},help:{nodes:"Names next to the most linked notes in the brain. The note under the pointer and the selected one always show theirs.",folders:"Folder names floating over the part of the brain that holds their notes."}},filter:n=>this.renderFilter(n),changed:()=>{const n=dk(),a=this.prefs;return a.labels!==n.labels||a.regionLabels!==n.regionLabels||a.rotate!==n.rotate||this.hidden.size>0||!!this.findHit||this.selected>=0||this.card?.isOpen||!!this.scene?.awayFromHome()},reset:()=>{this.chrome.finder?.clear(),this.card.close(!0);const n=this.prefs.regions;this.prefs={...dk(),regions:n},lv(this.prefs),this.scene?.setLabels(!0,!0),this.scene?.setAutoRotate(!0),this.setHidden([]),this.select(-1),this.scene?.goHome()},regions:{list:()=>Array.from(this.regions.values()).map(n=>({name:n.name,color:n.color,count:n.count,hidden:this.hidden.has(n.name)})),toggle:n=>{const a=new Set(this.hidden);a.has(n)?a.delete(n):a.add(n),this.setHidden(Array.from(a))},setAll:n=>this.setHidden(n?Array.from(this.regions.keys()):[]),focus:n=>this.openFolder(n)},nav:{zoom:n=>this.scene?.zoomBy(n),fit:()=>this.scene?.resetView(),nudge:(n,a)=>this.scene?.orbitBy(-n*.26,-a*.2),home:()=>{this.select(-1),this.scene?.goHome()}},minimap:(n,a,i,o)=>this.drawMini(n,a,i,o),minimapNav:(n,a)=>this.miniNav(n,a),onOverlay:()=>{this.select(-1),this.card.close(!0)}}),this.card=this.buildCard(),this.chromeTimer=window.setInterval(()=>{if(!this.scene||document.hidden)return;const n=this.scene.orientation();this.chrome.setOrientation(n.yaw,n.pitch),this.chrome.redrawMini()},120),this.root.addEventListener("keydown",n=>{n.target.closest("input,textarea,select")||(n.key==="/"||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="f")&&(n.preventDefault(),n.stopPropagation(),this.chrome.focusSearch())}),window.setTimeout(()=>e.hint.classList.add("gone"),7e3),this.root.addEventListener("keydown",n=>{n.key==="Escape"&&this.selected>=0&&this.select(-1)})}renderFilter(e){e.innerHTML="<h4>Brain</h4>"+(this.reduced?"":po("rotate","Rotate when idle",this.prefs.rotate,"The brain turns slowly by itself two seconds after you stop moving it. Only the 3D brain has this."))+'<div class="vc-hint">Drag to turn · scroll to zoom · click a point to open its note · / to search · #tag finds tags</div>';const n=e.querySelector("[data-t=rotate]");n&&(n.onclick=()=>{this.prefs.rotate=!this.prefs.rotate,this.scene?.setAutoRotate(this.prefs.rotate),lv(this.prefs),this.chrome.renderPanel()})}drawMini(e,n,a,i){const o=e.getContext("2d"),s=this.scene;if(!o||!s)return;const r=document.documentElement.dataset.theme==="light";o.setTransform(i,0,0,i,0,0),o.clearRect(0,0,n,a);const l=Math.min(n,a)/3.4,c=n/2,d=a/2,p=this.notes.length,h=Math.max(1,Math.ceil(p/2500));for(let A=0;A<p;A+=h){const _=this.notes[A];if(this.hidden.has(_.folder))continue;const[S,,T]=s.positionOf(A);o.fillStyle=this.regions.get(_.folder)?.color||"#888",o.globalAlpha=.75,o.fillRect(c+S*l-1,d+T*l-1,2,2)}o.globalAlpha=1,o.strokeStyle=r?"rgba(15,23,42,.18)":"rgba(230,233,239,.16)",o.lineWidth=1,o.beginPath(),o.ellipse(c,d,1.25*l,1.05*l,0,0,Math.PI*2),o.stroke();const u=s.cameraView();if(!u)return;const f=Math.atan2(u.eye[2]-u.target[2],u.eye[0]-u.target[0]),v=Math.min(n,a)/2-7,g=c+Math.cos(f)*v,m=d+Math.sin(f)*v,b=f+Math.PI,k=u.fov*.5*(u.rect.w/u.rect.h),y=v*1.25,w=r?"13,148,136":"94,234,212";o.strokeStyle=`rgba(${w},.18)`,o.beginPath(),o.arc(c,d,v,0,Math.PI*2),o.stroke(),o.save(),o.beginPath(),o.arc(c,d,v,0,Math.PI*2),o.clip(),o.fillStyle=`rgba(${w},.12)`,o.strokeStyle=`rgba(${w},.6)`,o.beginPath(),o.moveTo(g,m),o.lineTo(g+Math.cos(b-k)*y,m+Math.sin(b-k)*y),o.lineTo(g+Math.cos(b+k)*y,m+Math.sin(b+k)*y),o.closePath(),o.fill(),o.stroke(),o.restore(),o.fillStyle=`rgb(${w})`,o.beginPath(),o.arc(g,m,4,0,Math.PI*2),o.fill()}miniNav(e,n){const a=this.scene,i=a?.cameraView(),o=this.chrome.miniCanvas.getBoundingClientRect();if(!a||!i||!o.width)return;const s=Math.min(o.width,o.height)/3.4,r=(e*o.width-o.width/2)/s,l=(n*o.height-o.height/2)/s;Math.hypot(r-i.target[0],l-i.target[2])<.05||a.orbitTo(Math.atan2(r-i.target[0],l-i.target[2]),void 0,.6)}destroy(){Ru("brain",null),!this.destroyed&&(this.destroyed=!0,this.unsub.forEach(e=>e()),this.unsub=[],this.observers.forEach(e=>e.disconnect()),document.removeEventListener("visibilitychange",this.syncRunning),clearTimeout(this.refreshTimer),clearInterval(this.chromeTimer),this.chrome?.destroy(),this.card?.destroy(),this.scene?.dispose(),this.scene=null,this.root.remove())}refresh(){return this.loading?this.loading:(this.loading=(async()=>{try{const e=await Oe("/api/graph");if(this.destroyed)return;N.graph.nodes=e.nodes||[],N.graph.links=e.links||[],this.apply(e.nodes||[],e.links||[])}catch(e){this.notes.length||(this.els.hint.textContent="Could not load the graph: "+e.message)}finally{this.loading=null}})(),this.loading)}apply(e,n){if(!this.scene)return;const a=this.selected>=0?this.notes[this.selected]?.path:"",i=this.tagIndex(),o=e.map(m=>{const b=String(m.path||m.id),k=lt(b)||(typeof m.title=="string"&&m.title?m.title:String(m.id||cv(b).replace(/\.md$/i,""))),y=Array.isArray(m.tags)?m.tags.map(String):i.get(b)||[];return{path:b,name:k,folder:m.folder||"Root",tags:y,degree:m.degree||0}}),s=new Map;o.forEach(m=>s.set(m.folder,(s.get(m.folder)||0)+1));const r=Array.from(s.entries()).sort((m,b)=>b[1]-m[1]||m[0].localeCompare(b[0])),l=rV(r.length),c=[...r].sort((m,b)=>m[0].localeCompare(b[0])).map(m=>m[0]);this.regions=new Map,r.forEach(([m,b],k)=>{const y=N.folderMeta[m];this.regions.set(m,{name:m,count:b,anchor:l[k],color:JB(c.indexOf(m),y&&y.color)})}),this.index=new Map;const d=new Map;o.forEach((m,b)=>{this.index.set(Li(m.path),b);const k=Li(cv(m.path));d.has(k)||d.set(k,b);const y=Li(m.name);d.has(y)||d.set(y,b)}),d.forEach((m,b)=>{this.index.has(b)||this.index.set(b,m)});const p=[];this.out=new Map,this.inc=new Map;const h=new Set;for(const m of n){const b=this.index.get(Li(String(m.source))),k=this.index.get(Li(String(m.target)));if(b===void 0||k===void 0||b===k)continue;const y=b<k?b+":"+k:k+":"+b;this.out.has(b)||this.out.set(b,[]),this.inc.has(k)||this.inc.set(k,[]),this.out.get(b).includes(k)||this.out.get(b).push(k),this.inc.get(k).includes(b)||this.inc.get(k).push(b),!h.has(y)&&(h.add(y),p.push([b,k]))}const u=new Array(o.length).fill(0);p.forEach(([m,b])=>{u[m]++,u[b]++});const f=o.length>6e3?.7:o.length>2e3?.85:1,v=o.map((m,b)=>{const k=this.regions.get(m.folder),y=cV(k.count,r.length);return{key:m.path,target:lV(m.path,k.anchor,y),origin:k.anchor,color:k.color,size:(.034+Math.min(.065,Math.sqrt(u[b]+m.degree*.3)*.011))*f}});this.notes=o;const g=Array.from(this.regions.values()).map(m=>({name:m.name,anchor:m.anchor,color:m.color,count:m.count}));if(this.scene.setDim(null),this.scene.setData(v,p,g),this.scene.setEmpty(!o.length),this.chrome.setEmpty(!o.length),this.els.hint.hidden=!o.length,this.selected>=0&&(this.selected=-1),this.prefs.hidden.length&&(this.hidden=new Set(this.prefs.hidden.filter(m=>this.regions.has(m)))),this.renderRegions(),this.chrome?.finder?.update(),this.applyFilter(!1),this.scene.refreshNoteLabels(),a){const m=this.index.get(Li(a));m!==void 0?this.select(m,!1):this.select(-1)}for(const m of this.pendingFlare.splice(0)){const b=this.index.get(Li(m));b!==void 0&&this.scene.flareNote(b,1)}}tagIndex(){const e=new Map,n=N.tags.index;return n&&n.forEach((a,i)=>{for(const o of a){const s=o.path;s&&(e.has(s)||e.set(s,[]),e.get(s).push(i))}}),e}renderRegions(){this.chrome.refreshRegions()}setHidden(e){this.hidden=new Set(e.filter(n=>this.regions.has(n))),this.prefs.hidden=Array.from(this.hidden),lv(this.prefs),this.renderRegions(),this.applyFilter()}focusRegion(e){const n=this.regions.get(e);if(!n||!this.scene||this.hidden.has(e))return;this.scene.focus(n.anchor,1.9);let a=0;for(let i=0;i<this.notes.length&&a<80;i++)this.notes[i].folder===e&&(this.scene.flareNote(i,1),a++)}matches(e){const n=this.notes[e];return!n||this.hidden.has(n.folder)?!1:!this.findHit||this.findHit.has(n.path)}applyFilter(e=!0){if(!this.scene)return;const n=!!(this.hidden.size||this.findHit);this.scene.setHiddenRegions(this.hidden),this.scene.setDim(n?a=>this.matches(a)?0:1:null),e&&this.scene.refreshNoteLabels()}hover(e,n,a){e>=0&&this.hidden.has(this.notes[e]?.folder)&&(e=-1);const i=this.els.tip;if(this.root.classList.toggle("hovering",e>=0),e<0||!this.notes[e]){i.classList.add("hidden");return}const o=this.notes[e],s=this.regions.get(o.folder),r=(this.out.get(e)?.length||0)+(this.inc.get(e)?.length||0);i.innerHTML=`<b>${x(o.name)}</b><div class="bt-f" style="--c:${C(s?.color||"#888")}"><i></i>${x(o.folder)} · ${r} link${r===1?"":"s"}</div>`+(o.tags.length?`<div class="brain-tags">${o.tags.slice(0,5).map(d=>`<span>#${x(d)}</span>`).join("")}</div>`:""),i.classList.remove("hidden");const l=this.root.clientWidth,c=n+280>l?n-290:n;i.style.left=c+"px",i.style.top=Math.min(a,this.root.clientHeight-90)+"px"}pick(e){if(e>=0&&this.hidden.has(this.notes[e]?.folder)&&(e=-1),e<0){this.selected>=0&&this.select(-1);return}this.select(e,!0)}select(e,n=!1){if(this.selected=e,this.scene?.select(e),e<0||!this.notes[e]){this.card.path&&!this.card.path.endsWith("/")&&this.card.close();return}this.els.tip.classList.add("hidden"),this.chrome.close();const a=this.notes[e];this.card.showNote(a.path,a.name,a.folder,this.regions.get(a.folder)?.color||"#888",a.tags),n&&this.scene&&this.scene.focus(this.scene.positionOf(e),1.15)}openFolder(e){this.focusRegion(e),this.regions.has(e)&&(this.selected>=0&&(this.selected=-1,this.scene?.select(-1)),this.chrome.close(),this.card.showFolder(e,this.regions.get(e).color,this.regions.get(e).count))}buildCard(){const e=a=>{const i=this.notes[a];return{path:i.path,name:i.name,color:this.regions.get(i.folder)?.color||"#888",degree:i.degree}},n=a=>this.notes.findIndex(i=>i.path===a);return new ng({root:this.root,focusNode:a=>{const i=n(a);i>=0&&this.scene&&this.scene.focus(this.scene.positionOf(i),1.15)},focusFolder:a=>this.focusRegion(a),onlyFolder:a=>this.setHidden(Array.from(this.regions.keys()).filter(i=>i!==a)),pick:a=>{const i=n(a);i>=0&&this.select(i,!0)},links:a=>{const i=n(a),o=this.out.get(i)||[],s=(this.inc.get(i)||[]).filter(r=>!o.includes(r));return{out:o.map(e),in:s.map(e)}},folderItems:a=>this.notes.map((i,o)=>[i,o]).filter(([i])=>i.folder===a).sort((i,o)=>o[0].degree-i[0].degree).map(([,i])=>e(i)),tag:a=>this.chrome.setQuery("#"+a+" "),home:()=>this.scene?.goHome(),closed:()=>{this.selected>=0&&(this.selected=-1,this.scene?.select(-1))}})}onActivity(e){if(!this.scene)return;const n=[];for(const a of e.paths||[]){const i=this.index.get(Li(a))??this.index.get(Li(cv(a)));i!==void 0&&!n.includes(i)&&n.push(i)}this.scene.activity(e.actor||"agent",e.phase||"start",e.ok,n)}onMutation(e){const n=[e.path,e.to,e.new_path].find(a=>typeof a=="string");n&&this.pendingFlare.push(n),this.scheduleRefresh()}scheduleRefresh(){clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.refresh()},450)}}let eu=null;async function TV(){const t=document.getElementById("view-brain");if(t){if(eu&&eu.alive()){eu.scheduleRefresh();return}eu?.destroy(),eu=new AV(t)}}const Sn=240,Dn=136,od=20,Ri=22,ul=24,tu=140;function EV(){return{v:1,frames:{},cards:{}}}function pk(t){let e=Ri*2+Sn,n=ul+Ri+Dn;for(const a of t.cards)a.drag||(e=Math.max(e,a.x+Sn+Ri),n=Math.max(n,a.y+Dn+Ri));return{w:e,h:n}}function La(t){const e=pk(t);return{x:t.x,y:t.y,w:Math.max(t.w,e.w),h:Math.max(t.h,e.h)}}function fl(t,e){return{x:t.x+e.x,y:t.y+e.y,w:Sn,h:Dn}}function dv(t,e){return t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y}function hk(t,e,n){return e>=t.x&&e<=t.x+t.w&&n>=t.y&&n<=t.y+t.h}function sd(t){if(!t.cards.length)return;let e=1/0,n=1/0;for(const o of t.cards)e=Math.min(e,o.x),n=Math.min(n,o.y);const a=e<Ri?e-Ri:0,i=n<ul?n-ul:0;if(!(!a&&!i)){t.x+=a,t.y+=i;for(const o of t.cards)o.x-=a,o.y-=i}}function xC(t){return Math.max(1,Math.min(8,Math.round(Math.sqrt(t*1.5))))}function pv(t){const e=t.cards.slice().sort((i,o)=>o.mtime-i.mtime||i.name.localeCompare(o.name)),n=xC(e.length);e.forEach((i,o)=>{i.x=Ri+o%n*(Sn+od),i.y=ul+Math.floor(o/n)*(Dn+od)});const a=Math.max(1,Math.ceil(e.length/n));t.w=Ri*2+n*Sn+(n-1)*od,t.h=ul+Ri+a*Dn+(a-1)*od}function hv(t,e=0,n=0){if(!t.length)return;const a=t.map(c=>({f:c,b:La(c)})),i=a.reduce((c,d)=>c+(d.b.w+tu)*(d.b.h+tu),0),o=Math.max(Math.sqrt(i)*1.5,Math.max(...a.map(c=>c.b.w)));a.sort((c,d)=>c.f.name==="Root"?-1:d.f.name==="Root"?1:d.b.h-c.b.h||c.f.name.localeCompare(d.f.name));let s=e,r=n,l=0;for(const c of a)s>e&&s+c.b.w>e+o&&(s=e,r+=l+tu,l=0),c.f.x=s,c.f.y=r,s+=c.b.w+tu,l=Math.max(l,c.b.h)}function uk(t,e){const n=xC(t.cards.length+1),a=t.cards.filter(i=>!0);for(let i=0;i<2e3;i++){const o=Ri+i%n*(Sn+od),s=ul+Math.floor(i/n)*(Dn+od),r={x:o-4,y:s-4,w:Sn+8,h:Dn+8};if(!a.some(l=>dv(r,{x:l.x,y:l.y,w:Sn,h:Dn})))return{x:o,y:s}}return{x:Ri,y:ul+pk(t).h}}function _V(t){if(!t.length)return{x:0,y:0};let e=-1/0,n=1/0;for(const a of t){const i=La(a);e=Math.max(e,i.x+i.w),n=Math.min(n,i.y)}return{x:e+tu,y:n}}function fk(t){if(!t.length)return null;let e=1/0,n=1/0,a=-1/0,i=-1/0;for(const o of t)e=Math.min(e,o.x),n=Math.min(n,o.y),a=Math.max(a,o.x+o.w),i=Math.max(i,o.y+o.h);return{x:e,y:n,w:a-e,h:i-n}}function uv(t,e){const n=t.split("/").pop()||t;return!e||e==="Root"?n:e+"/"+n}function CV(t,e){const n=t.split("/");return n[n.length-1]=e+".md",n.join("/")}function LV(t){return t.replace(/[^\w\s-]/g,"").trim().replace(/ /g,"_")}function RV(t){const e=String(t||"?").replace(/[_\-.@]+/g," ").trim().split(/\s+/).filter(Boolean);return e.length?e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase():"?"}function PV(t,e){const a=[e];let i=0;for(;a.length&&i++<200;){const o=a.shift(),s=La(o),r={x:s.x-60,y:s.y-60,w:s.w+120,h:s.h+120};for(const l of t){if(l===o)continue;const c=La(l);if(!dv(r,c))continue;const d=s.y+s.h+60-c.y,p=s.x+s.w+60-c.x;c.y>=s.y&&(d<=p||c.x<s.x)?l.y+=d:c.x>=s.x?l.x+=p:l.y+=d,a.push(l)}}}const fv=[1,-1,0,0],mv=[0,0,1,-1];function gv(t,e){return e===0?[t.x+t.w,t.y+t.h/2]:e===1?[t.x,t.y+t.h/2]:e===2?[t.x+t.w/2,t.y+t.h]:[t.x+t.w/2,t.y]}function mk(t,e,n){const a=Math.min(t[0],e[0]),i=Math.max(t[0],e[0]),o=Math.min(t[1],e[1]),s=Math.max(t[1],e[1]);return i>n.x&&a<n.x+n.w&&s>n.y&&o<n.y+n.h}function bC(t,e){return{x:t.x-e,y:t.y-e,w:t.w+e*2,h:t.h+e*2}}function yC(t){const e=[];for(const n of t){const a=e[e.length-1];if(!(a&&Math.abs(a[0]-n[0])<.01&&Math.abs(a[1]-n[1])<.01)){if(e.length>=2){const i=e[e.length-2],o=Math.abs(i[0]-a[0])<.01&&Math.abs(a[0]-n[0])<.01,s=Math.abs(i[1]-a[1])<.01&&Math.abs(a[1]-n[1])<.01;(o||s)&&e.pop()}e.push(n)}}return e}function wC(t,e,n,a){let i=0,o=0;for(let s=1;s<t.length;s++){const r=t[s-1],l=t[s];i+=Math.abs(l[0]-r[0])+Math.abs(l[1]-r[1]),s>1&&s<t.length-1&&(mk(r,l,n)||mk(r,l,a))&&(o+=2);for(const d of e)mk(r,l,d)&&o++}return i+o*2400+(t.length-2)*40}function kC(t,e,n,a=9,i=9){let o=null,s=1/0;const r=bC(t,.5),l=bC(e,.5);for(let c=0;c<4;c++)for(let d=0;d<4;d++){const p=gv(t,c),h=gv(e,d),u=[p[0]+fv[c]*a,p[1]+mv[c]*a],f=[h[0]+fv[d]*a,h[1]+mv[d]*a],v=(fv[c]*(h[0]-p[0])+mv[c]*(h[1]-p[1])<-a?1:0)+(fv[d]*(p[0]-h[0])+mv[d]*(p[1]-h[1])<-a?1:0),g=[(u[0]+f[0])/2,u[0],f[0]],m=[(u[1]+f[1])/2,u[1],f[1]],b=Math.min(u[1],f[1]),k=Math.max(u[1],f[1]),y=Math.min(u[0],f[0]),w=Math.max(u[0],f[0]);for(const _ of n)_.y<k&&_.y+_.h>b&&g.push(_.x-i,_.x+_.w+i),_.x<w&&_.x+_.w>y&&m.push(_.y-i,_.y+_.h+i);const A=(_,S)=>Array.from(new Set(_.map(T=>Math.round(T)))).sort((T,E)=>Math.abs(T-S)-Math.abs(E-S)).slice(0,9);for(const _ of A(g,(u[0]+f[0])/2)){const S=yC([p,u,[_,u[1]],[_,f[1]],f,h]),T=wC(S,n,r,l)+v*300;T<s&&(s=T,o=S)}for(const _ of A(m,(u[1]+f[1])/2)){const S=yC([p,u,[u[0],_],[f[0],_],f,h]),T=wC(S,n,r,l)+v*300;T<s&&(s=T,o=S)}}return o||[gv(t,0),gv(e,1)]}function IV(t,e,n){t.beginPath(),t.moveTo(e[0][0],e[0][1]);for(let i=1;i<e.length-1;i++){const o=e[i-1],s=e[i],r=e[i+1],l=Math.min(n,Math.hypot(s[0]-o[0],s[1]-o[1])/2,Math.hypot(r[0]-s[0],r[1]-s[1])/2);t.arcTo(s[0],s[1],r[0],r[1],l)}const a=e[e.length-1];t.lineTo(a[0],a[1]),t.stroke()}function rd(t,e){const n=/^#?([0-9a-f]{6})$/i.exec(t.trim());if(!n)return`rgba(148,163,184,${e})`;const a=parseInt(n[1],16);return`rgba(${a>>16&255},${a>>8&255},${a&255},${e})`}const nu=new Map,NV=60;function zV(t){let e=0;for(const n of t){e=e*31+n.x*7+n.y*13+n.cards.length|0;for(const a of n.cards)e=e*31+a.x*3+a.y*5|0}return t.length+":"+e}function DV(t,e,n,a,i){const o=[];for(const s of t===e?[t]:[t,e])for(const r of s.cards)r===n||r===a||o.push({x:s.x+r.x-4,y:s.y+r.y-4,w:Sn+8,h:Dn+8});for(const s of i){if(s===t||s===e)continue;const r=La(s);o.push({x:r.x-12,y:r.y-12,w:r.w+24,h:r.h+24})}return o}function OV(t,e){const{cam:n,w:a,h:i,dpr:o}=e;t.setTransform(o,0,0,o,0,0),t.clearRect(0,0,a,i),t.setTransform(o*n.z,0,0,o*n.z,o*n.x,o*n.y);const s=-n.x/n.z,r=-n.y/n.z,l=s+a/n.z,c=r+i/n.z;if(e.paintCards)for(const v of e.frames){const g=e.color(v.name),m=e.light?"#ffffff":"#151a25",b=e.light?"rgba(15,23,42,.16)":"rgba(230,233,239,.16)";for(const k of v.cards){const y=v.x+k.x,w=v.y+k.y;y>l||w>c||y+Sn<s||w+Dn<r||(t.fillStyle=m,t.beginPath(),t.roundRect(y,w,Sn,Dn,14),t.fill(),t.fillStyle=rd(g,.9),t.fillRect(y,w+12,5,Dn-24),t.fillStyle=e.light?"rgba(15,23,42,.5)":"rgba(230,233,239,.55)",t.fillRect(y+20,w+22,Sn*.62,16),t.fillStyle=b,t.fillRect(y+20,w+56,Sn-40,9),t.fillRect(y+20,w+74,Sn*.55,9),e.selected.has(k.path)&&(t.strokeStyle=e.light?"#0d9488":"#5eead4",t.lineWidth=3/n.z,t.beginPath(),t.roundRect(y,w,Sn,Dn,14),t.stroke()))}}if(!e.showLinks||!e.links.length)return!1;const d=zV(e.frames);let p=NV,h=!1;const u=Math.max(1.2/n.z,1.2);for(const f of[0,1])for(const v of e.links){const g=e.frameOf(v.a),m=e.frameOf(v.b);if(!g||!m)continue;const b=!!e.focus&&(e.focus.has(v.a.path)||e.focus.has(v.b.path));if(f===1!==b)continue;const k=g.x+v.a.x,y=g.y+v.a.y,w=m.x+v.b.x,A=m.y+v.b.y,_=Math.min(k,w),S=Math.min(y,A),T=Math.max(k,w)+Sn,E=Math.max(y,A)+Dn;if(_>l||S>c||T<s||E<r)continue;const P=v.a.path+"\0"+v.b.path,R=k+","+y+","+w+","+A;let B=nu.get(P);if(!B||B.sig!==d){const Ne={x:k,y,w:Sn,h:Dn},Xe={x:w,y:A,w:Sn,h:Dn};p>0?(p--,B={sig:d,ends:R,pts:kC(Ne,Xe,DV(g,m,v.a,v.b,e.frames))},nu.set(P,B)):(h=!0,(!B||B.ends!==R)&&(B={sig:"",ends:R,pts:kC(Ne,Xe,[])}),nu.set(P,B))}const D=B.pts,[$,G]=D[0],[O,J]=D[D.length-1],[ne,ae]=D[D.length-2],q=Math.hypot(O-ne,J-ae)||1,we=(ne-O)/q,Re=(ae-J)/q,ot=e.color(v.a.folder),Qe=e.light?.42:.34,st=b?.95:e.focus?.06:n.z<.3?Qe*.45:n.z<.6?Qe*.75:Qe;t.strokeStyle=rd(ot,st),t.lineWidth=b?u*1.9:u,t.lineJoin="round",IV(t,D,14);const de=(b?9:6)*Math.max(1,1/n.z)*.9,Z=Math.atan2(-Re,-we);t.fillStyle=rd(ot,b?1:st+.1),t.beginPath(),t.moveTo(O,J),t.lineTo(O-Math.cos(Z-.45)*de,J-Math.sin(Z-.45)*de),t.lineTo(O-Math.cos(Z+.45)*de,J-Math.sin(Z+.45)*de),t.closePath(),t.fill(),t.beginPath(),t.arc($,G,(b?3.2:2.2)*Math.max(1,1/n.z)*.8,0,Math.PI*2),t.fill()}return nu.size>e.links.length*3+500&&nu.clear(),h}function $V(t,e){t.setTransform(e.dpr,0,0,e.dpr,0,0),t.clearRect(0,0,e.w,e.h);const n=e.frames.map(p=>La(p));let a=e.view.x,i=e.view.y,o=e.view.x+e.view.w,s=e.view.y+e.view.h;for(const p of n)a=Math.min(a,p.x),i=Math.min(i,p.y),o=Math.max(o,p.x+p.w),s=Math.max(s,p.y+p.h);const r=8,l=Math.min((e.w-r*2)/Math.max(1,o-a),(e.h-r*2)/Math.max(1,s-i)),c=r+(e.w-r*2-(o-a)*l)/2-a*l,d=r+(e.h-r*2-(s-i)*l)/2-i*l;return e.frames.forEach((p,h)=>{const u=n[h],f=e.color(p.name);t.fillStyle=rd(f,e.light?.16:.14),t.strokeStyle=rd(f,.6),t.lineWidth=1,t.fillRect(c+u.x*l,d+u.y*l,u.w*l,u.h*l),t.strokeRect(c+u.x*l+.5,d+u.y*l+.5,u.w*l-1,u.h*l-1),t.fillStyle=rd(f,.75);for(const v of p.cards)t.fillRect(c+(p.x+v.x)*l,d+(p.y+v.y)*l,Math.max(1,Sn*l),Math.max(1,Dn*l))}),t.strokeStyle=e.light?"rgba(15,23,42,.75)":"rgba(230,233,239,.85)",t.lineWidth=1.5,t.fillStyle=e.light?"rgba(15,23,42,.05)":"rgba(230,233,239,.06)",t.fillRect(c+e.view.x*l,d+e.view.y*l,e.view.w*l,e.view.h*l),t.strokeRect(c+e.view.x*l,d+e.view.y*l,e.view.w*l,e.view.h*l),{s:l,ox:c,oy:d}}const SC="memora.canvas.excerpts",FV=3,So=new Map,ml=[],vv=new Set;let MC=()=>{},AC=0,xv=0;try{const t=sessionStorage.getItem(SC);if(t)for(const[e,n]of Object.entries(JSON.parse(t)))So.set(e,n)}catch{}function UV(){clearTimeout(AC),AC=window.setTimeout(()=>{try{const t={};let e=0;for(const[n,a]of So){if(e++>3e3)break;t[n]=a}sessionStorage.setItem(SC,JSON.stringify(t))}catch{}},800)}function BV(t){return String(t||"").replace(/^---[\s\S]*?\n---\s*/,"").replace(/^#\s+.*$/m,"").replace(/```[\s\S]*?```/g," ").replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[#>*_`~|-]+/g," ").replace(/\s+/g," ").trim().slice(0,220)}function HV(t){MC=t}function qV(t){return So.get(t)}function WV(t){So.delete(t)}function GV(t,e){const n=So.get(t);n&&(So.delete(t),So.set(e,n))}function VV(t,e){const n=So.get(t);n&&n.m>=e||vv.has(t)||ml.some(a=>a.path===t)||(ml.push({path:t,mtime:e}),gk())}function jV(t){for(let e=ml.length-1;e>=0;e--)t.has(ml[e].path)||ml.splice(e,1)}function TC(t){xv=Math.max(0,xv+(t?1:-1)),xv||gk()}function gk(){for(;!xv&&vv.size<FV&&ml.length;){const t=ml.pop();vv.add(t.path),Oe("/api/note?path="+encodeURIComponent(t.path)).then(e=>{const n=(e.tags&&e.tags.length?e.tags:o2(e.content)).slice(0,6);So.set(t.path,{m:Math.max(t.mtime,Math.floor(Number(e.mtime)||0)),text:BV(e.content),tags:n}),UV(),MC(t.path)}).catch(()=>{So.set(t.path,{m:t.mtime,text:"",tags:[]})}).finally(()=>{vv.delete(t.path),gk()})}}async function EC(t,e){const n=await Ve("/api/move",{path:t,folder:e||"Root"});return n&&(n.path||n.to)||uv(t,e)}async function YV(t,e){const n=await Ve("/api/rename",{path:t,name:e});return n&&n.path||t}async function XV(t,e){await Ve("/api/folder-meta",{folder:t,color:e})}async function KV(t,e){const n={moved:[],failed:[]},a=t.slice(),i=async()=>{for(;a.length;){const o=a.shift();try{n.moved.push({from:o,to:await EC(o,e)})}catch(s){n.failed.push({path:o,error:s.message})}}};return await Promise.all([i(),i(),i()]),n}const vk="canvas",_C="memora.layout."+vk;let au=null,xk=0,bk=null;function ZV(){try{const t=localStorage.getItem(_C);if(!t)return null;const e=JSON.parse(t);return CC(e)?LC(e):null}catch{return null}}function JV(t){try{localStorage.setItem(_C,JSON.stringify({...t,_at:Date.now()}))}catch{}}function CC(t){const e=t;return!!e&&typeof e=="object"&&!!e.frames&&typeof e.frames=="object"&&!!e.cards&&typeof e.cards=="object"}const yk=(...t)=>t.every(e=>typeof e=="number"&&isFinite(e));function LC(t){const e={},n={};for(const[i,o]of Object.entries(t.frames))o&&yk(o.x,o.y,o.w,o.h)&&(e[i]=o);for(const[i,o]of Object.entries(t.cards))o&&yk(o.x,o.y)&&(n[i]=o);const a=t.view&&yk(t.view.x,t.view.y,t.view.z)&&t.view.z>0?t.view:void 0;return{...t,view:a,frames:e,cards:n}}async function QV(){const t=ZV();try{const e=await Oe("/api/ui/layout/"+vk);if(au=!0,CC(e&&e.data))return LC(e.data)}catch(e){const n=e.status;au=n===404||n===405?!1:null}return t||EV()}async function wk(){const t=bk;if(bk=null,!!t&&(JV(t),au!==!1))try{await $n("/api/ui/layout/"+vk,{method:"PUT",body:{data:t}}),au=!0}catch(e){const n=e.status;(n===404||n===405)&&(au=!1)}}function ej(t,e=!1){bk=t,clearTimeout(xk),e?wk():xk=window.setTimeout(()=>{wk()},700)}function tj(){clearTimeout(xk),wk()}const aa=t=>`<svg viewBox="0 0 24 24" aria-hidden="true">${t}</svg>`,On={pointer:aa('<path d="M5 3l14 8-6.2 1.6L10 19z"/>'),hand:aa('<path d="M8 13V5.5a1.5 1.5 0 0 1 3 0V12M11 11V4.5a1.5 1.5 0 0 1 3 0V12M14 11.5V6a1.5 1.5 0 0 1 3 0v8a6 6 0 0 1-6 6h-.6a6 6 0 0 1-4.6-2.2L3.6 14.6a1.6 1.6 0 0 1 2.3-2.2L8 14.5"/>'),fit:aa('<path d="M4 9V5a1 1 0 0 1 1-1h4M15 4h4a1 1 0 0 1 1 1v4M20 15v4a1 1 0 0 1-1 1h-4M9 20H5a1 1 0 0 1-1-1v-4"/>'),tidy:aa('<rect x="4" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.5"/>'),link:aa('<path d="M5 18c4 0 4-12 9-12h5"/><circle cx="5" cy="18" r="1.6"/><path d="m16 3 3 3-3 3"/>'),help:aa('<circle cx="12" cy="12" r="9"/><path d="M9.6 9.3a2.4 2.4 0 1 1 3.3 2.2c-.8.4-1.1.9-1.1 1.7M12 16.6h.01"/>'),open:aa('<path d="M14 4h6v6M20 4l-8.5 8.5M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"/>'),alL:aa('<path d="M4 3v18M8 7h10M8 13h6M8 17h8"/>'),alC:aa('<path d="M12 3v18M6 7h12M8 12h8M5 17h14"/>'),alR:aa('<path d="M20 3v18M6 7h10M10 12h6M8 17h8"/>'),alT:aa('<path d="M3 4h18M7 8v10M12 8v6M17 8v8"/>'),alM:aa('<path d="M3 12h18M7 6v12M12 8v8M17 5v14"/>'),alB:aa('<path d="M3 20h18M7 6v10M12 10v6M17 8v8"/>'),disH:aa('<path d="M4 4v16M20 4v16"/><rect x="9.5" y="7" width="5" height="10" rx="1"/>'),disV:aa('<path d="M4 4h16M4 20h16"/><rect x="7" y="9.5" width="10" height="5" rx="1"/>'),undo:aa('<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>')},nj='<svg viewBox="0 0 18 18"><path d="M2 1.5l13 6.2-5.6 1.5L7 15z" fill="var(--ac)" stroke="#fff" stroke-width="1.3" stroke-linejoin="round"/></svg>';function ia(t,e,n,a=""){return`<button class="cv-btn ${a}" data-act="${t}" title="${x(n)}" aria-label="${x(n)}">${e}</button>`}function aj(t){const e=re("div","cv-ui cv-tools",ia("tool-select",On.pointer,"Select (V)","on")+ia("tool-hand",On.hand,"Hand (H, or hold Space)","wide")+`<span class="cv-sep"></span><span class="cv-zoom wide" title="Zoom level">100%</span><button class="cv-btn wide" data-act="fit" title="Fit the whole board on screen (Shift+1)" aria-label="Fit the whole board on screen">${On.fit}Fit</button><button class="cv-btn" data-act="zoom-100" title="Actual size, 100% (Shift+0)" aria-label="Actual size, 100%">100%</button><span class="cv-sep"></span>`+ia("tidy",On.tidy,"Tidy up (T: selection, Shift+T: whole board)")+ia("links",On.link,"Show links between notes (L)","on")+ia("help",On.help,"Keyboard shortcuts (?)")),n=e.querySelector(".cv-zoom"),a=re("div","cv-ui cv-selbar hidden",'<span class="cnt"></span><span class="cv-fchips"></span>'+ia("sel-open",On.open,"Preview and open (Enter)")+ia("fit-sel",On.fit,"Focus the selection (Shift+2)")+'<span class="cv-sep"></span>'+ia("al-l",On.alL,"Align left (Alt+A)")+ia("al-c",On.alC,"Align horizontal centers (Alt+H)")+ia("al-r",On.alR,"Align right (Alt+D)")+ia("al-t",On.alT,"Align top (Alt+W)")+ia("al-m",On.alM,"Align vertical centers (Alt+V)")+ia("al-b",On.alB,"Align bottom (Alt+S)")+'<span class="cv-sep"></span>'+ia("dis-h",On.disH,"Distribute horizontally (Alt+Shift+H)")+ia("dis-v",On.disV,"Distribute vertically (Alt+Shift+V)")+'<span class="cv-sep"></span>'+ia("tidy",On.tidy,"Tidy into a grid (T)")),i=re("div","cv-ui cv-toast",'<span class="msg"></span>');i.setAttribute("role","status"),i.setAttribute("aria-live","polite");const o=re("div","cv-ui cv-help hidden",ij());o.setAttribute("role","dialog"),o.setAttribute("aria-label","Canvas keyboard shortcuts");const s=re("div","cv-scrim hidden");return t.append(e,a,i,s,o),{tools:e,zoom:n,selbar:a,toast:i,help:o,scrim:s}}function ij(){const t=n=>n.split(" ").map(a=>`<kbd>${x(a)}</kbd>`).join("");return`<h3>Canvas shortcuts</h3>
|
|
11865
11885
|
<p>Drag a card into another folder frame to move the note on disk. Drag a frame by its name to rearrange the board; drop it onto another frame to move the whole folder there. Double-click a title to rename. On touch: drag to pan, pinch to zoom, long-press a card to move it, tap to preview.</p>
|
|
11866
|
-
<div class="cols">${[["Pan","Space+drag"],["Pan (mouse)","Middle-drag"],["Zoom at cursor","Ctrl+wheel"],["Zoom in / out","+ -"],["Zoom to fit","Shift+1"],["Zoom to selection","Shift+2"],["Zoom to 100%","Shift+0"],["Select / Hand tool","V H"],["Add to selection","Shift+click"],["Select all","Ctrl+A"],["Preview note","Enter"],["Open note","O"],["Rename","F2"],["Nudge","Arrows"],["Align left / right","Alt+A Alt+D"],["Align top / bottom","Alt+W Alt+S"],["Align centers","Alt+H Alt+V"],["Distribute","Alt+Shift+H/V"],["Tidy selection","T"],["Tidy whole board","Shift+T"],["Wikilinks","L"],["Minimap","M"],["Undo last move","Ctrl+Z"],["Clear / close","Esc"]].map(([n,a])=>`<div class="row"><span>${x(n)}</span><span>${t(a)}</span></div>`).join("")}</div>`}class oj{constructor(e){this.node=e}show(e,n={}){this.node.classList.remove("show");const a=n.undo;Xn(e,n.err?"err":"info",n.ms??(a?7e3:3600),a?{label:"Undo",icon:On.undo,run:()=>a()}:void 0,{group:"canvas"})}hide(){bL("canvas")}}async function bv(t){TC(!0);try{return await t()}finally{TC(!1)}}const RC=(t,e)=>bv(()=>EC(t,e)),PC=(t,e)=>bv(()=>YV(t,e)),kk=(t,e)=>bv(()=>KV(t,e)),sj=(t,e)=>bv(()=>XV(t,e)),Sk=.04,IC=4,NC=.8,rj=.7,zC=.45,lj=.2,Mk=600*1e3,cj=380;class dj{constructor(e){this.host=e,this.frames=new Map,this.cards=new Map,this.links=[],this.linkCount=new Map,this.layout={v:1,frames:{},cards:{}},this.cam={x:0,y:0,z:1},this.W=1,this.H=1,this.dpr=1,this.lod=0,this.sel=new Set,this.selFrames=new Set,this.hover=null,this.tool="select",this.space=!1,this.showLinks=!0,this.hiddenFrames=hj(),this.labelPrefs=fj(),this.pointers=new Map,this.g=null,this.zoomAnim=null,this.fly=null,this.inertia=null,this.tween=null,this.edge=null,this.raf=0,this.geomDirty=!0,this.miniAt=0,this.miniMap={s:1,ox:0,oy:0},this.movingTimer=0,this.camSaveTimer=0,this.active=!1,this.ready=!1,this.unsubs=[],this.cursors=new Map,this.undoStack=[],this.flashPending=new Set,this.linksTimer=0,this.syncTimer=0,this.decayTimer=0,this.busy=!1,this.needFit=!1,this.sizes=new WeakMap,this.onKeyBound=n=>this.onKey(n),this.onKeyUpBound=n=>{n.code==="Space"&&(this.space=!1,this.root.classList.toggle("hand",this.tool==="hand"))},this.onBlurBound=()=>{this.space=!1},this.frameOf=n=>this.frames.get(n.folder),this.hits=null,this.lastPointer=-1}async init(){this.build(),this.layout=await QV(),this.showLinks=this.layout.links!==!1,this.syncButtons(),this.sync(),this.layout.view&&isFinite(this.layout.view.z)&&(this.cam={...this.layout.view}),this.needFit=!0,this.ready=!0,this.fitIfNeeded(),this.activate(),this.loadLinks(),this.seedTouches(),pj(this.host,e=>e?this.activate():this.deactivate())}refresh(){this.ready&&(this.activate(),this.sync(),this.scheduleLinks())}build(){this.host.innerHTML="";const e=document.createElement("div");e.className="cv",e.tabIndex=-1,this.root=e,this.bg=document.createElement("div"),this.bg.className="cv-layer cv-bg",this.linkCv=document.createElement("canvas"),this.linkCv.className="cv-links",this.fg=document.createElement("div"),this.fg.className="cv-layer cv-fg",this.marquee=document.createElement("div"),this.marquee.className="cv-marquee hidden",e.append(this.bg,this.linkCv,this.fg,this.marquee),this.host.appendChild(e),this.ctx=this.linkCv.getContext("2d"),this.ui=aj(e),this.vc=this.buildViewChrome(e),this.applyLabelPrefs(),this.toast=new oj(this.ui.toast),this.panel=this.buildCard(e),e.addEventListener("pointerdown",n=>this.onDown(n)),e.addEventListener("pointermove",n=>this.onMove(n)),e.addEventListener("pointerup",n=>this.onUp(n)),e.addEventListener("pointercancel",n=>this.onUp(n,!0)),e.addEventListener("wheel",n=>this.onWheel(n),{passive:!1}),e.addEventListener("dblclick",n=>this.onDbl(n)),e.addEventListener("contextmenu",n=>{n.target.closest("input")||n.preventDefault()}),e.addEventListener("gesturestart",n=>n.preventDefault()),this.wireChrome(),new ResizeObserver(()=>this.resize()).observe(e),this.resize(),HV(n=>{const a=this.cards.get(n);a&&a.el&&this.fillCard(a)})}wireChrome(){const e=this.ui,n=a=>{const i=a.target.closest("[data-act]");i&&this.command(i.dataset.act||"")};e.tools.addEventListener("click",n),e.selbar.addEventListener("click",a=>{const i=a.target.closest("[data-fchip]");if(i){this.focusFolder(i.dataset.fchip||"");return}n(a)}),e.scrim.onclick=()=>this.toggleHelp(!1)}activate(){this.active||!this.ready||this.host.classList.contains("hidden")||(this.active=!0,this.vc.shown(),this.needFit=!0,window.addEventListener("keydown",this.onKeyBound),window.addEventListener("keyup",this.onKeyUpBound),window.addEventListener("blur",this.onBlurBound),this.unsubs.push(Hn("activity",e=>this.onActivity(e))),this.unsubs.push(Hn("mutation",e=>this.onMutation(e))),this.decayTimer=window.setInterval(()=>this.decayTouches(),3e4),this.resize(),this.kick(!0))}deactivate(){this.active&&(this.active=!1,window.removeEventListener("keydown",this.onKeyBound),window.removeEventListener("keyup",this.onKeyUpBound),window.removeEventListener("blur",this.onBlurBound),this.unsubs.forEach(e=>e()),this.unsubs=[],clearInterval(this.decayTimer),cancelAnimationFrame(this.raf),this.raf=0,this.cancelGesture(),this.pointers.clear(),this.edge=null,this.persist(!0),tj())}resize(){const e=this.root.getBoundingClientRect();!e.width||!e.height||(this.W=e.width,this.H=e.height,this.dpr=Math.min(2,window.devicePixelRatio||1),this.linkCv.width=Math.round(this.W*this.dpr),this.linkCv.height=Math.round(this.H*this.dpr),this.fitIfNeeded(),this.kick(!0))}sync(){const e=new Set,n=[],a=!Object.keys(this.layout.frames).length&&!this.frames.size;for(const i of b2()){const o=N.tree[i]||[];if(!o.length)continue;let s=this.frames.get(i),r=!1;if(!s){const l=this.layout.frames[i];s={name:i,x:0,y:0,w:0,h:0,cards:[],el:null},l?Object.assign(s,{x:l.x,y:l.y,w:l.w,h:l.h}):(r=!0,n.push(s)),this.frames.set(i,s)}for(const l of o){e.add(l.path);let c=this.cards.get(l.path);if(c){const d=c.mtime!==l.mtime||c.name!==l.name;if(c.mtime=l.mtime,c.name=l.name||
|
|
11886
|
+
<div class="cols">${[["Pan","Space+drag"],["Pan (mouse)","Middle-drag"],["Zoom at cursor","Ctrl+wheel"],["Zoom in / out","+ -"],["Zoom to fit","Shift+1"],["Zoom to selection","Shift+2"],["Zoom to 100%","Shift+0"],["Select / Hand tool","V H"],["Add to selection","Shift+click"],["Select all","Ctrl+A"],["Preview note","Enter"],["Open note","O"],["Rename","F2"],["Nudge","Arrows"],["Align left / right","Alt+A Alt+D"],["Align top / bottom","Alt+W Alt+S"],["Align centers","Alt+H Alt+V"],["Distribute","Alt+Shift+H/V"],["Tidy selection","T"],["Tidy whole board","Shift+T"],["Wikilinks","L"],["Minimap","M"],["Undo last move","Ctrl+Z"],["Clear / close","Esc"]].map(([n,a])=>`<div class="row"><span>${x(n)}</span><span>${t(a)}</span></div>`).join("")}</div>`}class oj{constructor(e){this.node=e}show(e,n={}){this.node.classList.remove("show");const a=n.undo;Xn(e,n.err?"err":"info",n.ms??(a?7e3:3600),a?{label:"Undo",icon:On.undo,run:()=>a()}:void 0,{group:"canvas"})}hide(){bL("canvas")}}async function bv(t){TC(!0);try{return await t()}finally{TC(!1)}}const RC=(t,e)=>bv(()=>EC(t,e)),PC=(t,e)=>bv(()=>YV(t,e)),kk=(t,e)=>bv(()=>KV(t,e)),sj=(t,e)=>bv(()=>XV(t,e)),Sk=.04,IC=4,NC=.8,rj=.7,zC=.45,lj=.2,Mk=600*1e3,cj=380;class dj{constructor(e){this.host=e,this.frames=new Map,this.cards=new Map,this.links=[],this.linkCount=new Map,this.layout={v:1,frames:{},cards:{}},this.cam={x:0,y:0,z:1},this.W=1,this.H=1,this.dpr=1,this.lod=0,this.sel=new Set,this.selFrames=new Set,this.hover=null,this.tool="select",this.space=!1,this.showLinks=!0,this.hiddenFrames=hj(),this.labelPrefs=fj(),this.pointers=new Map,this.g=null,this.zoomAnim=null,this.fly=null,this.inertia=null,this.tween=null,this.edge=null,this.raf=0,this.geomDirty=!0,this.miniAt=0,this.miniMap={s:1,ox:0,oy:0},this.movingTimer=0,this.camSaveTimer=0,this.active=!1,this.ready=!1,this.unsubs=[],this.cursors=new Map,this.undoStack=[],this.flashPending=new Set,this.linksTimer=0,this.syncTimer=0,this.decayTimer=0,this.busy=!1,this.needFit=!1,this.sizes=new WeakMap,this.onKeyBound=n=>this.onKey(n),this.onKeyUpBound=n=>{n.code==="Space"&&(this.space=!1,this.root.classList.toggle("hand",this.tool==="hand"))},this.onBlurBound=()=>{this.space=!1},this.frameOf=n=>this.frames.get(n.folder),this.hits=null,this.lastPointer=-1}async init(){this.build(),this.layout=await QV(),this.showLinks=this.layout.links!==!1,this.syncButtons(),this.sync(),this.layout.view&&isFinite(this.layout.view.z)&&(this.cam={...this.layout.view}),this.needFit=!0,this.ready=!0,this.fitIfNeeded(),this.activate(),this.loadLinks(),this.seedTouches(),pj(this.host,e=>e?this.activate():this.deactivate())}refresh(){this.ready&&(this.activate(),this.sync(),this.scheduleLinks())}build(){this.host.innerHTML="";const e=document.createElement("div");e.className="cv",e.tabIndex=-1,this.root=e,this.bg=document.createElement("div"),this.bg.className="cv-layer cv-bg",this.linkCv=document.createElement("canvas"),this.linkCv.className="cv-links",this.fg=document.createElement("div"),this.fg.className="cv-layer cv-fg",this.marquee=document.createElement("div"),this.marquee.className="cv-marquee hidden",e.append(this.bg,this.linkCv,this.fg,this.marquee),this.host.appendChild(e),this.ctx=this.linkCv.getContext("2d"),this.ui=aj(e),this.vc=this.buildViewChrome(e),this.applyLabelPrefs(),this.toast=new oj(this.ui.toast),this.panel=this.buildCard(e),e.addEventListener("pointerdown",n=>this.onDown(n)),e.addEventListener("pointermove",n=>this.onMove(n)),e.addEventListener("pointerup",n=>this.onUp(n)),e.addEventListener("pointercancel",n=>this.onUp(n,!0)),e.addEventListener("wheel",n=>this.onWheel(n),{passive:!1}),e.addEventListener("dblclick",n=>this.onDbl(n)),e.addEventListener("contextmenu",n=>{n.target.closest("input")||n.preventDefault()}),e.addEventListener("gesturestart",n=>n.preventDefault()),this.wireChrome(),new ResizeObserver(()=>this.resize()).observe(e),this.resize(),HV(n=>{const a=this.cards.get(n);a&&a.el&&this.fillCard(a)})}wireChrome(){const e=this.ui,n=a=>{const i=a.target.closest("[data-act]");i&&this.command(i.dataset.act||"")};e.tools.addEventListener("click",n),e.selbar.addEventListener("click",a=>{const i=a.target.closest("[data-fchip]");if(i){this.focusFolder(i.dataset.fchip||"");return}n(a)}),e.scrim.onclick=()=>this.toggleHelp(!1)}activate(){this.active||!this.ready||this.host.classList.contains("hidden")||(this.active=!0,this.vc.shown(),this.needFit=!0,window.addEventListener("keydown",this.onKeyBound),window.addEventListener("keyup",this.onKeyUpBound),window.addEventListener("blur",this.onBlurBound),this.unsubs.push(Hn("activity",e=>this.onActivity(e))),this.unsubs.push(Hn("mutation",e=>this.onMutation(e))),this.decayTimer=window.setInterval(()=>this.decayTouches(),3e4),this.resize(),this.kick(!0))}deactivate(){this.active&&(this.active=!1,window.removeEventListener("keydown",this.onKeyBound),window.removeEventListener("keyup",this.onKeyUpBound),window.removeEventListener("blur",this.onBlurBound),this.unsubs.forEach(e=>e()),this.unsubs=[],clearInterval(this.decayTimer),cancelAnimationFrame(this.raf),this.raf=0,this.cancelGesture(),this.pointers.clear(),this.edge=null,this.persist(!0),tj())}resize(){const e=this.root.getBoundingClientRect();!e.width||!e.height||(this.W=e.width,this.H=e.height,this.dpr=Math.min(2,window.devicePixelRatio||1),this.linkCv.width=Math.round(this.W*this.dpr),this.linkCv.height=Math.round(this.H*this.dpr),this.fitIfNeeded(),this.kick(!0))}sync(){const e=new Set,n=[],a=!Object.keys(this.layout.frames).length&&!this.frames.size;for(const i of b2()){const o=N.tree[i]||[];if(!o.length)continue;let s=this.frames.get(i),r=!1;if(!s){const l=this.layout.frames[i];s={name:i,x:0,y:0,w:0,h:0,cards:[],el:null},l?Object.assign(s,{x:l.x,y:l.y,w:l.w,h:l.h}):(r=!0,n.push(s)),this.frames.set(i,s)}for(const l of o){e.add(l.path);let c=this.cards.get(l.path);if(c){const d=c.mtime!==l.mtime||c.name!==l.name;if(c.mtime=l.mtime,c.name=l.name||pn(l.path),c.folder!==i){const p=this.frames.get(c.folder);p&&(p.cards=p.cards.filter(u=>u!==c)),c.folder=i;const h=uk(s);c.x=h.x,c.y=h.y,s.cards.push(c),this.flashPending.add(c.path)}d&&c.el&&this.fillCard(c)}else{const d=this.layout.cards[l.path];if(c={path:l.path,name:l.name||pn(l.path),folder:i,mtime:l.mtime,x:0,y:0,el:null,touch:null,drag:!1},d&&!r)c.x=d.x,c.y=d.y;else if(!r){const p=uk(s);c.x=p.x,c.y=p.y}s.cards.push(c),this.cards.set(l.path,c),this.ready&&this.flashPending.add(l.path)}}}for(const[i,o]of this.cards){if(e.has(i))continue;const s=this.frames.get(o.folder);s&&(s.cards=s.cards.filter(r=>r!==o)),o.el?.remove(),this.cards.delete(i),this.sel.delete(i)}for(const[i,o]of this.frames)o.cards.length||(o.el?.remove(),o.el=null,this.frames.delete(i),this.selFrames.delete(i));for(const i of n)pv(i);if(a)hv(Array.from(this.frames.values()));else if(n.length){const i=Array.from(this.frames.values()).filter(o=>!n.includes(o));for(const o of n){const s=_V(i);o.x=s.x,o.y=s.y,i.push(o)}}for(const i of this.frames.values()){sd(i);const o=La(i),s=Math.round(o.w)+"x"+Math.round(o.h);if(this.sizes.get(i)!==s&&((this.sizes.has(i)||!this.ready)&&this.separate(i),this.sizes.set(i,s)),i.el&&i.el.style.getPropertyValue("--fc")!==Yn(i.name)){this.fillFrame(i);for(const r of i.cards)r.el&&r.el.style.setProperty("--fc",Yn(r.folder))}}for(const i of this.flashPending){const o=this.cards.get(i);o&&o.el&&this.flash(o)}this.vc.setEmpty(this.cards.size===0),this.fitIfNeeded(),this.vc?.refreshRegions(),this.geomDirty=!0,this.persist(),this.kick(!0)}separate(e){e&&this.frames.has(e.name)&&PV(Array.from(this.frames.values()),e)}fitIfNeeded(){!this.needFit||!this.ready||this.W<50||!this.frames.size||(this.needFit=!1,this.openView())}openView(){const e=this.allBounds();if(!e)return;const n=this.W<=760,a=n?28:80;if(Math.min((this.W-a*2)/e.w,(this.H-a*2-40)/(e.h+40))>=NC){this.fitTo(e,!1);return}const o=n?rj:NC,s=n?60:84,r=n?76:96;this.cam={z:o,x:s-e.x*o,y:r-e.y*o},this.kick(!0)}scheduleLinks(){clearTimeout(this.linksTimer),this.linksTimer=window.setTimeout(()=>{this.loadLinks()},500)}async loadLinks(){let e;try{e=await Oe("/api/graph")}catch{return}const n=new Map;for(const s of e.nodes||[])s.path&&!n.has(s.id)&&n.set(s.id,s.path);const a=[],i=new Map,o=new Set;for(const s of e.links||[]){const r=this.cards.get(n.get(s.source)||""),l=this.cards.get(n.get(s.target)||"");if(!r||!l||r===l)continue;const c=r.path+`
|
|
11867
11887
|
`+l.path;o.has(c)||(o.add(c),a.push({a:r,b:l}),i.set(r.path,(i.get(r.path)||0)+1),i.set(l.path,(i.get(l.path)||0)+1))}this.links=a,this.linkCount=i;for(const s of this.cards.values())s.el&&this.fillCard(s);this.vc?.refreshRegions(),this.kick()}async seedTouches(){try{const e=await Oe("/api/logs?range=1h&limit=300"),n=N.me?.user||N.me?.username||"",a=Date.now();for(const i of(e.events||[]).slice().reverse()){const o=String(i.actor||i.by||i.user||""),s=String(i.path||i.node&&i.node.path||"");if(!o||!s||o===n||o==="web"||o==="browser")continue;const r=Number(i.ts||0)*1e3;if(!r||a-r>Mk)continue;const l=this.findCard(s);l&&(!l.touch||l.touch.at<r)&&(l.touch={actor:o,label:String(i.action||i.label||i.event||"edit"),at:r,live:!1},l.el&&this.fillCard(l))}}catch{}}persist(e=!1){if(!this.ready)return;const n={},a={};for(const o of this.frames.values()){n[o.name]={x:Math.round(o.x),y:Math.round(o.y),w:Math.round(o.w),h:Math.round(o.h)};for(const s of o.cards)a[s.path]={x:Math.round(s.x),y:Math.round(s.y)}}const i={x:Math.round(this.cam.x),y:Math.round(this.cam.y),z:+this.cam.z.toFixed(4)};this.layout={v:1,view:i,frames:n,cards:a,links:this.showLinks,minimap:this.vc.prefs.minimap},ej(this.layout,e)}saveCamSoon(){clearTimeout(this.camSaveTimer),this.camSaveTimer=window.setTimeout(()=>this.persist(),900)}kick(e=!1){e&&(this.geomDirty=!0),!this.raf&&this.active&&(this.raf=requestAnimationFrame(n=>this.frame(n)))}markMoving(){this.root.classList.add("moving"),clearTimeout(this.movingTimer),this.movingTimer=window.setTimeout(()=>this.root.classList.remove("moving"),160)}frame(e){this.raf=0;let n=!1;const a=this.cam,i=a.z,o=a.x,s=a.y;if(this.fly){const l=Math.min(1,(e-this.fly.t0)/this.fly.ms),c=1-Math.pow(1-l,3),[d,p,h]=this.fly.c0,[u,f,v]=this.fly.c1,g=Math.exp(Math.log(h)+(Math.log(v)-Math.log(h))*c),m=d+(u-d)*c,b=p+(f-p)*c;a.z=g,a.x=this.W/2-m*g,a.y=this.H/2-b*g,l>=1?(this.fly=null,this.saveCamSoon()):n=!0}if(this.zoomAnim){const l=this.zoomAnim;let c=a.z+(l.zt-a.z)*.28;Math.abs(l.zt-c)<l.zt*.002?(c=l.zt,this.zoomAnim=null,this.saveCamSoon()):n=!0;const d=(l.ax-a.x)/a.z,p=(l.ay-a.y)/a.z;a.z=c,a.x=l.ax-d*c,a.y=l.ay-p*c}if(this.inertia){const l=this.inertia,c=Math.min(48,e-l.t||16);l.t=e,a.x+=l.vx*c,a.y+=l.vy*c;const d=Math.pow(.93,c/16);l.vx*=d,l.vy*=d,Math.hypot(l.vx,l.vy)<.015?(this.inertia=null,this.saveCamSoon()):n=!0}if(this.edge&&this.g&&(this.g.kind==="card-drag"||this.g.kind==="frame-drag")&&(a.x-=this.edge.vx,a.y-=this.edge.vy,this.dragMove(this.g.px,this.g.py),n=!0),this.tween){const l=this.tween,c=Math.min(1,(e-l.t0)/l.ms),d=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2;for(const p of l.items)p.o.x=p.fx+(p.tx-p.fx)*d,p.o.y=p.fy+(p.ty-p.fy)*d;this.geomDirty=!0,c>=1?this.tween=null:n=!0}const r=a.x!==o||a.y!==s||a.z!==i;r&&this.markMoving(),this.applyCam(),(r||this.geomDirty)&&this.virtualize(),this.geomDirty&&this.placeAll(),this.geomDirty=!1,this.drawLinks(),this.vc.prefs.minimap&&(e-this.miniAt>60||!n)&&(this.miniAt=e,this.vc.redrawMini()),n&&this.kick()}applyCam(){const{x:e,y:n,z:a}=this.cam,i=`translate(${e}px,${n}px) scale(${a})`;this.bg.style.transform=i,this.fg.style.transform=i;const o=this.root.style;o.setProperty("--z",String(a)),o.setProperty("--iz",String(1/a)),o.setProperty("--lz",String(Math.min(1/a,4.2)*(a<.6?1.15:1)));let s=24;for(;s*a<14;)s*=2;for(;s*a>56;)s/=2;const r=s*a;o.backgroundImage=`radial-gradient(circle, var(--cv-dot) ${a>.6?1.1:.9}px, transparent ${a>.6?1.5:1.3}px)`,o.backgroundSize=`${r}px ${r}px`,o.backgroundPosition=`${e%r}px ${n%r}px`;const l=a<lj?2:a<zC?1:0;l!==this.lod&&(this.lod=l,this.root.classList.toggle("lod1",l>=1),this.geomDirty=!0),this.ui.zoom.textContent=Math.round(a*100)+"%"}viewBox(e=0){const n=this.cam.z;return{x:-this.cam.x/n-e/n,y:-this.cam.y/n-e/n,w:this.W/n+2*e/n,h:this.H/n+2*e/n}}virtualize(){const e=this.viewBox(240),n=new Set;for(const a of this.frames.values()){a.el||this.mountFrame(a);const i=this.hiddenFrames.has(a.name);a.el.style.display=i?"none":"";for(const o of a.cards){const s=!i&&(o.drag||o.el&&o.el.querySelector("input"));!i&&this.lod<2&&dv(e,fl(a,o))||s?(n.add(o.path),o.el||(this.mountCard(o),this.placeCard(o,a))):o.el&&(o.el.remove(),o.el=null)}}jV(n)}placeAll(){for(const e of this.frames.values()){this.placeFrame(e);for(const n of e.cards)n.el&&this.placeCard(n,e)}}mountFrame(e){const n=document.createElement("div");n.className="cv-frame",n.dataset.frame=e.name,n.innerHTML='<div class="cv-flabel" title="Drag to move the folder frame; double-click to rename"><i class="cv-fdot"></i><span class="cv-ftitle"></span><span class="cv-fcount"></span><button class="cv-fbtn" data-fact="tidy" title="Tidy this frame">⊞</button><button class="cv-fbtn" data-fact="color" title="Folder color">◐</button></div><div class="cv-fresize" title="Resize frame"></div>',e.el=n,this.bg.appendChild(n),this.fillFrame(e)}fillFrame(e){if(!e.el)return;e.el.style.setProperty("--fc",Yn(e.name));const n=e.el.querySelector(".cv-ftitle");n.querySelector("input")||(n.textContent=/^root$/i.test(e.name)?"Top level":e.name),e.el.querySelector(".cv-fcount").textContent=String(e.cards.length),e.el.classList.toggle("sel",this.selFrames.has(e.name))}placeFrame(e){if(!e.el)return;const n=La(e);e.el.style.transform=`translate(${n.x}px,${n.y}px)`,e.el.style.width=n.w+"px",e.el.style.height=n.h+"px";const a=e.el.querySelector(".cv-fcount");a&&a.textContent!==String(e.cards.length)&&(a.textContent=String(e.cards.length))}mountCard(e){const n=document.createElement("div");n.className="cv-card",n.dataset.path=e.path,e.el=n,this.fillCard(e),this.fg.appendChild(n),this.flashPending.has(e.path)&&this.flash(e)}fillCard(e){const n=e.el;if(!n||n.querySelector("input"))return;const a=qV(e.path);(!a||a.m<e.mtime)&&VV(e.path,e.mtime);const i=a?a.tags.slice(0,3).map(l=>`<span>#${x(l)}</span>`).join(""):"",o=this.linkCount.get(e.path)||0,s=e.touch&&Date.now()-e.touch.at<Mk?e.touch:null,r=s?An(s.actor):"";n.style.setProperty("--fc",Yn(e.folder)),r&&n.style.setProperty("--ac",r),n.classList.toggle("touched",!!s),n.classList.toggle("live",!!(s&&s.live)),n.classList.toggle("sel",this.sel.has(e.path)),this.markHit(e),n.innerHTML=`<div class="cv-ctitle"><span>${x(e.name)}</span></div>
|
|
11868
11888
|
<div class="cv-cex${a?"":" loading"}">${a?x(a.text):""}</div>
|
|
11869
11889
|
<div class="cv-ctags">${i}</div>
|
|
11870
11890
|
<div class="cv-cfoot"><span title="Last edited">${x(kn(e.mtime))}</span>${o?`<span title="${o} ${o===1?"link":"links"} to other notes">↔ ${o}</span>`:""}<span class="grow"></span>${s?`<span class="cv-agent${s.live?" live":""}" title="${x(s.actor)}: ${x(s.label)} (${x(kn(s.at/1e3))})">${x(RV(s.actor))}</span>`:""}</div>
|
|
11871
|
-
<button class="cv-copen" title="Preview (Enter)" aria-label="Preview">${On.open}</button>`}placeCard(e,n=this.frameOf(e)){!e.el||!n||(e.el.style.transform=`translate(${n.x+e.x}px,${n.y+e.y}px)`)}flash(e){this.flashPending.delete(e.path),e.el&&(e.el.classList.remove("flash"),e.el.offsetWidth,e.el.classList.add("flash"))}drawLinks(){const e=this.hover||this.sel.size?new Set(this.sel):null;e&&this.hover&&e.add(this.hover),OV(this.ctx,{cam:this.cam,w:this.W,h:this.H,dpr:this.dpr,links:this.hiddenFrames.size?this.links.filter(a=>!this.hiddenFrames.has(a.a.folder)&&!this.hiddenFrames.has(a.b.folder)):this.links,showLinks:this.showLinks,focus:e,paintCards:this.lod===2,frames:this.shownFrames(),frameOf:this.frameOf,color:Yn,selected:this.sel,light:document.documentElement.dataset.theme==="light"})&&this.kick()}paintMini(e,n,a,i){const o=e.getContext("2d");o&&(this.miniMap=$V(o,{w:n,h:a,dpr:i,frames:this.shownFrames(),color:Yn,view:this.viewBox(),light:document.documentElement.dataset.theme==="light"}))}applyLabelPrefs(){this.root.classList.toggle("no-node-text",!this.labelPrefs.nodes),this.root.classList.toggle("no-folder-titles",!this.labelPrefs.folders)}focusFolder(e){const n=this.frames.get(e);if(n){if(this.hiddenFrames.has(e)){const a=new Set(this.hiddenFrames);a.delete(e),this.setHiddenFrames(a),this.vc.refreshRegions()}this.fitTo(La(n)),this.flashFrame(n)}}flashFrame(e){window.setTimeout(()=>{const n=e.el;n&&(n.classList.remove("flash"),n.offsetWidth,n.classList.add("flash"),window.setTimeout(()=>n.classList.remove("flash"),1700))},250)}shownFrames(){const e=Array.from(this.frames.values());return this.hiddenFrames.size?e.filter(n=>!this.hiddenFrames.has(n.name)):e}setHiddenFrames(e){this.hiddenFrames=new Set(e),uj(this.hiddenFrames);for(const n of Array.from(this.sel))this.hiddenFrames.has(this.cards.get(n)?.folder||"")&&this.sel.delete(n);this.paintSelection(),this.geomDirty=!0,this.kick(!0),requestAnimationFrame(()=>this.vc.redrawMini())}buildViewChrome(e){const n=(a,i)=>{const o=this.cam.z,s=[(this.W/2-this.cam.x)/o,(this.H/2-this.cam.y)/o,o];this.zoomAnim=null,this.inertia=null,this.fly={t0:performance.now(),ms:200,c0:s,c1:[s[0]+a*this.W*.16/o,s[1]+i*this.H*.16/o,o]},this.kick(),this.saveCamSoon()};return new lw({page:"canvas",root:e,search:{placeholder:"Find a note, #tag or in:folder",find:{items:()=>{const a=new Map(N.graph.nodes.map(i=>[i.path||i.id,i]));return Array.from(this.cards.values()).map(i=>{const o=a.get(i.path);return{id:i.path,name:i.name,folder:i.folder,region:i.folder,color:Yn(i.folder),tags:Array.isArray(o?.tags)?o.tags.map(String):[],degree:o?.degree||0}})},hidden:a=>this.hiddenFrames.has(a),highlight:a=>this.lightCards(a),pick:a=>{const i=this.cards.get(a.id);i&&(this.reveal(i,!0),this.openPanel(i))},folder:a=>{this.focusFolder(a),this.openFolderCard(a)}}},changed:()=>!this.labelPrefs.nodes||!this.labelPrefs.folders||!this.showLinks||this.hiddenFrames.size>0||!!this.hits||!!this.panel?.isOpen||this.sel.size>0||this.selFrames.size>0,labels:{get:()=>({nodes:this.labelPrefs.nodes,folders:this.labelPrefs.folders}),set:(a,i)=>{this.labelPrefs[a]=i,$C(this.labelPrefs),this.applyLabelPrefs()},help:{nodes:"The preview text, tags and footer on each card. Titles always stay.",folders:"The name and count over each folder frame."}},filter:a=>this.renderFilter(a),reset:()=>{this.labelPrefs={nodes:!0,folders:!0},$C(this.labelPrefs),this.applyLabelPrefs(),this.showLinks=!0,this.syncButtons(),this.persist(),this.vc.finder?.clear(),this.closePanel(),this.setHiddenFrames([]),this.select([]),this.selFrames.clear(),this.paintSelection(),this.animate(()=>{for(const a of this.frames.values())pv(a);hv(Array.from(this.frames.values()),0,0)}),window.setTimeout(()=>this.fitTo(this.allBounds()),420)},regions:{list:()=>Array.from(this.frames.values()).sort((a,i)=>i.cards.length-a.cards.length||a.name.localeCompare(i.name)).map(a=>({name:a.name,color:Yn(a.name),count:a.cards.length,hidden:this.hiddenFrames.has(a.name)})),toggle:a=>{const i=new Set(this.hiddenFrames);i.has(a)?i.delete(a):i.add(a),this.setHiddenFrames(i)},setAll:a=>this.setHiddenFrames(a?Array.from(this.frames.keys()):[]),focus:a=>{const i=this.frames.get(a);i&&(this.fitTo(La(i)),this.flashFrame(i),this.openFolderCard(a))}},nav:{zoom:a=>this.zoomAt(a,this.W/2,this.H/2),fit:()=>this.fitTo(this.allBounds()),nudge:n,home:()=>this.fitTo(this.allBounds())},minimap:(a,i,o,s)=>this.paintMini(a,i,o,s),minimapNav:(a,i)=>{const o=this.vc.miniCanvas.getBoundingClientRect(),s=this.miniMap,r=(a*o.width-s.ox)/s.s,l=(i*o.height-s.oy)/s.s;this.stopAnims(),this.cam.x=this.W/2-r*this.cam.z,this.cam.y=this.H/2-l*this.cam.z,this.kick(!0),this.saveCamSoon()},onPrefs:()=>this.kick(),onOverlay:()=>this.closePanel()})}lightCards(e){this.hits=e,this.root.classList.toggle("searching",!!this.hits);for(const n of this.cards.values())n.el&&this.markHit(n)}markHit(e){const n=!!this.hits&&this.hits.has(e.path);e.el?.classList.toggle("hit",n)}renderFilter(e){e.innerHTML="<h4>Canvas</h4>"+po("links","Link lines",this.showLinks,"Lines between cards for every link from one note to another, routed around cards and frames.")+'<button type="button" class="vc-act" data-tidy title="Lay every folder frame out in a neat grid">Tidy the whole board</button><div class="vc-hint">V select · H or Space pan · T tidy · L wires · M minimap · ? all shortcuts</div>',e.querySelector("[data-t=links]").onclick=()=>{this.command("links"),this.vc.renderPanel()},e.querySelector("[data-tidy]").onclick=()=>this.tidy(null,!0)}stopAnims(){this.fly=null,this.inertia=null,this.zoomAnim=null}zoomAt(e,n,a){this.fly=null,this.inertia=null;const i=this.zoomAnim?this.zoomAnim.zt:this.cam.z,o=Math.max(Sk,Math.min(IC,i*e));this.zoomAnim={zt:o,ax:n,ay:a},this.kick()}zoomTo(e){this.zoomAnim=null,this.zoomAt(e/this.cam.z,this.W/2,this.H/2)}allBounds(){return fk(this.shownFrames().map(e=>La(e)))}selectionBounds(){const e=[];for(const n of this.sel){const a=this.cards.get(n),i=a&&this.frameOf(a);a&&i&&e.push(fl(i,a))}for(const n of this.selFrames){const a=this.frames.get(n);a&&e.push(La(a))}return fk(e)}fitTo(e,n=!0,a=1.25){if(!e)return;const i=this.panel&&this.panel.isOpen&&this.W>760?400:0,o=this.W<600?28:80,s=this.W-i,r=Math.max(Sk,Math.min(a,(s-o*2)/e.w,(this.H-o*2-40)/(e.h+40))),l=e.x+e.w/2,c=e.y+e.h/2-12/r,d=[l+i/2/r,c,r];if(!n){this.cam={z:r,x:this.W/2-d[0]*r,y:this.H/2-d[1]*r},this.kick(!0);return}const p=[(this.W/2-this.cam.x)/this.cam.z,(this.H/2-this.cam.y)/this.cam.z,this.cam.z];this.zoomAnim=null,this.inertia=null,this.fly={t0:performance.now(),ms:420,c0:p,c1:d},this.kick()}reveal(e,n){const a=this.frameOf(e);if(!a)return;const i=fl(a,e),o=this.viewBox(-60);!n&&hk(o,i.x,i.y)&&hk(o,i.x+i.w,i.y+i.h)&&this.cam.z>=zC||this.fitTo({x:i.x-160,y:i.y-120,w:i.w+320,h:i.h+240},!0,Math.max(this.cam.z,1))}select(e,n=!1){n||(this.sel.clear(),this.selFrames.clear());for(const a of e)this.sel.add(a);this.paintSelection()}paintSelection(){for(const r of this.cards.values())r.el&&r.el.classList.toggle("sel",this.sel.has(r.path));for(const r of this.frames.values())r.el?.classList.toggle("sel",this.selFrames.has(r.name));const e=this.sel.size,n=e>=1||this.selFrames.size>0;this.ui.selbar.classList.toggle("hidden",!n),this.root.classList.toggle("has-sel",n);const a=this.ui.selbar.querySelector(".cnt");a.textContent=e?`${e} note${e===1?"":"s"}`:`${this.selFrames.size} folder${this.selFrames.size===1?"":"s"}`,this.ui.selbar.querySelectorAll("[data-act^=al-],[data-act^=dis-]").forEach(r=>{r.classList.toggle("hidden",r.dataset.act.startsWith("dis-")?e<3:e<2)}),this.ui.selbar.querySelectorAll(".cv-sep").forEach((r,l)=>r.classList.toggle("hidden",l<2&&e<2)),this.ui.selbar.querySelector("[data-act=sel-open]")?.classList.toggle("hidden",e!==1);const i=new Map;for(const r of this.sel){const l=this.cards.get(r);l&&i.set(l.folder,(i.get(l.folder)||0)+1)}for(const r of this.selFrames)i.set(r,i.get(r)||0);const o=Array.from(i.keys()),s=this.ui.selbar.querySelector(".cv-fchips");if(s.innerHTML=o.slice(0,3).map(r=>`<button class="cv-btn cv-fchip" data-fchip="${x(r)}" title="Focus folder ${x(r)}"><i class="cv-fdot" style="--fc:${x(Yn(r))}"></i><span>${x(r==="Root"?"Vault":r.split("/").pop()||r)}</span></button>`).join("")+(o.length>3?`<span class="cv-fmore">+${o.length-3}</span>`:""),this.panel.isOpen&&e===1){const r=this.cards.get(Array.from(this.sel)[0]);r&&this.panel.path!==r.path&&this.openPanel(r)}this.kick()}selectedCards(){return Array.from(this.sel).map(e=>this.cards.get(e)).filter(e=>!!e)}pt(e){const n=this.root.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}toWorld(e,n){return{x:(e-this.cam.x)/this.cam.z,y:(n-this.cam.y)/this.cam.z}}frameAt(e,n,a){let i=null;for(const o of this.frames.values()){if(a&&a.has(o)||this.hiddenFrames.has(o.name))continue;const s=La(o);hk(s,e,n)&&(i=o)}return i}onDown(e){const n=e.target;if(n.closest(".cv-ui")||n.closest("input"))return;if(n.closest(".cv-copen")){const p=n.closest(".cv-card"),h=p&&this.cards.get(p.dataset.path||"");h&&(e.stopPropagation(),this.select([h.path]),this.openPanel(h));return}const a=n.closest(".cv-fbtn");if(a){const p=a.closest(".cv-frame"),h=p&&this.frames.get(p.dataset.frame||"");h&&(a.dataset.fact==="tidy"?this.tidy([h],!1):(te.openFolderColor(h.name),this.recolorWhenModalCloses()));return}const i=this.pt(e);if(this.pointers.set(e.pointerId,{x:i.x,y:i.y,type:e.pointerType}),e.pointerType!=="mouse"&&this.capture(e.pointerId),this.lastPointer=e.pointerId,this.inertia=null,this.fly=null,this.pointers.size===2){this.cancelGesture();const[p,h]=Array.from(this.pointers.values());this.g={kind:"pinch",d0:Math.hypot(p.x-h.x,p.y-h.y)||1,z0:this.cam.z,cx:(p.x+h.x)/2,cy:(p.y+h.y)/2};return}if(this.pointers.size>2)return;const o=n.closest(".cv-card"),s=n.closest(".cv-flabel"),r=n.closest(".cv-fresize"),l=n.closest(".cv-frame"),c=e.pointerType!=="mouse",d=e.button===1||this.space||this.tool==="hand"||c&&!o&&!s&&!r;if(e.button!==2){if(d){e.preventDefault(),this.g={kind:"pan",lx:i.x,ly:i.y,samples:[{x:i.x,y:i.y,t:performance.now()}]},this.root.classList.add("panning");return}if(r&&l){const p=this.frames.get(l.dataset.frame||"");if(p){const h=La(p);this.g={kind:"resize",frame:p,sx:i.x,sy:i.y,w:h.w,h:h.h}}return}if(s&&l){const p=this.frames.get(l.dataset.frame||"");if(!p)return;e.shiftKey?(this.selFrames.has(p.name)?this.selFrames.delete(p.name):this.selFrames.add(p.name),this.paintSelection()):this.selFrames.has(p.name)||(this.sel.clear(),this.selFrames.clear(),this.selFrames.add(p.name),this.paintSelection()),this.g={kind:"frame-pending",frame:p,sx:i.x,sy:i.y};return}if(o){const p=this.cards.get(o.dataset.path||"");if(!p)return;const h={kind:"card-pending",card:p,sx:i.x,sy:i.y,shift:e.shiftKey,touch:c,timer:0};c&&(h.timer=window.setTimeout(()=>{if(this.g===h){try{navigator.vibrate?.(12)}catch{}this.beginCardDrag(h,h.sx,h.sy)}},cj)),this.g=h;return}if(l&&!c){const p=this.frames.get(l.dataset.frame||"");if(p&&this.selFrames.has(p.name)&&!e.shiftKey){this.g={kind:"frame-pending",frame:p,sx:i.x,sy:i.y};return}}this.g={kind:"marquee-pending",sx:i.x,sy:i.y,shift:e.shiftKey}}}onMove(e){const n=this.pt(e),a=this.pointers.get(e.pointerId);a&&(a.x=n.x,a.y=n.y);const i=this.g;if(i&&a&&e.pointerType==="mouse"&&i.kind!=="card-pending"&&i.kind!=="marquee-pending"&&i.kind!=="frame-pending"&&this.capture(e.pointerId),!i){if(e.pointerType==="mouse"){const o=e.target.closest(".cv-card"),s=o&&o.dataset.path||null;s!==this.hover&&(this.hover=s,this.kick())}return}if(a)switch(i.kind){case"pinch":{const o=Array.from(this.pointers.values());if(o.length<2)return;const[s,r]=o,l=Math.hypot(s.x-r.x,s.y-r.y)||1,c=(s.x+r.x)/2,d=(s.y+r.y)/2,p=Math.max(Sk,Math.min(IC,i.z0*l/i.d0)),h=(i.cx-this.cam.x)/this.cam.z,u=(i.cy-this.cam.y)/this.cam.z;this.cam.z=p,this.cam.x=c-h*p,this.cam.y=d-u*p,i.cx=c,i.cy=d,this.kick();return}case"pan":{i.d=(i.d||0)+Math.abs(n.x-i.lx)+Math.abs(n.y-i.ly),this.cam.x+=n.x-i.lx,this.cam.y+=n.y-i.ly,i.lx=n.x,i.ly=n.y;const o=performance.now();for(i.samples.push({x:n.x,y:n.y,t:o});i.samples.length>2&&o-i.samples[0].t>90;)i.samples.shift();this.kick();return}case"card-pending":{const o=Math.hypot(n.x-i.sx,n.y-i.sy);if(i.touch){o>8&&(clearTimeout(i.timer),this.g={kind:"pan",lx:n.x,ly:n.y,samples:[{x:n.x,y:n.y,t:performance.now()}]},this.cam.x+=n.x-i.sx,this.cam.y+=n.y-i.sy,this.kick());return}o>3&&this.beginCardDrag(i,n.x,n.y);return}case"card-drag":case"frame-drag":i.px=n.x,i.py=n.y,this.edgeScroll(n.x,n.y),this.dragMove(n.x,n.y);return;case"marquee-pending":Math.hypot(n.x-i.sx,n.y-i.sy)>3&&(this.g={kind:"marquee",sx:i.sx,sy:i.sy,px:n.x,py:n.y,base:i.shift?new Set(this.sel):new Set},i.shift||this.selFrames.clear(),this.updateMarquee());return;case"marquee":i.px=n.x,i.py=n.y,this.updateMarquee();return;case"frame-pending":if(Math.hypot(n.x-i.sx,n.y-i.sy)>3){const s=(this.selFrames.has(i.frame.name)?Array.from(this.selFrames):[i.frame.name]).map(r=>this.frames.get(r)).filter(r=>!!r).map(r=>({f:r,x:r.x,y:r.y}));this.g={kind:"frame-drag",frames:s,sx:i.sx,sy:i.sy,px:n.x,py:n.y,drop:null};for(const r of s)r.f.el&&this.bg.appendChild(r.f.el);this.dragMove(n.x,n.y)}return;case"resize":{const o=i.frame,s=pk(o);o.w=Math.max(s.w,i.w+(n.x-i.sx)/this.cam.z),o.h=Math.max(s.h,i.h+(n.y-i.sy)/this.cam.z),this.placeFrame(o),this.kick();return}default:return}}onUp(e,n=!1){const a=this.pointers.delete(e.pointerId),i=this.g;if(this.root.classList.remove("panning"),this.edge=null,!(!i||!a)){if(i.kind==="pinch"){if(this.pointers.size<2){this.g=null;const o=Array.from(this.pointers.values())[0];o&&(this.g={kind:"pan",lx:o.x,ly:o.y,samples:[]}),this.saveCamSoon()}return}if(this.g=null,n){(i.kind==="card-drag"||i.kind==="frame-drag")&&this.revertDrag(i),this.marquee.classList.add("hidden");return}switch(i.kind){case"pan":{(i.d||0)<6&&e.pointerType!=="mouse"&&!e.target.closest(".cv-card,.cv-flabel")&&(this.sel.size||this.selFrames.size?this.select([]):this.panel.isOpen&&this.closePanel());const o=i.samples;if(o.length>=2){const s=o[0],r=o[o.length-1],l=Math.max(1,r.t-s.t);performance.now()-r.t<60&&l>4&&(this.inertia={vx:(r.x-s.x)/l,vy:(r.y-s.y)/l,t:performance.now()},Math.hypot(this.inertia.vx,this.inertia.vy)<.08&&(this.inertia=null))}this.kick(),this.saveCamSoon();return}case"card-pending":{clearTimeout(i.timer);const o=i.card;if(i.touch){this.select([o.path]),this.openPanel(o);return}i.shift?(this.sel.has(o.path)?this.sel.delete(o.path):this.sel.add(o.path),this.paintSelection()):this.select([o.path]);return}case"card-drag":this.dropCards(i);return;case"frame-drag":this.dropFrames(i);return;case"frame-pending":this.openFolderCard(i.frame.name);return;case"marquee":this.marquee.classList.add("hidden"),this.paintSelection();return;case"marquee-pending":i.shift||this.select([]);return;case"resize":this.separate(i.frame),this.persist();return;default:return}}}capture(e=this.lastPointer){try{this.root.hasPointerCapture(e)||this.root.setPointerCapture(e)}catch{}}cancelGesture(){const e=this.g;e&&(e.kind==="card-pending"&&clearTimeout(e.timer),(e.kind==="card-drag"||e.kind==="frame-drag")&&this.revertDrag(e),this.marquee.classList.add("hidden"),this.root.classList.remove("panning"),this.g=null)}onWheel(e){if(e.target.closest(".nc,.cv-help"))return;e.preventDefault();const n=this.pt(e),a=e.deltaMode===1,i=a?e.deltaY*16:e.deltaY,o=a?e.deltaX*16:e.deltaX;if(e.ctrlKey||e.metaKey){this.zoomAt(Math.exp(-Math.max(-50,Math.min(50,i))*.0085),n.x,n.y);return}if((a||o===0&&Math.abs(i)>=40&&Number.isInteger(i))&&!e.shiftKey){this.zoomAt(Math.exp(-Math.max(-120,Math.min(120,i))*.0021),n.x,n.y);return}this.stopAnims(),e.shiftKey&&o===0?this.cam.x-=i:(this.cam.x-=o,this.cam.y-=i),this.kick(),this.saveCamSoon()}onDbl(e){let n=e.target;if(n===this.root&&(n=document.elementFromPoint(e.clientX,e.clientY)||n),n.closest(".cv-ui")||n.closest("input"))return;const a=n.closest(".cv-flabel");if(a){const o=a.closest(".cv-frame"),s=o&&this.frames.get(o.dataset.frame||"");s&&this.startRenameFrame(s);return}const i=n.closest(".cv-card");if(i){const o=this.cards.get(i.dataset.path||"");if(!o)return;n.closest(".cv-ctitle")?this.startRenameCard(o):this.openPanel(o);return}if(!n.closest(".cv-frame")){const o=this.pt(e);this.zoomAt(1.6,o.x,o.y)}}edgeScroll(e,n){const o=e<36?-9:e>this.W-36?9:0,s=n<36?-9:n>this.H-36?9:0;this.edge=o||s?{vx:-o,vy:-s}:null,this.edge&&this.kick()}updateMarquee(){const e=this.g;if(!e||e.kind!=="marquee")return;const n=Math.min(e.sx,e.px),a=Math.min(e.sy,e.py),i=Math.abs(e.px-e.sx),o=Math.abs(e.py-e.sy);Object.assign(this.marquee.style,{left:n+"px",top:a+"px",width:i+"px",height:o+"px"}),this.marquee.classList.remove("hidden");const s=this.toWorld(n,a),r={x:s.x,y:s.y,w:i/this.cam.z,h:o/this.cam.z};this.sel=new Set(e.base);for(const l of this.frames.values())for(const c of l.cards)dv(r,fl(l,c))&&this.sel.add(c.path);for(const l of this.cards.values())l.el&&l.el.classList.toggle("sel",this.sel.has(l.path));this.kick()}beginCardDrag(e,n,a){const i=e.card;this.sel.has(i.path)||(e.shift?this.sel.add(i.path):(this.sel.clear(),this.selFrames.clear(),this.sel.add(i.path)),this.paintSelection());const o=this.selectedCards().map(s=>{const r=this.frameOf(s);return s.drag=!0,{c:s,wx:r.x+s.x,wy:r.y+s.y,from:s.folder,fx:s.x,fy:s.y}});for(const s of o)s.c.el||(this.mountCard(s.c),this.placeCard(s.c)),s.c.el.classList.add("drag"),this.fg.appendChild(s.c.el);this.g={kind:"card-drag",cards:o,sx:e.sx,sy:e.sy,px:n,py:a,lead:i,drop:null},this.dragMove(n,a)}dragMove(e,n){const a=this.g;if(a){if(a.kind==="card-drag"){const i=this.toWorld(a.sx,a.sy),o=this.toWorld(e,n),s=o.x-i.x,r=o.y-i.y;for(const d of a.cards){const p=this.frameOf(d.c);d.c.x=d.wx+s-p.x,d.c.y=d.wy+r-p.y,this.placeCard(d.c,p)}const l=this.frameAt(o.x,o.y),c=l&&l.name!==a.lead.folder?l:null;c!==a.drop&&(a.drop?.el?.classList.remove("drop"),c?.el?.classList.add("drop"),a.drop=c);for(const d of this.frames.values())this.placeFrame(d);this.kick()}else if(a.kind==="frame-drag"){const i=this.toWorld(a.sx,a.sy),o=this.toWorld(e,n);for(const l of a.frames)l.f.x=l.x+o.x-i.x,l.f.y=l.y+o.y-i.y;const s=new Set(a.frames.map(l=>l.f)),r=a.frames.length===1&&a.frames[0].f.name!=="Root"?this.frameAt(o.x,o.y,s):null;r!==a.drop&&(a.drop?.el?.classList.remove("drop"),r?.el?.classList.add("drop"),a.drop=r),this.geomDirty=!0,this.kick()}}}revertDrag(e){if(e.drop?.el?.classList.remove("drop"),e.kind==="card-drag")for(const n of e.cards)n.c.drag=!1,n.c.x=n.fx,n.c.y=n.fy,n.c.el?.classList.remove("drag");else for(const n of e.frames)n.f.x=n.x,n.f.y=n.y;this.kick(!0)}async dropCards(e){e.drop?.el?.classList.remove("drop");const n=this.toWorld(e.px,e.py),a=this.frameAt(n.x,n.y),i=[],o=new Set;for(const p of e.cards)p.c.drag=!1,p.c.el?.classList.remove("drag"),a&&a.name!==p.c.folder?i.push(p):o.add(this.frameOf(p.c));for(const p of o)sd(p),this.separate(p);if(!i.length||!a){this.kick(!0),this.persist();return}const s=i.map(p=>{const h=this.frameOf(p.c),u=h.x+p.c.x,f=h.y+p.c.y;return{o:p,from:h,wx:u,wy:f,oldPath:p.c.path}});for(const p of s)p.from.cards=p.from.cards.filter(h=>h!==p.o.c),p.o.c.folder=a.name,p.o.c.x=p.wx-a.x,p.o.c.y=p.wy-a.y,a.cards.push(p.o.c),this.rekey(p.o.c,uv(p.oldPath,a.name)),p.o.c.el&&this.fillCard(p.o.c);sd(a),this.separate(a),this.kick(!0);const r=s.length===1?`"${s[0].o.c.name}"`:`${s.length} notes`;this.toast.show(`Moving ${r} to ${a.name}...`,{ms:2e4});const l=[];let c=0,d="";for(const p of s)try{const h=await RC(p.oldPath,a.name);this.rekey(p.o.c,h),l.push({c:p.o.c,from:p.o.from,oldPath:p.oldPath,fx:p.o.fx,fy:p.o.fy,frame:p.from})}catch(h){c++,d=h.message,a.cards=a.cards.filter(u=>u!==p.o.c),p.o.c.folder=p.o.from,p.o.c.x=p.o.fx,p.o.c.y=p.o.fy,this.rekey(p.o.c,p.oldPath),this.frames.has(p.o.from)||this.frames.set(p.o.from,p.from),p.from.cards.push(p.o.c),p.o.c.el&&this.fillCard(p.o.c)}if(this.kick(!0),this.persist(),l.length){const p=async()=>{for(const h of l)try{const u=await RC(h.c.path,h.from),f=this.frameOf(h.c);f&&(f.cards=f.cards.filter(v=>v!==h.c)),h.c.folder=h.from,h.c.x=h.fx,h.c.y=h.fy,this.rekey(h.c,u),this.frames.has(h.from)||(this.frames.set(h.from,h.frame),h.frame.el=null),this.frames.get(h.from).cards.push(h.c),h.c.el&&this.fillCard(h.c)}catch(u){this.toast.show("Undo failed: "+u.message,{err:!0})}this.kick(!0),this.persist(),await this.afterWrite()};this.pushUndo(`Move ${r}`,p),this.toast.show(`Moved ${l.length===1?`"${l[0].c.name}"`:l.length+" notes"} to ${a.name}${c?` · ${c} failed: ${d}`:""}`,{undo:()=>{this.runUndo()},err:c>0})}else this.toast.show(`Could not move: ${d}`,{err:!0});await this.afterWrite()}dropFrames(e){e.drop?.el?.classList.remove("drop");const n=e.drop;if(n&&e.frames.length===1){const a=e.frames[0].f;a.x=e.frames[0].x,a.y=e.frames[0].y,this.kick(!0),this.confirmFolderInto(a,n);return}for(const a of e.frames)this.separate(a.f);this.kick(!0),this.persist()}confirmFolderInto(e,n){const a=e.cards.length;ue.confirm("Move folder",`Move the folder "${e.name}" with its ${a} note${a===1?"":"s"} into "${n.name}"? The notes move on disk to ${n.name}/${e.name}/.`,"Move folder",async()=>{ue.close(),await this.moveFolderInto(e,n)},!1)}async moveFolderInto(e,n){const a=n.name==="Root"?e.name:n.name+"/"+e.name,i=e.cards.map(c=>c.path),o=new Map(e.cards.map(c=>[c.path,{x:c.x,y:c.y}])),s={x:e.x,y:e.y,w:e.w,h:e.h};this.toast.show(`Moving ${i.length} notes into ${n.name}...`,{ms:3e4}),this.busy=!0;const r=await kk(i,a);this.busy=!1;for(const c of r.moved){const d=this.cards.get(c.from);if(!d)continue;e.cards=e.cards.filter(h=>h!==d),d.folder=n.name;const p=uk(n);d.x=p.x,d.y=p.y,n.cards.push(d),this.rekey(d,c.to),this.flashPending.add(d.path),d.el&&this.fillCard(d)}this.kick(!0),this.persist();const l=async()=>{const c=await kk(r.moved.map(d=>this.cards.get(d.to)?.path||d.to),e.name);this.layout.frames[e.name]=s;for(const d of c.moved){const p=r.moved.find(f=>f.to===d.from),h=p&&o.get(p.from);h&&(this.layout.cards[d.to]=h);const u=this.cards.get(d.from);if(u){const f=this.frameOf(u);f&&(f.cards=f.cards.filter(v=>v!==u)),u.el?.remove(),this.cards.delete(d.from)}}await this.afterWrite()};this.pushUndo(`Move folder ${e.name}`,l),this.toast.show(`Moved ${r.moved.length} notes into ${n.name}/${e.name}${r.failed.length?` · ${r.failed.length} failed`:""}`,{undo:()=>{this.runUndo()},err:r.failed.length>0}),await this.afterWrite()}rekey(e,n){if(e.path===n)return;const a=e.path;this.cards.delete(a),e.path=n,this.cards.set(n,e),this.sel.delete(a)&&this.sel.add(n),this.hover===a&&(this.hover=n),GV(a,n),e.el&&(e.el.dataset.path=n),this.panel.path===a&&(this.panel.path=n)}async afterWrite(){try{await te.loadCore()}catch{}this.sync(),this.scheduleLinks()}pushUndo(e,n){this.undoStack.push({label:e,run:n}),this.undoStack.length>20&&this.undoStack.shift()}async runUndo(){const e=this.undoStack.pop();if(!e){this.toast.show("Nothing to undo");return}this.toast.show(`Undoing: ${e.label}...`);try{await e.run(),this.toast.show(`Undone: ${e.label}`)}catch(n){this.toast.show("Undo failed: "+n.message,{err:!0})}}inlineEdit(e,n,a){const i=document.createElement("input");i.value=n,i.spellcheck=!1,e.textContent="",e.appendChild(i),i.focus(),i.select();let o=!1;const s=r=>{if(o)return;o=!0;const l=i.value.trim();i.remove(),a(r&&l&&l!==n?l:"")};i.addEventListener("keydown",r=>{r.stopPropagation(),r.key==="Enter"?s(!0):r.key==="Escape"&&s(!1)}),i.addEventListener("blur",()=>s(!0)),i.addEventListener("pointerdown",r=>r.stopPropagation())}startRenameCard(e){e.el||(this.mountCard(e),this.placeCard(e));const n=e.el.querySelector(".cv-ctitle");n&&this.inlineEdit(n,e.name,a=>{if(!a){this.fillCard(e);return}this.renameCard(e,a)})}async renameCard(e,n){const a=e.path,i=e.name;e.name=n,this.rekey(e,CV(a,n)),this.fillCard(e);try{const o=await PC(a,n);this.rekey(e,o),this.pushUndo(`Rename "${i}"`,async()=>{const s=await PC(e.path,i);e.name=i,this.rekey(e,s),this.fillCard(e),await this.afterWrite()}),this.toast.show(`Renamed to "${n}"`,{undo:()=>{this.runUndo()}}),this.panel.path===e.path&&this.openPanel(e)}catch(o){e.name=i,this.rekey(e,a),this.fillCard(e),this.toast.show("Rename failed: "+o.message,{err:!0})}this.persist(),await this.afterWrite()}startRenameFrame(e){if(e.name==="Root"){this.toast.show("Root is the vault itself and cannot be renamed");return}const n=e.el?.querySelector(".cv-ftitle");n&&this.inlineEdit(n,e.name,a=>{if(!a){this.fillFrame(e);return}this.renameFrame(e,a)})}async renameFrame(e,n,a=!1){const i=LV(n),o=e.name;if(!i||i===o){this.fillFrame(e);return}if(N.tree[i]||this.frames.has(i)){this.fillFrame(e),this.toast.show(`A folder named "${i}" already exists`,{err:!0});return}const s=N.folderMeta[o]?.color;this.frames.delete(o),e.name=i,this.frames.set(i,e),e.el&&(e.el.dataset.frame=i),this.selFrames.delete(o)&&this.selFrames.add(i);const r=e.cards.map(c=>c.path);for(const c of e.cards)c.folder=i,this.rekey(c,uv(c.path,i));this.fillFrame(e),this.kick(!0),this.toast.show(`Renaming folder to ${i} (${r.length} notes)...`,{ms:3e4}),this.busy=!0;const l=await kk(r,i);this.busy=!1;for(const c of l.moved){const d=e.cards.find(p=>p.path===uv(c.from,i));d&&this.rekey(d,c.to)}if(s)try{await sj(i,s),N.folderMeta[i]={...N.folderMeta[i]||{},color:s}}catch{}l.failed.length?this.toast.show(`Renamed with ${l.failed.length} failures: ${l.failed[0].error}`,{err:!0}):a||(this.pushUndo(`Rename folder ${o}`,async()=>{const c=this.frames.get(i);c&&await this.renameFrame(c,o,!0)}),this.toast.show(`Folder renamed to ${i}`,{undo:()=>{this.runUndo()}})),this.persist(),await this.afterWrite()}recolorWhenModalCloses(){const e=document.getElementById("modalHost");if(!e)return;const n=new MutationObserver(()=>{!e.classList.contains("hidden")&&e.childElementCount||(n.disconnect(),this.recolor())});n.observe(e,{attributes:!0,childList:!0}),window.setTimeout(()=>n.disconnect(),12e4)}recolor(){for(const e of this.frames.values()){this.fillFrame(e);for(const n of e.cards)n.el&&n.el.style.setProperty("--fc",Yn(n.folder))}this.kick()}animate(e){const n=[];for(const o of this.frames.values()){n.push(o);for(const s of o.cards)n.push(s)}const a=n.map(o=>[o.x,o.y]);e();const i=[];n.forEach((o,s)=>{const[r,l]=a[s];(r!==o.x||l!==o.y)&&i.push({o,fx:r,fy:l,tx:o.x,ty:o.y})});for(const o of i)o.o.x=o.fx,o.o.y=o.fy;this.tween={t0:performance.now(),ms:380,items:i},this.kick(!0),window.setTimeout(()=>this.persist(),420)}async enter(){for(let e=0;e<40&&(!this.ready||!this.frames.size||this.W<50);e++)await new Promise(n=>setTimeout(n,75));!this.ready||!this.frames.size||(this.needFit=!1,this.animate(()=>{for(const n of this.frames.values())pv(n);const e=this.allBounds();hv(Array.from(this.frames.values()),e?e.x:0,e?e.y:0)}),await new Promise(e=>setTimeout(e,420)),this.fitTo(this.allBounds()))}tidy(e,n){const a=e&&e.length?e:Array.from(this.frames.values());this.animate(()=>{for(const i of a)pv(i);if(n){const i=this.allBounds();hv(Array.from(this.frames.values()),i?i.x:0,i?i.y:0)}}),this.toast.show(n?"Board tidied":`Tidied ${a.length} frame${a.length===1?"":"s"}`)}align(e){const n=this.selectedCards();if(n.length<2)return;const a=n.map(o=>fl(this.frameOf(o),o)),i=fk(a);this.animate(()=>{n.forEach(o=>{const s=this.frameOf(o);e==="l"&&(o.x=i.x-s.x),e==="r"&&(o.x=i.x+i.w-Sn-s.x),e==="c"&&(o.x=i.x+i.w/2-Sn/2-s.x),e==="t"&&(o.y=i.y-s.y),e==="b"&&(o.y=i.y+i.h-Dn-s.y),e==="m"&&(o.y=i.y+i.h/2-Dn/2-s.y)});for(const o of new Set(n.map(s=>this.frameOf(s))))sd(o)})}distribute(e){const n=this.selectedCards();if(n.length<3)return;const a=n.map(l=>{const c=this.frameOf(l);return{c:l,f:c,x:c.x+l.x,y:c.y+l.y}});a.sort((l,c)=>e==="h"?l.x-c.x:l.y-c.y);const i=a[0],o=a[a.length-1],r=(e==="h"?o.x-i.x:o.y-i.y)/(a.length-1);this.animate(()=>{a.forEach((l,c)=>{e==="h"?l.c.x=i.x+r*c-l.f.x:l.c.y=i.y+r*c-l.f.y});for(const l of new Set(a.map(c=>c.f)))sd(l)})}nudge(e,n){const a=this.selectedCards();if(a.length){for(const i of a)i.x+=e,i.y+=n;for(const i of new Set(a.map(o=>this.frameOf(o))))sd(i)}else for(const i of this.selFrames){const o=this.frames.get(i);o&&(o.x+=e,o.y+=n)}this.kick(!0),this.persist()}command(e){switch(e){case"tool-select":case"tool-hand":this.tool=e==="tool-hand"?"hand":"select",this.root.classList.toggle("hand",this.tool==="hand"),this.syncButtons();break;case"zoom-in":this.zoomAt(1.25,this.W/2,this.H/2);break;case"zoom-out":this.zoomAt(.8,this.W/2,this.H/2);break;case"zoom-100":this.zoomTo(1);break;case"fit":this.fitTo(this.allBounds());break;case"sel-open":{const n=this.selectedCards()[0];n&&(this.reveal(n,!1),this.openPanel(n));break}case"fit-sel":this.fitTo(this.selectionBounds()||this.allBounds());break;case"tidy":{const n=new Set;for(const a of this.selectedCards())n.add(this.frameOf(a));for(const a of this.selFrames){const i=this.frames.get(a);i&&n.add(i)}this.tidy(n.size?Array.from(n):null,!n.size);break}case"links":this.showLinks=!this.showLinks,this.syncButtons(),this.persist(),this.kick();break;case"minimap":this.vc.toggleMinimap(),this.persist();break;case"help":this.toggleHelp();break;case"al-l":case"al-c":case"al-r":case"al-t":case"al-m":case"al-b":this.align(e.slice(3));break;case"dis-h":case"dis-v":this.distribute(e.slice(4));break}}syncButtons(){const e=this.ui.tools;e.querySelector("[data-act=tool-select]")?.classList.toggle("on",this.tool==="select"),e.querySelector("[data-act=tool-hand]")?.classList.toggle("on",this.tool==="hand"),e.querySelector("[data-act=links]")?.classList.toggle("on",this.showLinks)}toggleHelp(e){const n=e??this.ui.help.classList.contains("hidden");this.ui.help.classList.toggle("hidden",!n),this.ui.scrim.classList.toggle("hidden",!n)}async openPanel(e){this.vc.close(),this.root.classList.add("panel-open");const n=N.graph.nodes.find(a=>a.path===e.path);this.panel.showNote(e.path,e.name,e.folder,Yn(e.folder),Array.isArray(n?.tags)?n.tags.map(String):[])}openFolderCard(e){this.vc.close(),this.root.classList.add("panel-open"),this.panel.showFolder(e,Yn(e),this.frames.get(e)?.cards.length)}closePanel(){this.panel.close(),this.root.classList.remove("panel-open")}buildCard(e){const n=a=>({path:a.path,name:a.name,color:Yn(a.folder),degree:this.linkCount.get(a.path)||0});return new ng({root:e,focusNode:a=>{const i=this.cards.get(a);i&&this.reveal(i,!0)},focusFolder:a=>this.focusFolder(a),onlyFolder:a=>this.setHiddenFrames(Array.from(this.frames.keys()).filter(i=>i!==a)),pick:a=>{const i=this.cards.get(a);i&&(this.select([i.path]),this.reveal(i,!0),this.openPanel(i))},links:a=>{const i=this.links.filter(s=>s.a.path===a).map(s=>n(s.b)),o=new Set(i.map(s=>s.path));return{out:i,in:this.links.filter(s=>s.b.path===a&&!o.has(s.a.path)).map(s=>n(s.a))}},folderItems:a=>Array.from(this.cards.values()).filter(i=>i.folder===a).map(n).sort((i,o)=>(o.degree||0)-(i.degree||0)),tag:a=>this.vc.setQuery("#"+a+" "),home:()=>window.setTimeout(()=>this.fitTo(this.allBounds()),60),closed:()=>this.root.classList.remove("panel-open")})}onKey(e){if(N.page!=="canvas")return;const n=e.target,a=n?.tagName;if(a==="INPUT"||a==="TEXTAREA"||a==="SELECT"||n?.isContentEditable||document.querySelector("#modalHost:not(.hidden)"))return;const i=e.ctrlKey||e.metaKey,o=e.key,s=e.code;if(s==="Space"){this.space||(this.space=!0,this.root.classList.add("hand")),e.preventDefault();return}if(o==="Escape"){this.ui.help.classList.contains("hidden")?this.g?this.cancelGesture():this.sel.size||this.selFrames.size?this.select([]):this.panel.isOpen&&this.closePanel():this.toggleHelp(!1);return}if(i&&(o==="z"||o==="Z")&&!e.shiftKey){e.preventDefault(),this.runUndo();return}if(i&&(o==="a"||o==="A")){e.preventDefault(),this.select(Array.from(this.cards.keys()));return}if(i)return;if(e.altKey){const l={KeyA:"al-l",KeyD:"al-r",KeyW:"al-t",KeyS:"al-b",KeyH:e.shiftKey?"dis-h":"al-c",KeyV:e.shiftKey?"dis-v":"al-m"};l[s]&&(e.preventDefault(),this.command(l[s]));return}if(e.shiftKey&&(s==="Digit1"||s==="Digit2"||s==="Digit0")){e.preventDefault(),this.command(s==="Digit1"?"fit":s==="Digit2"?"fit-sel":"zoom-100");return}if(o.startsWith("Arrow")){if(!this.sel.size&&!this.selFrames.size)return;e.preventDefault();const l=e.shiftKey?10:1;this.nudge(o==="ArrowLeft"?-l:o==="ArrowRight"?l:0,o==="ArrowUp"?-l:o==="ArrowDown"?l:0);return}const r=this.sel.size===1?this.cards.get(Array.from(this.sel)[0]):void 0;switch(o){case"v":case"V":this.command("tool-select");break;case"h":case"H":this.command("tool-hand");break;case"+":case"=":this.command("zoom-in");break;case"-":case"_":this.command("zoom-out");break;case"t":this.command("tidy");break;case"T":this.tidy(null,!0);break;case"l":case"L":this.command("links");break;case"m":case"M":this.command("minimap");break;case"?":this.toggleHelp();break;case"/":e.preventDefault(),this.vc.focusSearch();break;case"Enter":r&&(e.preventDefault(),this.openPanel(r));break;case"o":case"O":r&&te.openNote(r.path);break;case"F2":if(e.preventDefault(),r)this.startRenameCard(r);else if(this.selFrames.size===1){const l=this.frames.get(Array.from(this.selFrames)[0]);l&&this.startRenameFrame(l)}break;default:return}}findCard(e){if(!e)return;const n=e.replace(/^\/+/,""),a=this.cards.get(n)||this.cards.get(n+".md");if(a)return a;const i=dn(n);for(const o of this.cards.values())if(o.name===i)return o}onActivity(e){const n=e.paths||[],a=e.phase==="start";let i;for(const o of n){const s=this.findCard(o);s&&(s.touch={actor:e.actor,label:e.label||e.action,at:Date.now(),live:a},s.el&&this.fillCard(s),i=s)}i&&this.moveCursor(e.actor,i,e.label||e.action)}moveCursor(e,n,a){const i=this.frameOf(n);if(!i)return;let o=this.cursors.get(e);if(!o){const l=document.createElement("div");l.className="cv-cursor",l.style.setProperty("--ac",An(e)),l.style.opacity="0",this.fg.appendChild(l),o={el:l,timer:0},this.cursors.set(e,o);const c=fl(i,n);l.style.transform=`translate(${c.x+c.w+40}px,${c.y-40}px)`,l.offsetWidth}o.el.innerHTML=`<div class="cv-cursor-in">${nj}<b>${x(e)}<small>${x(a)}</small></b></div>`;const s=fl(i,n);o.el.style.opacity="1",o.el.style.transform=`translate(${s.x+s.w-34}px,${s.y+s.h-30}px)`,this.fg.appendChild(o.el),clearTimeout(o.timer);const r=o;o.timer=window.setTimeout(()=>{r.el.style.opacity="0",window.setTimeout(()=>{r.el.style.opacity==="0"&&(r.el.remove(),this.cursors.delete(e))},500)},9e3)}decayTouches(){const e=Date.now();for(const n of this.cards.values())n.touch&&(n.touch.live&&e-n.touch.at>6e4&&(n.touch.live=!1),e-n.touch.at>Mk&&(n.touch=null),n.el&&this.fillCard(n))}onMutation(e){const n=e.node||{},a=String(n.path||e.path||""),i=String(e.old_path||"");if(e.type==="node_renamed"&&i&&a){const s=this.cards.get(i);s&&this.rekey(s,a)}if(a){WV(a),this.flashPending.add(a);const s=this.cards.get(a);s&&(e.actor&&(s.touch={actor:String(e.actor),label:String(e.type).replace("node_",""),at:Date.now(),live:!1}),s.el&&this.fillCard(s))}if(this.busy)return;const o=N.tree;clearTimeout(this.syncTimer),this.syncTimer=window.setTimeout(()=>{N.tree===o?this.afterWrite():(this.sync(),this.scheduleLinks())},900)}}function pj(t,e){let n=!t.classList.contains("hidden");new MutationObserver(()=>{const a=!t.classList.contains("hidden");a!==n&&(n=a,e(a))}).observe(t,{attributes:!0,attributeFilter:["class"]})}const DC="memora.canvas.hiddenFrames";function hj(){try{const t=JSON.parse(localStorage.getItem(DC)||"[]");return new Set(Array.isArray(t)?t.map(String):[])}catch{return new Set}}function uj(t){try{localStorage.setItem(DC,JSON.stringify(Array.from(t)))}catch{}}const OC="memora.canvas.labels";function fj(){try{const t=JSON.parse(localStorage.getItem(OC)||"{}");return{nodes:t.nodes!==!1,folders:t.folders!==!1}}catch{return{nodes:!0,folders:!0}}}function $C(t){try{localStorage.setItem(OC,JSON.stringify(t))}catch{}}const mj=`
|
|
11891
|
+
<button class="cv-copen" title="Preview (Enter)" aria-label="Preview">${On.open}</button>`}placeCard(e,n=this.frameOf(e)){!e.el||!n||(e.el.style.transform=`translate(${n.x+e.x}px,${n.y+e.y}px)`)}flash(e){this.flashPending.delete(e.path),e.el&&(e.el.classList.remove("flash"),e.el.offsetWidth,e.el.classList.add("flash"))}drawLinks(){const e=this.hover||this.sel.size?new Set(this.sel):null;e&&this.hover&&e.add(this.hover),OV(this.ctx,{cam:this.cam,w:this.W,h:this.H,dpr:this.dpr,links:this.hiddenFrames.size?this.links.filter(a=>!this.hiddenFrames.has(a.a.folder)&&!this.hiddenFrames.has(a.b.folder)):this.links,showLinks:this.showLinks,focus:e,paintCards:this.lod===2,frames:this.shownFrames(),frameOf:this.frameOf,color:Yn,selected:this.sel,light:document.documentElement.dataset.theme==="light"})&&this.kick()}paintMini(e,n,a,i){const o=e.getContext("2d");o&&(this.miniMap=$V(o,{w:n,h:a,dpr:i,frames:this.shownFrames(),color:Yn,view:this.viewBox(),light:document.documentElement.dataset.theme==="light"}))}applyLabelPrefs(){this.root.classList.toggle("no-node-text",!this.labelPrefs.nodes),this.root.classList.toggle("no-folder-titles",!this.labelPrefs.folders)}focusFolder(e){const n=this.frames.get(e);if(n){if(this.hiddenFrames.has(e)){const a=new Set(this.hiddenFrames);a.delete(e),this.setHiddenFrames(a),this.vc.refreshRegions()}this.fitTo(La(n)),this.flashFrame(n)}}flashFrame(e){window.setTimeout(()=>{const n=e.el;n&&(n.classList.remove("flash"),n.offsetWidth,n.classList.add("flash"),window.setTimeout(()=>n.classList.remove("flash"),1700))},250)}shownFrames(){const e=Array.from(this.frames.values());return this.hiddenFrames.size?e.filter(n=>!this.hiddenFrames.has(n.name)):e}setHiddenFrames(e){this.hiddenFrames=new Set(e),uj(this.hiddenFrames);for(const n of Array.from(this.sel))this.hiddenFrames.has(this.cards.get(n)?.folder||"")&&this.sel.delete(n);this.paintSelection(),this.geomDirty=!0,this.kick(!0),requestAnimationFrame(()=>this.vc.redrawMini())}buildViewChrome(e){const n=(a,i)=>{const o=this.cam.z,s=[(this.W/2-this.cam.x)/o,(this.H/2-this.cam.y)/o,o];this.zoomAnim=null,this.inertia=null,this.fly={t0:performance.now(),ms:200,c0:s,c1:[s[0]+a*this.W*.16/o,s[1]+i*this.H*.16/o,o]},this.kick(),this.saveCamSoon()};return new lw({page:"canvas",root:e,search:{placeholder:"Find a note, #tag or in:folder",find:{items:()=>{const a=new Map(N.graph.nodes.map(i=>[i.path||i.id,i]));return Array.from(this.cards.values()).map(i=>{const o=a.get(i.path);return{id:i.path,name:i.name,folder:i.folder,region:i.folder,color:Yn(i.folder),tags:Array.isArray(o?.tags)?o.tags.map(String):[],degree:o?.degree||0}})},hidden:a=>this.hiddenFrames.has(a),highlight:a=>this.lightCards(a),pick:a=>{const i=this.cards.get(a.id);i&&(this.reveal(i,!0),this.openPanel(i))},folder:a=>{this.focusFolder(a),this.openFolderCard(a)}}},changed:()=>!this.labelPrefs.nodes||!this.labelPrefs.folders||!this.showLinks||this.hiddenFrames.size>0||!!this.hits||!!this.panel?.isOpen||this.sel.size>0||this.selFrames.size>0,labels:{get:()=>({nodes:this.labelPrefs.nodes,folders:this.labelPrefs.folders}),set:(a,i)=>{this.labelPrefs[a]=i,$C(this.labelPrefs),this.applyLabelPrefs()},help:{nodes:"The preview text, tags and footer on each card. Titles always stay.",folders:"The name and count over each folder frame."}},filter:a=>this.renderFilter(a),reset:()=>{this.labelPrefs={nodes:!0,folders:!0},$C(this.labelPrefs),this.applyLabelPrefs(),this.showLinks=!0,this.syncButtons(),this.persist(),this.vc.finder?.clear(),this.closePanel(),this.setHiddenFrames([]),this.select([]),this.selFrames.clear(),this.paintSelection(),this.animate(()=>{for(const a of this.frames.values())pv(a);hv(Array.from(this.frames.values()),0,0)}),window.setTimeout(()=>this.fitTo(this.allBounds()),420)},regions:{list:()=>Array.from(this.frames.values()).sort((a,i)=>i.cards.length-a.cards.length||a.name.localeCompare(i.name)).map(a=>({name:a.name,color:Yn(a.name),count:a.cards.length,hidden:this.hiddenFrames.has(a.name)})),toggle:a=>{const i=new Set(this.hiddenFrames);i.has(a)?i.delete(a):i.add(a),this.setHiddenFrames(i)},setAll:a=>this.setHiddenFrames(a?Array.from(this.frames.keys()):[]),focus:a=>{const i=this.frames.get(a);i&&(this.fitTo(La(i)),this.flashFrame(i),this.openFolderCard(a))}},nav:{zoom:a=>this.zoomAt(a,this.W/2,this.H/2),fit:()=>this.fitTo(this.allBounds()),nudge:n,home:()=>this.fitTo(this.allBounds())},minimap:(a,i,o,s)=>this.paintMini(a,i,o,s),minimapNav:(a,i)=>{const o=this.vc.miniCanvas.getBoundingClientRect(),s=this.miniMap,r=(a*o.width-s.ox)/s.s,l=(i*o.height-s.oy)/s.s;this.stopAnims(),this.cam.x=this.W/2-r*this.cam.z,this.cam.y=this.H/2-l*this.cam.z,this.kick(!0),this.saveCamSoon()},onPrefs:()=>this.kick(),onOverlay:()=>this.closePanel()})}lightCards(e){this.hits=e,this.root.classList.toggle("searching",!!this.hits);for(const n of this.cards.values())n.el&&this.markHit(n)}markHit(e){const n=!!this.hits&&this.hits.has(e.path);e.el?.classList.toggle("hit",n)}renderFilter(e){e.innerHTML="<h4>Canvas</h4>"+po("links","Link lines",this.showLinks,"Lines between cards for every link from one note to another, routed around cards and frames.")+'<button type="button" class="vc-act" data-tidy title="Lay every folder frame out in a neat grid">Tidy the whole board</button><div class="vc-hint">V select · H or Space pan · T tidy · L wires · M minimap · ? all shortcuts</div>',e.querySelector("[data-t=links]").onclick=()=>{this.command("links"),this.vc.renderPanel()},e.querySelector("[data-tidy]").onclick=()=>this.tidy(null,!0)}stopAnims(){this.fly=null,this.inertia=null,this.zoomAnim=null}zoomAt(e,n,a){this.fly=null,this.inertia=null;const i=this.zoomAnim?this.zoomAnim.zt:this.cam.z,o=Math.max(Sk,Math.min(IC,i*e));this.zoomAnim={zt:o,ax:n,ay:a},this.kick()}zoomTo(e){this.zoomAnim=null,this.zoomAt(e/this.cam.z,this.W/2,this.H/2)}allBounds(){return fk(this.shownFrames().map(e=>La(e)))}selectionBounds(){const e=[];for(const n of this.sel){const a=this.cards.get(n),i=a&&this.frameOf(a);a&&i&&e.push(fl(i,a))}for(const n of this.selFrames){const a=this.frames.get(n);a&&e.push(La(a))}return fk(e)}fitTo(e,n=!0,a=1.25){if(!e)return;const i=this.panel&&this.panel.isOpen&&this.W>760?400:0,o=this.W<600?28:80,s=this.W-i,r=Math.max(Sk,Math.min(a,(s-o*2)/e.w,(this.H-o*2-40)/(e.h+40))),l=e.x+e.w/2,c=e.y+e.h/2-12/r,d=[l+i/2/r,c,r];if(!n){this.cam={z:r,x:this.W/2-d[0]*r,y:this.H/2-d[1]*r},this.kick(!0);return}const p=[(this.W/2-this.cam.x)/this.cam.z,(this.H/2-this.cam.y)/this.cam.z,this.cam.z];this.zoomAnim=null,this.inertia=null,this.fly={t0:performance.now(),ms:420,c0:p,c1:d},this.kick()}reveal(e,n){const a=this.frameOf(e);if(!a)return;const i=fl(a,e),o=this.viewBox(-60);!n&&hk(o,i.x,i.y)&&hk(o,i.x+i.w,i.y+i.h)&&this.cam.z>=zC||this.fitTo({x:i.x-160,y:i.y-120,w:i.w+320,h:i.h+240},!0,Math.max(this.cam.z,1))}select(e,n=!1){n||(this.sel.clear(),this.selFrames.clear());for(const a of e)this.sel.add(a);this.paintSelection()}paintSelection(){for(const r of this.cards.values())r.el&&r.el.classList.toggle("sel",this.sel.has(r.path));for(const r of this.frames.values())r.el?.classList.toggle("sel",this.selFrames.has(r.name));const e=this.sel.size,n=e>=1||this.selFrames.size>0;this.ui.selbar.classList.toggle("hidden",!n),this.root.classList.toggle("has-sel",n);const a=this.ui.selbar.querySelector(".cnt");a.textContent=e?`${e} note${e===1?"":"s"}`:`${this.selFrames.size} folder${this.selFrames.size===1?"":"s"}`,this.ui.selbar.querySelectorAll("[data-act^=al-],[data-act^=dis-]").forEach(r=>{r.classList.toggle("hidden",r.dataset.act.startsWith("dis-")?e<3:e<2)}),this.ui.selbar.querySelectorAll(".cv-sep").forEach((r,l)=>r.classList.toggle("hidden",l<2&&e<2)),this.ui.selbar.querySelector("[data-act=sel-open]")?.classList.toggle("hidden",e!==1);const i=new Map;for(const r of this.sel){const l=this.cards.get(r);l&&i.set(l.folder,(i.get(l.folder)||0)+1)}for(const r of this.selFrames)i.set(r,i.get(r)||0);const o=Array.from(i.keys()),s=this.ui.selbar.querySelector(".cv-fchips");if(s.innerHTML=o.slice(0,3).map(r=>`<button class="cv-btn cv-fchip" data-fchip="${x(r)}" title="Focus folder ${x(r)}"><i class="cv-fdot" style="--fc:${x(Yn(r))}"></i><span>${x(r==="Root"?"Vault":r.split("/").pop()||r)}</span></button>`).join("")+(o.length>3?`<span class="cv-fmore">+${o.length-3}</span>`:""),this.panel.isOpen&&e===1){const r=this.cards.get(Array.from(this.sel)[0]);r&&this.panel.path!==r.path&&this.openPanel(r)}this.kick()}selectedCards(){return Array.from(this.sel).map(e=>this.cards.get(e)).filter(e=>!!e)}pt(e){const n=this.root.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}toWorld(e,n){return{x:(e-this.cam.x)/this.cam.z,y:(n-this.cam.y)/this.cam.z}}frameAt(e,n,a){let i=null;for(const o of this.frames.values()){if(a&&a.has(o)||this.hiddenFrames.has(o.name))continue;const s=La(o);hk(s,e,n)&&(i=o)}return i}onDown(e){const n=e.target;if(n.closest(".cv-ui")||n.closest("input"))return;if(n.closest(".cv-copen")){const p=n.closest(".cv-card"),h=p&&this.cards.get(p.dataset.path||"");h&&(e.stopPropagation(),this.select([h.path]),this.openPanel(h));return}const a=n.closest(".cv-fbtn");if(a){const p=a.closest(".cv-frame"),h=p&&this.frames.get(p.dataset.frame||"");h&&(a.dataset.fact==="tidy"?this.tidy([h],!1):(te.openFolderColor(h.name),this.recolorWhenModalCloses()));return}const i=this.pt(e);if(this.pointers.set(e.pointerId,{x:i.x,y:i.y,type:e.pointerType}),e.pointerType!=="mouse"&&this.capture(e.pointerId),this.lastPointer=e.pointerId,this.inertia=null,this.fly=null,this.pointers.size===2){this.cancelGesture();const[p,h]=Array.from(this.pointers.values());this.g={kind:"pinch",d0:Math.hypot(p.x-h.x,p.y-h.y)||1,z0:this.cam.z,cx:(p.x+h.x)/2,cy:(p.y+h.y)/2};return}if(this.pointers.size>2)return;const o=n.closest(".cv-card"),s=n.closest(".cv-flabel"),r=n.closest(".cv-fresize"),l=n.closest(".cv-frame"),c=e.pointerType!=="mouse",d=e.button===1||this.space||this.tool==="hand"||c&&!o&&!s&&!r;if(e.button!==2){if(d){e.preventDefault(),this.g={kind:"pan",lx:i.x,ly:i.y,samples:[{x:i.x,y:i.y,t:performance.now()}]},this.root.classList.add("panning");return}if(r&&l){const p=this.frames.get(l.dataset.frame||"");if(p){const h=La(p);this.g={kind:"resize",frame:p,sx:i.x,sy:i.y,w:h.w,h:h.h}}return}if(s&&l){const p=this.frames.get(l.dataset.frame||"");if(!p)return;e.shiftKey?(this.selFrames.has(p.name)?this.selFrames.delete(p.name):this.selFrames.add(p.name),this.paintSelection()):this.selFrames.has(p.name)||(this.sel.clear(),this.selFrames.clear(),this.selFrames.add(p.name),this.paintSelection()),this.g={kind:"frame-pending",frame:p,sx:i.x,sy:i.y};return}if(o){const p=this.cards.get(o.dataset.path||"");if(!p)return;const h={kind:"card-pending",card:p,sx:i.x,sy:i.y,shift:e.shiftKey,touch:c,timer:0};c&&(h.timer=window.setTimeout(()=>{if(this.g===h){try{navigator.vibrate?.(12)}catch{}this.beginCardDrag(h,h.sx,h.sy)}},cj)),this.g=h;return}if(l&&!c){const p=this.frames.get(l.dataset.frame||"");if(p&&this.selFrames.has(p.name)&&!e.shiftKey){this.g={kind:"frame-pending",frame:p,sx:i.x,sy:i.y};return}}this.g={kind:"marquee-pending",sx:i.x,sy:i.y,shift:e.shiftKey}}}onMove(e){const n=this.pt(e),a=this.pointers.get(e.pointerId);a&&(a.x=n.x,a.y=n.y);const i=this.g;if(i&&a&&e.pointerType==="mouse"&&i.kind!=="card-pending"&&i.kind!=="marquee-pending"&&i.kind!=="frame-pending"&&this.capture(e.pointerId),!i){if(e.pointerType==="mouse"){const o=e.target.closest(".cv-card"),s=o&&o.dataset.path||null;s!==this.hover&&(this.hover=s,this.kick())}return}if(a)switch(i.kind){case"pinch":{const o=Array.from(this.pointers.values());if(o.length<2)return;const[s,r]=o,l=Math.hypot(s.x-r.x,s.y-r.y)||1,c=(s.x+r.x)/2,d=(s.y+r.y)/2,p=Math.max(Sk,Math.min(IC,i.z0*l/i.d0)),h=(i.cx-this.cam.x)/this.cam.z,u=(i.cy-this.cam.y)/this.cam.z;this.cam.z=p,this.cam.x=c-h*p,this.cam.y=d-u*p,i.cx=c,i.cy=d,this.kick();return}case"pan":{i.d=(i.d||0)+Math.abs(n.x-i.lx)+Math.abs(n.y-i.ly),this.cam.x+=n.x-i.lx,this.cam.y+=n.y-i.ly,i.lx=n.x,i.ly=n.y;const o=performance.now();for(i.samples.push({x:n.x,y:n.y,t:o});i.samples.length>2&&o-i.samples[0].t>90;)i.samples.shift();this.kick();return}case"card-pending":{const o=Math.hypot(n.x-i.sx,n.y-i.sy);if(i.touch){o>8&&(clearTimeout(i.timer),this.g={kind:"pan",lx:n.x,ly:n.y,samples:[{x:n.x,y:n.y,t:performance.now()}]},this.cam.x+=n.x-i.sx,this.cam.y+=n.y-i.sy,this.kick());return}o>3&&this.beginCardDrag(i,n.x,n.y);return}case"card-drag":case"frame-drag":i.px=n.x,i.py=n.y,this.edgeScroll(n.x,n.y),this.dragMove(n.x,n.y);return;case"marquee-pending":Math.hypot(n.x-i.sx,n.y-i.sy)>3&&(this.g={kind:"marquee",sx:i.sx,sy:i.sy,px:n.x,py:n.y,base:i.shift?new Set(this.sel):new Set},i.shift||this.selFrames.clear(),this.updateMarquee());return;case"marquee":i.px=n.x,i.py=n.y,this.updateMarquee();return;case"frame-pending":if(Math.hypot(n.x-i.sx,n.y-i.sy)>3){const s=(this.selFrames.has(i.frame.name)?Array.from(this.selFrames):[i.frame.name]).map(r=>this.frames.get(r)).filter(r=>!!r).map(r=>({f:r,x:r.x,y:r.y}));this.g={kind:"frame-drag",frames:s,sx:i.sx,sy:i.sy,px:n.x,py:n.y,drop:null};for(const r of s)r.f.el&&this.bg.appendChild(r.f.el);this.dragMove(n.x,n.y)}return;case"resize":{const o=i.frame,s=pk(o);o.w=Math.max(s.w,i.w+(n.x-i.sx)/this.cam.z),o.h=Math.max(s.h,i.h+(n.y-i.sy)/this.cam.z),this.placeFrame(o),this.kick();return}default:return}}onUp(e,n=!1){const a=this.pointers.delete(e.pointerId),i=this.g;if(this.root.classList.remove("panning"),this.edge=null,!(!i||!a)){if(i.kind==="pinch"){if(this.pointers.size<2){this.g=null;const o=Array.from(this.pointers.values())[0];o&&(this.g={kind:"pan",lx:o.x,ly:o.y,samples:[]}),this.saveCamSoon()}return}if(this.g=null,n){(i.kind==="card-drag"||i.kind==="frame-drag")&&this.revertDrag(i),this.marquee.classList.add("hidden");return}switch(i.kind){case"pan":{(i.d||0)<6&&e.pointerType!=="mouse"&&!e.target.closest(".cv-card,.cv-flabel")&&(this.sel.size||this.selFrames.size?this.select([]):this.panel.isOpen&&this.closePanel());const o=i.samples;if(o.length>=2){const s=o[0],r=o[o.length-1],l=Math.max(1,r.t-s.t);performance.now()-r.t<60&&l>4&&(this.inertia={vx:(r.x-s.x)/l,vy:(r.y-s.y)/l,t:performance.now()},Math.hypot(this.inertia.vx,this.inertia.vy)<.08&&(this.inertia=null))}this.kick(),this.saveCamSoon();return}case"card-pending":{clearTimeout(i.timer);const o=i.card;if(i.touch){this.select([o.path]),this.openPanel(o);return}i.shift?(this.sel.has(o.path)?this.sel.delete(o.path):this.sel.add(o.path),this.paintSelection()):this.select([o.path]);return}case"card-drag":this.dropCards(i);return;case"frame-drag":this.dropFrames(i);return;case"frame-pending":this.openFolderCard(i.frame.name);return;case"marquee":this.marquee.classList.add("hidden"),this.paintSelection();return;case"marquee-pending":i.shift||this.select([]);return;case"resize":this.separate(i.frame),this.persist();return;default:return}}}capture(e=this.lastPointer){try{this.root.hasPointerCapture(e)||this.root.setPointerCapture(e)}catch{}}cancelGesture(){const e=this.g;e&&(e.kind==="card-pending"&&clearTimeout(e.timer),(e.kind==="card-drag"||e.kind==="frame-drag")&&this.revertDrag(e),this.marquee.classList.add("hidden"),this.root.classList.remove("panning"),this.g=null)}onWheel(e){if(e.target.closest(".nc,.cv-help"))return;e.preventDefault();const n=this.pt(e),a=e.deltaMode===1,i=a?e.deltaY*16:e.deltaY,o=a?e.deltaX*16:e.deltaX;if(e.ctrlKey||e.metaKey){this.zoomAt(Math.exp(-Math.max(-50,Math.min(50,i))*.0085),n.x,n.y);return}if((a||o===0&&Math.abs(i)>=40&&Number.isInteger(i))&&!e.shiftKey){this.zoomAt(Math.exp(-Math.max(-120,Math.min(120,i))*.0021),n.x,n.y);return}this.stopAnims(),e.shiftKey&&o===0?this.cam.x-=i:(this.cam.x-=o,this.cam.y-=i),this.kick(),this.saveCamSoon()}onDbl(e){let n=e.target;if(n===this.root&&(n=document.elementFromPoint(e.clientX,e.clientY)||n),n.closest(".cv-ui")||n.closest("input"))return;const a=n.closest(".cv-flabel");if(a){const o=a.closest(".cv-frame"),s=o&&this.frames.get(o.dataset.frame||"");s&&this.startRenameFrame(s);return}const i=n.closest(".cv-card");if(i){const o=this.cards.get(i.dataset.path||"");if(!o)return;n.closest(".cv-ctitle")?this.startRenameCard(o):this.openPanel(o);return}if(!n.closest(".cv-frame")){const o=this.pt(e);this.zoomAt(1.6,o.x,o.y)}}edgeScroll(e,n){const o=e<36?-9:e>this.W-36?9:0,s=n<36?-9:n>this.H-36?9:0;this.edge=o||s?{vx:-o,vy:-s}:null,this.edge&&this.kick()}updateMarquee(){const e=this.g;if(!e||e.kind!=="marquee")return;const n=Math.min(e.sx,e.px),a=Math.min(e.sy,e.py),i=Math.abs(e.px-e.sx),o=Math.abs(e.py-e.sy);Object.assign(this.marquee.style,{left:n+"px",top:a+"px",width:i+"px",height:o+"px"}),this.marquee.classList.remove("hidden");const s=this.toWorld(n,a),r={x:s.x,y:s.y,w:i/this.cam.z,h:o/this.cam.z};this.sel=new Set(e.base);for(const l of this.frames.values())for(const c of l.cards)dv(r,fl(l,c))&&this.sel.add(c.path);for(const l of this.cards.values())l.el&&l.el.classList.toggle("sel",this.sel.has(l.path));this.kick()}beginCardDrag(e,n,a){const i=e.card;this.sel.has(i.path)||(e.shift?this.sel.add(i.path):(this.sel.clear(),this.selFrames.clear(),this.sel.add(i.path)),this.paintSelection());const o=this.selectedCards().map(s=>{const r=this.frameOf(s);return s.drag=!0,{c:s,wx:r.x+s.x,wy:r.y+s.y,from:s.folder,fx:s.x,fy:s.y}});for(const s of o)s.c.el||(this.mountCard(s.c),this.placeCard(s.c)),s.c.el.classList.add("drag"),this.fg.appendChild(s.c.el);this.g={kind:"card-drag",cards:o,sx:e.sx,sy:e.sy,px:n,py:a,lead:i,drop:null},this.dragMove(n,a)}dragMove(e,n){const a=this.g;if(a){if(a.kind==="card-drag"){const i=this.toWorld(a.sx,a.sy),o=this.toWorld(e,n),s=o.x-i.x,r=o.y-i.y;for(const d of a.cards){const p=this.frameOf(d.c);d.c.x=d.wx+s-p.x,d.c.y=d.wy+r-p.y,this.placeCard(d.c,p)}const l=this.frameAt(o.x,o.y),c=l&&l.name!==a.lead.folder?l:null;c!==a.drop&&(a.drop?.el?.classList.remove("drop"),c?.el?.classList.add("drop"),a.drop=c);for(const d of this.frames.values())this.placeFrame(d);this.kick()}else if(a.kind==="frame-drag"){const i=this.toWorld(a.sx,a.sy),o=this.toWorld(e,n);for(const l of a.frames)l.f.x=l.x+o.x-i.x,l.f.y=l.y+o.y-i.y;const s=new Set(a.frames.map(l=>l.f)),r=a.frames.length===1&&a.frames[0].f.name!=="Root"?this.frameAt(o.x,o.y,s):null;r!==a.drop&&(a.drop?.el?.classList.remove("drop"),r?.el?.classList.add("drop"),a.drop=r),this.geomDirty=!0,this.kick()}}}revertDrag(e){if(e.drop?.el?.classList.remove("drop"),e.kind==="card-drag")for(const n of e.cards)n.c.drag=!1,n.c.x=n.fx,n.c.y=n.fy,n.c.el?.classList.remove("drag");else for(const n of e.frames)n.f.x=n.x,n.f.y=n.y;this.kick(!0)}async dropCards(e){e.drop?.el?.classList.remove("drop");const n=this.toWorld(e.px,e.py),a=this.frameAt(n.x,n.y),i=[],o=new Set;for(const p of e.cards)p.c.drag=!1,p.c.el?.classList.remove("drag"),a&&a.name!==p.c.folder?i.push(p):o.add(this.frameOf(p.c));for(const p of o)sd(p),this.separate(p);if(!i.length||!a){this.kick(!0),this.persist();return}const s=i.map(p=>{const h=this.frameOf(p.c),u=h.x+p.c.x,f=h.y+p.c.y;return{o:p,from:h,wx:u,wy:f,oldPath:p.c.path}});for(const p of s)p.from.cards=p.from.cards.filter(h=>h!==p.o.c),p.o.c.folder=a.name,p.o.c.x=p.wx-a.x,p.o.c.y=p.wy-a.y,a.cards.push(p.o.c),this.rekey(p.o.c,uv(p.oldPath,a.name)),p.o.c.el&&this.fillCard(p.o.c);sd(a),this.separate(a),this.kick(!0);const r=s.length===1?`"${s[0].o.c.name}"`:`${s.length} notes`;this.toast.show(`Moving ${r} to ${a.name}...`,{ms:2e4});const l=[];let c=0,d="";for(const p of s)try{const h=await RC(p.oldPath,a.name);this.rekey(p.o.c,h),l.push({c:p.o.c,from:p.o.from,oldPath:p.oldPath,fx:p.o.fx,fy:p.o.fy,frame:p.from})}catch(h){c++,d=h.message,a.cards=a.cards.filter(u=>u!==p.o.c),p.o.c.folder=p.o.from,p.o.c.x=p.o.fx,p.o.c.y=p.o.fy,this.rekey(p.o.c,p.oldPath),this.frames.has(p.o.from)||this.frames.set(p.o.from,p.from),p.from.cards.push(p.o.c),p.o.c.el&&this.fillCard(p.o.c)}if(this.kick(!0),this.persist(),l.length){const p=async()=>{for(const h of l)try{const u=await RC(h.c.path,h.from),f=this.frameOf(h.c);f&&(f.cards=f.cards.filter(v=>v!==h.c)),h.c.folder=h.from,h.c.x=h.fx,h.c.y=h.fy,this.rekey(h.c,u),this.frames.has(h.from)||(this.frames.set(h.from,h.frame),h.frame.el=null),this.frames.get(h.from).cards.push(h.c),h.c.el&&this.fillCard(h.c)}catch(u){this.toast.show("Undo failed: "+u.message,{err:!0})}this.kick(!0),this.persist(),await this.afterWrite()};this.pushUndo(`Move ${r}`,p),this.toast.show(`Moved ${l.length===1?`"${l[0].c.name}"`:l.length+" notes"} to ${a.name}${c?` · ${c} failed: ${d}`:""}`,{undo:()=>{this.runUndo()},err:c>0})}else this.toast.show(`Could not move: ${d}`,{err:!0});await this.afterWrite()}dropFrames(e){e.drop?.el?.classList.remove("drop");const n=e.drop;if(n&&e.frames.length===1){const a=e.frames[0].f;a.x=e.frames[0].x,a.y=e.frames[0].y,this.kick(!0),this.confirmFolderInto(a,n);return}for(const a of e.frames)this.separate(a.f);this.kick(!0),this.persist()}confirmFolderInto(e,n){const a=e.cards.length;ue.confirm("Move folder",`Move the folder "${e.name}" with its ${a} note${a===1?"":"s"} into "${n.name}"? The notes move on disk to ${n.name}/${e.name}/.`,"Move folder",async()=>{ue.close(),await this.moveFolderInto(e,n)},!1)}async moveFolderInto(e,n){const a=n.name==="Root"?e.name:n.name+"/"+e.name,i=e.cards.map(c=>c.path),o=new Map(e.cards.map(c=>[c.path,{x:c.x,y:c.y}])),s={x:e.x,y:e.y,w:e.w,h:e.h};this.toast.show(`Moving ${i.length} notes into ${n.name}...`,{ms:3e4}),this.busy=!0;const r=await kk(i,a);this.busy=!1;for(const c of r.moved){const d=this.cards.get(c.from);if(!d)continue;e.cards=e.cards.filter(h=>h!==d),d.folder=n.name;const p=uk(n);d.x=p.x,d.y=p.y,n.cards.push(d),this.rekey(d,c.to),this.flashPending.add(d.path),d.el&&this.fillCard(d)}this.kick(!0),this.persist();const l=async()=>{const c=await kk(r.moved.map(d=>this.cards.get(d.to)?.path||d.to),e.name);this.layout.frames[e.name]=s;for(const d of c.moved){const p=r.moved.find(f=>f.to===d.from),h=p&&o.get(p.from);h&&(this.layout.cards[d.to]=h);const u=this.cards.get(d.from);if(u){const f=this.frameOf(u);f&&(f.cards=f.cards.filter(v=>v!==u)),u.el?.remove(),this.cards.delete(d.from)}}await this.afterWrite()};this.pushUndo(`Move folder ${e.name}`,l),this.toast.show(`Moved ${r.moved.length} notes into ${n.name}/${e.name}${r.failed.length?` · ${r.failed.length} failed`:""}`,{undo:()=>{this.runUndo()},err:r.failed.length>0}),await this.afterWrite()}rekey(e,n){if(e.path===n)return;const a=e.path;this.cards.delete(a),e.path=n,this.cards.set(n,e),this.sel.delete(a)&&this.sel.add(n),this.hover===a&&(this.hover=n),GV(a,n),e.el&&(e.el.dataset.path=n),this.panel.path===a&&(this.panel.path=n)}async afterWrite(){try{await te.loadCore()}catch{}this.sync(),this.scheduleLinks()}pushUndo(e,n){this.undoStack.push({label:e,run:n}),this.undoStack.length>20&&this.undoStack.shift()}async runUndo(){const e=this.undoStack.pop();if(!e){this.toast.show("Nothing to undo");return}this.toast.show(`Undoing: ${e.label}...`);try{await e.run(),this.toast.show(`Undone: ${e.label}`)}catch(n){this.toast.show("Undo failed: "+n.message,{err:!0})}}inlineEdit(e,n,a){const i=document.createElement("input");i.value=n,i.spellcheck=!1,e.textContent="",e.appendChild(i),i.focus(),i.select();let o=!1;const s=r=>{if(o)return;o=!0;const l=i.value.trim();i.remove(),a(r&&l&&l!==n?l:"")};i.addEventListener("keydown",r=>{r.stopPropagation(),r.key==="Enter"?s(!0):r.key==="Escape"&&s(!1)}),i.addEventListener("blur",()=>s(!0)),i.addEventListener("pointerdown",r=>r.stopPropagation())}startRenameCard(e){e.el||(this.mountCard(e),this.placeCard(e));const n=e.el.querySelector(".cv-ctitle");n&&this.inlineEdit(n,e.name,a=>{if(!a){this.fillCard(e);return}this.renameCard(e,a)})}async renameCard(e,n){const a=e.path,i=e.name;e.name=n,this.rekey(e,CV(a,n)),this.fillCard(e);try{const o=await PC(a,n);this.rekey(e,o),this.pushUndo(`Rename "${i}"`,async()=>{const s=await PC(e.path,i);e.name=i,this.rekey(e,s),this.fillCard(e),await this.afterWrite()}),this.toast.show(`Renamed to "${n}"`,{undo:()=>{this.runUndo()}}),this.panel.path===e.path&&this.openPanel(e)}catch(o){e.name=i,this.rekey(e,a),this.fillCard(e),this.toast.show("Rename failed: "+o.message,{err:!0})}this.persist(),await this.afterWrite()}startRenameFrame(e){if(e.name==="Root"){this.toast.show("Root is the vault itself and cannot be renamed");return}const n=e.el?.querySelector(".cv-ftitle");n&&this.inlineEdit(n,e.name,a=>{if(!a){this.fillFrame(e);return}this.renameFrame(e,a)})}async renameFrame(e,n,a=!1){const i=LV(n),o=e.name;if(!i||i===o){this.fillFrame(e);return}if(N.tree[i]||this.frames.has(i)){this.fillFrame(e),this.toast.show(`A folder named "${i}" already exists`,{err:!0});return}const s=N.folderMeta[o]?.color;this.frames.delete(o),e.name=i,this.frames.set(i,e),e.el&&(e.el.dataset.frame=i),this.selFrames.delete(o)&&this.selFrames.add(i);const r=e.cards.map(c=>c.path);for(const c of e.cards)c.folder=i,this.rekey(c,uv(c.path,i));this.fillFrame(e),this.kick(!0),this.toast.show(`Renaming folder to ${i} (${r.length} notes)...`,{ms:3e4}),this.busy=!0;const l=await kk(r,i);this.busy=!1;for(const c of l.moved){const d=e.cards.find(p=>p.path===uv(c.from,i));d&&this.rekey(d,c.to)}if(s)try{await sj(i,s),N.folderMeta[i]={...N.folderMeta[i]||{},color:s}}catch{}l.failed.length?this.toast.show(`Renamed with ${l.failed.length} failures: ${l.failed[0].error}`,{err:!0}):a||(this.pushUndo(`Rename folder ${o}`,async()=>{const c=this.frames.get(i);c&&await this.renameFrame(c,o,!0)}),this.toast.show(`Folder renamed to ${i}`,{undo:()=>{this.runUndo()}})),this.persist(),await this.afterWrite()}recolorWhenModalCloses(){const e=document.getElementById("modalHost");if(!e)return;const n=new MutationObserver(()=>{!e.classList.contains("hidden")&&e.childElementCount||(n.disconnect(),this.recolor())});n.observe(e,{attributes:!0,childList:!0}),window.setTimeout(()=>n.disconnect(),12e4)}recolor(){for(const e of this.frames.values()){this.fillFrame(e);for(const n of e.cards)n.el&&n.el.style.setProperty("--fc",Yn(n.folder))}this.kick()}animate(e){const n=[];for(const o of this.frames.values()){n.push(o);for(const s of o.cards)n.push(s)}const a=n.map(o=>[o.x,o.y]);e();const i=[];n.forEach((o,s)=>{const[r,l]=a[s];(r!==o.x||l!==o.y)&&i.push({o,fx:r,fy:l,tx:o.x,ty:o.y})});for(const o of i)o.o.x=o.fx,o.o.y=o.fy;this.tween={t0:performance.now(),ms:380,items:i},this.kick(!0),window.setTimeout(()=>this.persist(),420)}async enter(){for(let e=0;e<40&&(!this.ready||!this.frames.size||this.W<50);e++)await new Promise(n=>setTimeout(n,75));!this.ready||!this.frames.size||(this.needFit=!1,this.animate(()=>{for(const n of this.frames.values())pv(n);const e=this.allBounds();hv(Array.from(this.frames.values()),e?e.x:0,e?e.y:0)}),await new Promise(e=>setTimeout(e,420)),this.fitTo(this.allBounds()))}tidy(e,n){const a=e&&e.length?e:Array.from(this.frames.values());this.animate(()=>{for(const i of a)pv(i);if(n){const i=this.allBounds();hv(Array.from(this.frames.values()),i?i.x:0,i?i.y:0)}}),this.toast.show(n?"Board tidied":`Tidied ${a.length} frame${a.length===1?"":"s"}`)}align(e){const n=this.selectedCards();if(n.length<2)return;const a=n.map(o=>fl(this.frameOf(o),o)),i=fk(a);this.animate(()=>{n.forEach(o=>{const s=this.frameOf(o);e==="l"&&(o.x=i.x-s.x),e==="r"&&(o.x=i.x+i.w-Sn-s.x),e==="c"&&(o.x=i.x+i.w/2-Sn/2-s.x),e==="t"&&(o.y=i.y-s.y),e==="b"&&(o.y=i.y+i.h-Dn-s.y),e==="m"&&(o.y=i.y+i.h/2-Dn/2-s.y)});for(const o of new Set(n.map(s=>this.frameOf(s))))sd(o)})}distribute(e){const n=this.selectedCards();if(n.length<3)return;const a=n.map(l=>{const c=this.frameOf(l);return{c:l,f:c,x:c.x+l.x,y:c.y+l.y}});a.sort((l,c)=>e==="h"?l.x-c.x:l.y-c.y);const i=a[0],o=a[a.length-1],r=(e==="h"?o.x-i.x:o.y-i.y)/(a.length-1);this.animate(()=>{a.forEach((l,c)=>{e==="h"?l.c.x=i.x+r*c-l.f.x:l.c.y=i.y+r*c-l.f.y});for(const l of new Set(a.map(c=>c.f)))sd(l)})}nudge(e,n){const a=this.selectedCards();if(a.length){for(const i of a)i.x+=e,i.y+=n;for(const i of new Set(a.map(o=>this.frameOf(o))))sd(i)}else for(const i of this.selFrames){const o=this.frames.get(i);o&&(o.x+=e,o.y+=n)}this.kick(!0),this.persist()}command(e){switch(e){case"tool-select":case"tool-hand":this.tool=e==="tool-hand"?"hand":"select",this.root.classList.toggle("hand",this.tool==="hand"),this.syncButtons();break;case"zoom-in":this.zoomAt(1.25,this.W/2,this.H/2);break;case"zoom-out":this.zoomAt(.8,this.W/2,this.H/2);break;case"zoom-100":this.zoomTo(1);break;case"fit":this.fitTo(this.allBounds());break;case"sel-open":{const n=this.selectedCards()[0];n&&(this.reveal(n,!1),this.openPanel(n));break}case"fit-sel":this.fitTo(this.selectionBounds()||this.allBounds());break;case"tidy":{const n=new Set;for(const a of this.selectedCards())n.add(this.frameOf(a));for(const a of this.selFrames){const i=this.frames.get(a);i&&n.add(i)}this.tidy(n.size?Array.from(n):null,!n.size);break}case"links":this.showLinks=!this.showLinks,this.syncButtons(),this.persist(),this.kick();break;case"minimap":this.vc.toggleMinimap(),this.persist();break;case"help":this.toggleHelp();break;case"al-l":case"al-c":case"al-r":case"al-t":case"al-m":case"al-b":this.align(e.slice(3));break;case"dis-h":case"dis-v":this.distribute(e.slice(4));break}}syncButtons(){const e=this.ui.tools;e.querySelector("[data-act=tool-select]")?.classList.toggle("on",this.tool==="select"),e.querySelector("[data-act=tool-hand]")?.classList.toggle("on",this.tool==="hand"),e.querySelector("[data-act=links]")?.classList.toggle("on",this.showLinks)}toggleHelp(e){const n=e??this.ui.help.classList.contains("hidden");this.ui.help.classList.toggle("hidden",!n),this.ui.scrim.classList.toggle("hidden",!n)}async openPanel(e){this.vc.close(),this.root.classList.add("panel-open");const n=N.graph.nodes.find(a=>a.path===e.path);this.panel.showNote(e.path,e.name,e.folder,Yn(e.folder),Array.isArray(n?.tags)?n.tags.map(String):[])}openFolderCard(e){this.vc.close(),this.root.classList.add("panel-open"),this.panel.showFolder(e,Yn(e),this.frames.get(e)?.cards.length)}closePanel(){this.panel.close(),this.root.classList.remove("panel-open")}buildCard(e){const n=a=>({path:a.path,name:a.name,color:Yn(a.folder),degree:this.linkCount.get(a.path)||0});return new ng({root:e,focusNode:a=>{const i=this.cards.get(a);i&&this.reveal(i,!0)},focusFolder:a=>this.focusFolder(a),onlyFolder:a=>this.setHiddenFrames(Array.from(this.frames.keys()).filter(i=>i!==a)),pick:a=>{const i=this.cards.get(a);i&&(this.select([i.path]),this.reveal(i,!0),this.openPanel(i))},links:a=>{const i=this.links.filter(s=>s.a.path===a).map(s=>n(s.b)),o=new Set(i.map(s=>s.path));return{out:i,in:this.links.filter(s=>s.b.path===a&&!o.has(s.a.path)).map(s=>n(s.a))}},folderItems:a=>Array.from(this.cards.values()).filter(i=>i.folder===a).map(n).sort((i,o)=>(o.degree||0)-(i.degree||0)),tag:a=>this.vc.setQuery("#"+a+" "),home:()=>window.setTimeout(()=>this.fitTo(this.allBounds()),60),closed:()=>this.root.classList.remove("panel-open")})}onKey(e){if(N.page!=="canvas")return;const n=e.target,a=n?.tagName;if(a==="INPUT"||a==="TEXTAREA"||a==="SELECT"||n?.isContentEditable||document.querySelector("#modalHost:not(.hidden)"))return;const i=e.ctrlKey||e.metaKey,o=e.key,s=e.code;if(s==="Space"){this.space||(this.space=!0,this.root.classList.add("hand")),e.preventDefault();return}if(o==="Escape"){this.ui.help.classList.contains("hidden")?this.g?this.cancelGesture():this.sel.size||this.selFrames.size?this.select([]):this.panel.isOpen&&this.closePanel():this.toggleHelp(!1);return}if(i&&(o==="z"||o==="Z")&&!e.shiftKey){e.preventDefault(),this.runUndo();return}if(i&&(o==="a"||o==="A")){e.preventDefault(),this.select(Array.from(this.cards.keys()));return}if(i)return;if(e.altKey){const l={KeyA:"al-l",KeyD:"al-r",KeyW:"al-t",KeyS:"al-b",KeyH:e.shiftKey?"dis-h":"al-c",KeyV:e.shiftKey?"dis-v":"al-m"};l[s]&&(e.preventDefault(),this.command(l[s]));return}if(e.shiftKey&&(s==="Digit1"||s==="Digit2"||s==="Digit0")){e.preventDefault(),this.command(s==="Digit1"?"fit":s==="Digit2"?"fit-sel":"zoom-100");return}if(o.startsWith("Arrow")){if(!this.sel.size&&!this.selFrames.size)return;e.preventDefault();const l=e.shiftKey?10:1;this.nudge(o==="ArrowLeft"?-l:o==="ArrowRight"?l:0,o==="ArrowUp"?-l:o==="ArrowDown"?l:0);return}const r=this.sel.size===1?this.cards.get(Array.from(this.sel)[0]):void 0;switch(o){case"v":case"V":this.command("tool-select");break;case"h":case"H":this.command("tool-hand");break;case"+":case"=":this.command("zoom-in");break;case"-":case"_":this.command("zoom-out");break;case"t":this.command("tidy");break;case"T":this.tidy(null,!0);break;case"l":case"L":this.command("links");break;case"m":case"M":this.command("minimap");break;case"?":this.toggleHelp();break;case"/":e.preventDefault(),this.vc.focusSearch();break;case"Enter":r&&(e.preventDefault(),this.openPanel(r));break;case"o":case"O":r&&te.openNote(r.path);break;case"F2":if(e.preventDefault(),r)this.startRenameCard(r);else if(this.selFrames.size===1){const l=this.frames.get(Array.from(this.selFrames)[0]);l&&this.startRenameFrame(l)}break;default:return}}findCard(e){if(!e)return;const n=e.replace(/^\/+/,""),a=this.cards.get(n)||this.cards.get(n+".md");if(a)return a;const i=pn(n);for(const o of this.cards.values())if(o.name===i)return o}onActivity(e){const n=e.paths||[],a=e.phase==="start";let i;for(const o of n){const s=this.findCard(o);s&&(s.touch={actor:e.actor,label:e.label||e.action,at:Date.now(),live:a},s.el&&this.fillCard(s),i=s)}i&&this.moveCursor(e.actor,i,e.label||e.action)}moveCursor(e,n,a){const i=this.frameOf(n);if(!i)return;let o=this.cursors.get(e);if(!o){const l=document.createElement("div");l.className="cv-cursor",l.style.setProperty("--ac",An(e)),l.style.opacity="0",this.fg.appendChild(l),o={el:l,timer:0},this.cursors.set(e,o);const c=fl(i,n);l.style.transform=`translate(${c.x+c.w+40}px,${c.y-40}px)`,l.offsetWidth}o.el.innerHTML=`<div class="cv-cursor-in">${nj}<b>${x(e)}<small>${x(a)}</small></b></div>`;const s=fl(i,n);o.el.style.opacity="1",o.el.style.transform=`translate(${s.x+s.w-34}px,${s.y+s.h-30}px)`,this.fg.appendChild(o.el),clearTimeout(o.timer);const r=o;o.timer=window.setTimeout(()=>{r.el.style.opacity="0",window.setTimeout(()=>{r.el.style.opacity==="0"&&(r.el.remove(),this.cursors.delete(e))},500)},9e3)}decayTouches(){const e=Date.now();for(const n of this.cards.values())n.touch&&(n.touch.live&&e-n.touch.at>6e4&&(n.touch.live=!1),e-n.touch.at>Mk&&(n.touch=null),n.el&&this.fillCard(n))}onMutation(e){const n=e.node||{},a=String(n.path||e.path||""),i=String(e.old_path||"");if(e.type==="node_renamed"&&i&&a){const s=this.cards.get(i);s&&this.rekey(s,a)}if(a){WV(a),this.flashPending.add(a);const s=this.cards.get(a);s&&(e.actor&&(s.touch={actor:String(e.actor),label:String(e.type).replace("node_",""),at:Date.now(),live:!1}),s.el&&this.fillCard(s))}if(this.busy)return;const o=N.tree;clearTimeout(this.syncTimer),this.syncTimer=window.setTimeout(()=>{N.tree===o?this.afterWrite():(this.sync(),this.scheduleLinks())},900)}}function pj(t,e){let n=!t.classList.contains("hidden");new MutationObserver(()=>{const a=!t.classList.contains("hidden");a!==n&&(n=a,e(a))}).observe(t,{attributes:!0,attributeFilter:["class"]})}const DC="memora.canvas.hiddenFrames";function hj(){try{const t=JSON.parse(localStorage.getItem(DC)||"[]");return new Set(Array.isArray(t)?t.map(String):[])}catch{return new Set}}function uj(t){try{localStorage.setItem(DC,JSON.stringify(Array.from(t)))}catch{}}const OC="memora.canvas.labels";function fj(){try{const t=JSON.parse(localStorage.getItem(OC)||"{}");return{nodes:t.nodes!==!1,folders:t.folders!==!1}}catch{return{nodes:!0,folders:!0}}}function $C(t){try{localStorage.setItem(OC,JSON.stringify(t))}catch{}}const mj=`
|
|
11872
11892
|
:root.no-dots .cv{background-image:none!important}
|
|
11873
11893
|
#view-canvas{padding:0;overflow:hidden}
|
|
11874
11894
|
.cv{
|
|
@@ -12795,17 +12815,17 @@ html[data-theme=light] .cv-scrim{background:var(--scrim,rgba(15,23,42,.22))}
|
|
|
12795
12815
|
|
|
12796
12816
|
${Ii("stStop","Stop Memora on the machine it runs on.",Ra(mn("Shut down the server","Every browser and agent is disconnected until someone starts Memora again on that machine. This page cannot start it again.",`<button class="btn danger" id="sShutdown" type="button">${V("logout")}Shut down…</button>`,{ctl:"end",cls:"inl"}),{cls:"st-dz"}))}
|
|
12797
12817
|
</div>
|
|
12798
|
-
</div></div>`;const v=z=>{const j=z?.session_ttl||Number(i.session_ttl)||0,ce=z?.session_max_age||0,I=[["Version",c?"v"+c:"-",!1],["Server name",i.realm||o.realm||"-",!1],["Address for agents",location.origin+"/mcp",!0],["Notes folder",z?.vault||N.health.vault||i.vault||"Not set",!0],["Memora data folder",z?.state_dir||"-",!0],["Sign out after inactivity",j?Sv(j):"-",!1],["Longest sign-in",ce?Sv(ce):"No limit",!1],["Sign-in protection",o.locked?"Locked after too many attempts":o.armed?"Setup or reset window open":"Normal",!1]],U=t.querySelector("#sServerKv");U&&(U.innerHTML=I.map(([Y,pe,Ie])=>`<dt>${x(Y)}</dt><dd${Ie?' class="mono"':""}><span>${x(pe)}</span>${Ie&&pe!=="-"&&pe!=="Not set"?KC(pe,Y):""}</dd>`).join(""))};v(null);const g=[[1800,"30 minutes"],[3600,"1 hour"],[10800,"3 hours"],[28800,"8 hours"],[86400,"1 day"],[604800,"7 days"],[2592e3,"30 days"]],m=[[0,"No limit"],[86400,"1 day"],[604800,"7 days"],[2592e3,"30 days"],[7776e3,"90 days"]],b=t.querySelector("#sRealm"),k=t.querySelector("#sTtl"),y=t.querySelector("#sMaxAge"),w=t.querySelector("#sSrvSave");let A={realm:String(i.realm||o.realm||"Memora"),ttl:Number(i.session_ttl)||10800,max:0};const _=(z,j,ce)=>{const I=j.some(([U])=>U===ce)?j:[...j,[ce,Sv(ce)]].sort((U,Y)=>(U[0]||1/0)-(Y[0]||1/0));z.innerHTML=I.map(([U,Y])=>`<option value="${U}"${U===ce?" selected":""}>${x(Y)}</option>`).join("")},S=()=>{b.value=A.realm,_(k,g,A.ttl),_(y,m,A.max),w.disabled=!0},T=()=>{const z=Number(k.value),j=Number(y.value),ce=!b.value.trim()||j!==0&&j<z;w.disabled=ce||b.value.trim()===A.realm&&z===A.ttl&&j===A.max,Nt(t,"#sSrvSt",ce&&j!==0&&j<z?"error":"",ce&&j!==0&&j<z?"Longest sign-in must be at least the inactivity time":"")};[b,k,y].forEach(z=>z.addEventListener("input",T)),t.querySelector("#sSrvForm")?.addEventListener("submit",z=>{z.preventDefault(),w.disabled||w.click()}),w.onclick=()=>{(async()=>{w.disabled=!0,Nt(t,"#sSrvSt","saving","Saving…");try{const z=await Ve("/api/settings/server",{realm:b.value.trim(),session_ttl:Number(k.value),session_max_age:Number(y.value)});A={realm:z.realm,ttl:z.session_ttl,max:z.session_max_age},i.realm=z.realm,i.session_ttl=z.session_ttl,S(),Nt(t,"#sSrvSt","saved","Saved"),ye("Server settings saved","ok"),cd().then(j=>v(j)).catch(()=>v(null))}catch(z){Nt(t,"#sSrvSt","error",z.message),T()}})()},S(),cd().then(z=>{const j=z;j?.session_max_age!=null&&(A.max=j.session_max_age),j?.session_ttl&&(A.ttl=j.session_ttl),S()}).catch(()=>{}),t.querySelector("#sWhatsNew")?.addEventListener("click",()=>hy()),t.querySelector("#sDocs")?.addEventListener("click",z=>{z.preventDefault(),te.go("docs")}),Fb(c,i).then(z=>{const j=t.querySelector("#sVerState"),ce=t.querySelector("#sVerHint"),I=t.querySelector("#sVerLink"),U=t.querySelector("#sVerLatest");!j||!ce||!I||(I.href=z.url,U&&(U.textContent=z.latest?"v"+z.latest:z.state==="none"?"None yet":"-"),j.classList.remove("new","ok","warn"),z.available&&z.latest?(j.textContent="Update available v"+z.latest,j.classList.add("new"),ce.textContent="A newer release is out. Read what changed, then update.",I.textContent="View v"+z.latest+" on GitHub"):z.state==="ok"||z.state==="none"?(j.textContent="Up to date",j.classList.add("ok"),ce.textContent=z.state==="ok"?"You run the newest release.":"No release has been published yet."):z.state==="off"?(j.textContent="Checks off",ce.textContent="Release checks are turned off on this server (MEMORA_UPDATE_CHECK)."):z.state==="pending"?(j.textContent="Checking…",ce.textContent="The server checks GitHub shortly after it starts."):(j.textContent="Could not check",j.classList.add("warn"),ce.textContent="The server could not reach GitHub. It tries again later."))});const E=t.querySelector(".st-page"),P=t.querySelector(".st-nav"),R=Array.from(t.querySelectorAll("[data-sec]")),B=Array.from(t.querySelectorAll(".st-sec"));Na(P);const D=()=>E.clientWidth>=Zj,$=()=>{const z=ri??lu[0].id,j=D()||!!ri;R.forEach(ce=>{j&&ce.dataset.sec===z?ce.setAttribute("aria-current","true"):ce.removeAttribute("aria-current")})},G=(z,j,ce=!1)=>{if(N.page!=="settings"||!Ok())return;const I=pd(z),U="/settings"+(I?"#"+I.slug:""),Y=I?{page:"settings",stSec:I.id,stPushed:j==="push"||ce}:{page:"settings"};try{j==="push"?history.pushState(Y,"",U):history.replaceState(Y,"",U)}catch{}},O=(z,j,ce=!1)=>{ri=pd(z)?.id??null;const I=ri??lu[0].id;E.dataset.open=ri?"1":"0",B.forEach(U=>U.hidden=U.id!==I),$(),G(ri,j,ce)},J=z=>t.querySelector(`#${z}T`)?.focus({preventScroll:!0}),ne=z=>{(R.find(ce=>ce.dataset.sec===z)||R[0])?.focus({preventScroll:!0})};R.forEach(z=>{z.onclick=j=>{if(j.metaKey||j.ctrlKey||j.shiftKey||j.altKey||j.button)return;j.preventDefault();const ce=z.dataset.sec,I=D();O(ce,I||ri===ce?"replace":"push"),t.scrollTop=0,I||J(ce)}});const ae=t.querySelector("#stNavTg"),q=z=>{t.querySelector(".st-page")?.classList.toggle("nav-mini",z),ae.setAttribute("aria-pressed",String(z)),ae.title=z?"Show section names":"Hide section names for a wider page",ae.querySelector("span").textContent=z?"Show labels":"Hide labels"};let we=!1;try{we=localStorage.getItem("memora.settings.navMini")==="1"}catch{}q(we),ae.onclick=()=>{we=!we,q(we);try{localStorage.setItem("memora.settings.navMini",we?"1":"0")}catch{}},t.querySelector("#stUp").onclick=()=>{const z=ri;if(history.state?.stPushed){history.back();return}O(null,"replace"),t.scrollTop=0,ne(z)},Fk?.disconnect(),Fk=new ResizeObserver(()=>$()),Fk.observe(E),t.onscroll=null;const Re=IN(),ot=pd(Re)?.id??JC??ri;JC=null,O(ot,"replace",!!e?.pushed&&ot===e.id),E.addEventListener("click",z=>{const j=z.target.closest("[data-copy]");j&&ya(j.dataset.copy||"",`${j.dataset.what||"Value"} copied`)}),Mv={root:E,show:(z,j,ce)=>{const I=ri;O(z,j,ce),t.scrollTop=0,z&&!D()?J(z):z||ne(I)}};const Qe=Array.from(t.querySelectorAll("[data-theme-pref]"));GC||(GC=!0,window.addEventListener("memora:theme",z=>{const j=z.detail;document.querySelectorAll(".st-theme [data-theme-pref]").forEach(ce=>{ce.setAttribute("aria-checked",String(ce.dataset.themePref===j)),ce.tabIndex=ce.dataset.themePref===j?0:-1})}));const st=z=>{Hl(z.dataset.themePref),Qe.forEach(j=>{j.setAttribute("aria-checked",String(j===z)),j.tabIndex=j===z?0:-1})};Qe.forEach((z,j)=>{z.onclick=()=>st(z),z.onkeydown=ce=>{if(!["ArrowRight","ArrowLeft","ArrowDown","ArrowUp"].includes(ce.key))return;ce.preventDefault();const I=Qe[(j+(ce.key==="ArrowRight"||ce.key==="ArrowDown"?1:Qe.length-1))%Qe.length];st(I),I.focus()}});const de=t.querySelector("#sUserForm"),Z=t.querySelector("#sUser"),Ne=t.querySelector("#sUserPw"),Xe=t.querySelector("#sUserPwF"),De=t.querySelector("#sUserSave"),be=z=>{r=z,Z.value=z,t.querySelector("#sMeName").textContent=z,t.querySelector("#sAv").textContent=z.slice(0,1).toUpperCase();const j=t.querySelector("#sPwUserHint");j&&(j.value=z),_E(z)},ft=()=>{const z=Z.value.trim().toLowerCase()!==r.toLowerCase();Xe.hidden=!z,De.disabled=!z};Z.oninput=()=>{ft(),Nt(t,"#sUserSt","")},de.onsubmit=z=>{z.preventDefault();const j=Z.value.trim();if(!j)return Nt(t,"#sUserSt","error","Enter a username.");if(!/^[A-Za-z0-9._-]{1,32}$/.test(j))return Nt(t,"#sUserSt","error","Use letters, digits, '-', '_' or '.', at most 32.");if(j.toLowerCase()===r.toLowerCase())return Nt(t,"#sUserSt","error","That is already your username.");if(!Ne.value)return Ne.focus(),Nt(t,"#sUserSt","error","Enter your current password.");De.disabled=!0,Nt(t,"#sUserSt","saving"),(async()=>{try{const ce=await Ve("/api/settings/username",{username:j,current:Ne.value});Ne.value="",be(ce.user||j.toLowerCase());const I=await cd().catch(()=>null);I?.user&&be(I.user),ft(),Nt(t,"#sUserSt","saved",`Saved as ${r}`),ye("Username changed","ok")}catch(ce){Nt(t,"#sUserSt","error",ce.message),De.disabled=!1}})()},ft();const rt=t.querySelector("#sPwForm"),vt=t.querySelector("#sPwOpenBox"),Rt=t.querySelector("#sPwClosed"),mt=z=>t.querySelector(z).value,Gt=()=>{["#sPwCur","#sPw1","#sPw2"].forEach(z=>t.querySelector(z).value="")},
|
|
12818
|
+
</div></div>`;const v=z=>{const j=z?.session_ttl||Number(i.session_ttl)||0,ce=z?.session_max_age||0,I=[["Version",c?"v"+c:"-",!1],["Server name",i.realm||o.realm||"-",!1],["Address for agents",location.origin+"/mcp",!0],["Notes folder",z?.vault||N.health.vault||i.vault||"Not set",!0],["Memora data folder",z?.state_dir||"-",!0],["Sign out after inactivity",j?Sv(j):"-",!1],["Longest sign-in",ce?Sv(ce):"No limit",!1],["Sign-in protection",o.locked?"Locked after too many attempts":o.armed?"Setup or reset window open":"Normal",!1]],U=t.querySelector("#sServerKv");U&&(U.innerHTML=I.map(([Y,pe,Ie])=>`<dt>${x(Y)}</dt><dd${Ie?' class="mono"':""}><span>${x(pe)}</span>${Ie&&pe!=="-"&&pe!=="Not set"?KC(pe,Y):""}</dd>`).join(""))};v(null);const g=[[1800,"30 minutes"],[3600,"1 hour"],[10800,"3 hours"],[28800,"8 hours"],[86400,"1 day"],[604800,"7 days"],[2592e3,"30 days"]],m=[[0,"No limit"],[86400,"1 day"],[604800,"7 days"],[2592e3,"30 days"],[7776e3,"90 days"]],b=t.querySelector("#sRealm"),k=t.querySelector("#sTtl"),y=t.querySelector("#sMaxAge"),w=t.querySelector("#sSrvSave");let A={realm:String(i.realm||o.realm||"Memora"),ttl:Number(i.session_ttl)||10800,max:0};const _=(z,j,ce)=>{const I=j.some(([U])=>U===ce)?j:[...j,[ce,Sv(ce)]].sort((U,Y)=>(U[0]||1/0)-(Y[0]||1/0));z.innerHTML=I.map(([U,Y])=>`<option value="${U}"${U===ce?" selected":""}>${x(Y)}</option>`).join("")},S=()=>{b.value=A.realm,_(k,g,A.ttl),_(y,m,A.max),w.disabled=!0},T=()=>{const z=Number(k.value),j=Number(y.value),ce=!b.value.trim()||j!==0&&j<z;w.disabled=ce||b.value.trim()===A.realm&&z===A.ttl&&j===A.max,Nt(t,"#sSrvSt",ce&&j!==0&&j<z?"error":"",ce&&j!==0&&j<z?"Longest sign-in must be at least the inactivity time":"")};[b,k,y].forEach(z=>z.addEventListener("input",T)),t.querySelector("#sSrvForm")?.addEventListener("submit",z=>{z.preventDefault(),w.disabled||w.click()}),w.onclick=()=>{(async()=>{w.disabled=!0,Nt(t,"#sSrvSt","saving","Saving…");try{const z=await Ve("/api/settings/server",{realm:b.value.trim(),session_ttl:Number(k.value),session_max_age:Number(y.value)});A={realm:z.realm,ttl:z.session_ttl,max:z.session_max_age},i.realm=z.realm,i.session_ttl=z.session_ttl,S(),Nt(t,"#sSrvSt","saved","Saved"),ye("Server settings saved","ok"),cd().then(j=>v(j)).catch(()=>v(null))}catch(z){Nt(t,"#sSrvSt","error",z.message),T()}})()},S(),cd().then(z=>{const j=z;j?.session_max_age!=null&&(A.max=j.session_max_age),j?.session_ttl&&(A.ttl=j.session_ttl),S()}).catch(()=>{}),t.querySelector("#sWhatsNew")?.addEventListener("click",()=>hy()),t.querySelector("#sDocs")?.addEventListener("click",z=>{z.preventDefault(),te.go("docs")}),Fb(c,i).then(z=>{const j=t.querySelector("#sVerState"),ce=t.querySelector("#sVerHint"),I=t.querySelector("#sVerLink"),U=t.querySelector("#sVerLatest");!j||!ce||!I||(I.href=z.url,U&&(U.textContent=z.latest?"v"+z.latest:z.state==="none"?"None yet":"-"),j.classList.remove("new","ok","warn"),z.available&&z.latest?(j.textContent="Update available v"+z.latest,j.classList.add("new"),ce.textContent="A newer release is out. Read what changed, then update.",I.textContent="View v"+z.latest+" on GitHub"):z.state==="ok"||z.state==="none"?(j.textContent="Up to date",j.classList.add("ok"),ce.textContent=z.state==="ok"?"You run the newest release.":"No release has been published yet."):z.state==="off"?(j.textContent="Checks off",ce.textContent="Release checks are turned off on this server (MEMORA_UPDATE_CHECK)."):z.state==="pending"?(j.textContent="Checking…",ce.textContent="The server checks GitHub shortly after it starts."):(j.textContent="Could not check",j.classList.add("warn"),ce.textContent="The server could not reach GitHub. It tries again later."))});const E=t.querySelector(".st-page"),P=t.querySelector(".st-nav"),R=Array.from(t.querySelectorAll("[data-sec]")),B=Array.from(t.querySelectorAll(".st-sec"));Na(P);const D=()=>E.clientWidth>=Zj,$=()=>{const z=ri??lu[0].id,j=D()||!!ri;R.forEach(ce=>{j&&ce.dataset.sec===z?ce.setAttribute("aria-current","true"):ce.removeAttribute("aria-current")})},G=(z,j,ce=!1)=>{if(N.page!=="settings"||!Ok())return;const I=pd(z),U="/settings"+(I?"#"+I.slug:""),Y=I?{page:"settings",stSec:I.id,stPushed:j==="push"||ce}:{page:"settings"};try{j==="push"?history.pushState(Y,"",U):history.replaceState(Y,"",U)}catch{}},O=(z,j,ce=!1)=>{ri=pd(z)?.id??null;const I=ri??lu[0].id;E.dataset.open=ri?"1":"0",B.forEach(U=>U.hidden=U.id!==I),$(),G(ri,j,ce)},J=z=>t.querySelector(`#${z}T`)?.focus({preventScroll:!0}),ne=z=>{(R.find(ce=>ce.dataset.sec===z)||R[0])?.focus({preventScroll:!0})};R.forEach(z=>{z.onclick=j=>{if(j.metaKey||j.ctrlKey||j.shiftKey||j.altKey||j.button)return;j.preventDefault();const ce=z.dataset.sec,I=D();O(ce,I||ri===ce?"replace":"push"),t.scrollTop=0,I||J(ce)}});const ae=t.querySelector("#stNavTg"),q=z=>{t.querySelector(".st-page")?.classList.toggle("nav-mini",z),ae.setAttribute("aria-pressed",String(z)),ae.title=z?"Show section names":"Hide section names for a wider page",ae.querySelector("span").textContent=z?"Show labels":"Hide labels"};let we=!1;try{we=localStorage.getItem("memora.settings.navMini")==="1"}catch{}q(we),ae.onclick=()=>{we=!we,q(we);try{localStorage.setItem("memora.settings.navMini",we?"1":"0")}catch{}},t.querySelector("#stUp").onclick=()=>{const z=ri;if(history.state?.stPushed){history.back();return}O(null,"replace"),t.scrollTop=0,ne(z)},Fk?.disconnect(),Fk=new ResizeObserver(()=>$()),Fk.observe(E),t.onscroll=null;const Re=IN(),ot=pd(Re)?.id??JC??ri;JC=null,O(ot,"replace",!!e?.pushed&&ot===e.id),E.addEventListener("click",z=>{const j=z.target.closest("[data-copy]");j&&ya(j.dataset.copy||"",`${j.dataset.what||"Value"} copied`)}),Mv={root:E,show:(z,j,ce)=>{const I=ri;O(z,j,ce),t.scrollTop=0,z&&!D()?J(z):z||ne(I)}};const Qe=Array.from(t.querySelectorAll("[data-theme-pref]"));GC||(GC=!0,window.addEventListener("memora:theme",z=>{const j=z.detail;document.querySelectorAll(".st-theme [data-theme-pref]").forEach(ce=>{ce.setAttribute("aria-checked",String(ce.dataset.themePref===j)),ce.tabIndex=ce.dataset.themePref===j?0:-1})}));const st=z=>{Hl(z.dataset.themePref),Qe.forEach(j=>{j.setAttribute("aria-checked",String(j===z)),j.tabIndex=j===z?0:-1})};Qe.forEach((z,j)=>{z.onclick=()=>st(z),z.onkeydown=ce=>{if(!["ArrowRight","ArrowLeft","ArrowDown","ArrowUp"].includes(ce.key))return;ce.preventDefault();const I=Qe[(j+(ce.key==="ArrowRight"||ce.key==="ArrowDown"?1:Qe.length-1))%Qe.length];st(I),I.focus()}});const de=t.querySelector("#sUserForm"),Z=t.querySelector("#sUser"),Ne=t.querySelector("#sUserPw"),Xe=t.querySelector("#sUserPwF"),De=t.querySelector("#sUserSave"),be=z=>{r=z,Z.value=z,t.querySelector("#sMeName").textContent=z,t.querySelector("#sAv").textContent=z.slice(0,1).toUpperCase();const j=t.querySelector("#sPwUserHint");j&&(j.value=z),_E(z)},ft=()=>{const z=Z.value.trim().toLowerCase()!==r.toLowerCase();Xe.hidden=!z,De.disabled=!z};Z.oninput=()=>{ft(),Nt(t,"#sUserSt","")},de.onsubmit=z=>{z.preventDefault();const j=Z.value.trim();if(!j)return Nt(t,"#sUserSt","error","Enter a username.");if(!/^[A-Za-z0-9._-]{1,32}$/.test(j))return Nt(t,"#sUserSt","error","Use letters, digits, '-', '_' or '.', at most 32.");if(j.toLowerCase()===r.toLowerCase())return Nt(t,"#sUserSt","error","That is already your username.");if(!Ne.value)return Ne.focus(),Nt(t,"#sUserSt","error","Enter your current password.");De.disabled=!0,Nt(t,"#sUserSt","saving"),(async()=>{try{const ce=await Ve("/api/settings/username",{username:j,current:Ne.value});Ne.value="",be(ce.user||j.toLowerCase());const I=await cd().catch(()=>null);I?.user&&be(I.user),ft(),Nt(t,"#sUserSt","saved",`Saved as ${r}`),ye("Username changed","ok")}catch(ce){Nt(t,"#sUserSt","error",ce.message),De.disabled=!1}})()},ft();const rt=t.querySelector("#sPwForm"),vt=t.querySelector("#sPwOpenBox"),Rt=t.querySelector("#sPwClosed"),mt=z=>t.querySelector(z).value,Gt=()=>{["#sPwCur","#sPw1","#sPw2"].forEach(z=>t.querySelector(z).value="")},ln=z=>{vt.hidden=!z,Rt.hidden=z,z&&t.querySelector("#sPwCur").focus()};t.querySelector("#sPwOpen").onclick=()=>{Nt(t,"#sPwSt0",""),ln(!0)},t.querySelector("#sPwCancel").onclick=()=>{Gt(),Nt(t,"#sPwSt",""),ln(!1)},rt.onsubmit=z=>{z.preventDefault();const j=mt("#sPwCur"),ce=mt("#sPw1"),I=mt("#sPw2");if(!j)return Nt(t,"#sPwSt","error","Enter your current password.");if(ce.length<l)return Nt(t,"#sPwSt","error",`The new password needs at least ${l} characters.`);if(ce!==I)return Nt(t,"#sPwSt","error","The new passwords do not match.");const U=t.querySelector("#sPwSave");U.disabled=!0,Nt(t,"#sPwSt","saving"),(async()=>{try{const Y=await Ve("/api/settings/password",{current:j,password:ce,confirm:I});Gt(),ln(!1);const pe=Y.revoked_sessions||0;Nt(t,"#sPwSt0","saved","Password changed"+(pe?`. ${us(pe,"other device")} signed out.`:".")),ye("Password changed","ok"),dn()}catch(Y){Nt(t,"#sPwSt","error",Y.message)}finally{U.disabled=!1}})()};let cn=[];const Ut=t.querySelector("#sSess"),Jt=t.querySelector("#sOutOthers"),K=z=>{const j=[z.current?"Active now":"Active "+$i(z.last_seen),z.ip?"IP "+z.ip:"","Signed in "+jC(z.created_at)].filter(Boolean);return`<div class="st-ses${z.current?" cur":""}" data-id="${x(z.id)}">
|
|
12799
12819
|
<span class="dv" aria-hidden="true">${YC(z)}</span>
|
|
12800
12820
|
<div class="mn"><div class="nm"><span>${x(dd(z))}</span>${z.current?'<span class="st-tag">This device</span>':""}</div>
|
|
12801
12821
|
<div class="mt">${j.map(x).join("<em>·</em>")}</div></div>
|
|
12802
12822
|
<button type="button" class="more" data-more="${x(z.id)}" aria-haspopup="menu" aria-label="Actions for ${x(dd(z))}">${V("more")}</button>
|
|
12803
|
-
</div>`},
|
|
12823
|
+
</div>`},dn=async()=>{try{cn=(await Oe("/api/settings/sessions")).sessions||[]}catch(I){Ut.innerHTML=`<div class="st-empty">Could not read the sessions: ${x(I.message)}</div>`;return}if(!t.contains(Ut))return;Ut.innerHTML=cn.length?cn.map(K).join(""):'<div class="st-empty">No sessions.</div>';const z=cn.filter(I=>!I.current).length;Jt.disabled=z===0,Jt.title=z?"":"No other device is signed in";const j=cn.find(I=>I.current),ce=t.querySelector("#sMeSub");ce&&(ce.textContent=`Signed in on this device${j?.expires_in?` · session renews while you work (${Sv(j.expires_in)} idle left)`:""}`+(z?` · ${us(z,"other device")}`:"")),Ut.querySelectorAll("[data-more]").forEach(I=>{I.onclick=()=>{const U=cn.find(Y=>Y.id===I.dataset.more);U&&ee(I,U)}})},zt=async z=>{try{await Ve("/api/settings/sessions/revoke",{id:z.id}),ye(`${dd(z)} signed out`,"ok")}catch(j){ye("Could not sign it out: "+j.message,"err")}dn()},F=z=>{const j=Tu({title:"Name this device",sub:zk(z.user_agent)||"Unknown device",width:440,body:`<div class="field"><label for="sAlias">Device name</label>
|
|
12804
12824
|
<input id="sAlias" type="text" maxlength="64" value="${x(z.alias||"")}" placeholder="${x(zk(z.user_agent)||"Work laptop")}">
|
|
12805
12825
|
<span class="hint">Shown in this list only. Leave empty to show the browser name.</span></div>
|
|
12806
|
-
<span class="st-state" id="sAliasSt" role="status" aria-live="polite"></span>`,actions:[{label:"Cancel",cls:"ghost",run:ce=>ce.close()},{label:"Save",cls:"primary",run:async ce=>{const I=ce.body.querySelector("#sAlias").value;Nt(ce.body,"#sAliasSt","saving");try{await Ve("/api/settings/sessions/rename",{id:z.id,alias:I}),ce.close(),ye("Device renamed","ok"),
|
|
12826
|
+
<span class="st-state" id="sAliasSt" role="status" aria-live="polite"></span>`,actions:[{label:"Cancel",cls:"ghost",run:ce=>ce.close()},{label:"Save",cls:"primary",run:async ce=>{const I=ce.body.querySelector("#sAlias").value;Nt(ce.body,"#sAliasSt","saving");try{await Ve("/api/settings/sessions/rename",{id:z.id,alias:I}),ce.close(),ye("Device renamed","ok"),dn()}catch(U){Nt(ce.body,"#sAliasSt","error",U.message)}}}]});j.body.querySelector("#sAlias")?.addEventListener("keydown",ce=>{ce.key==="Enter"&&j.foot?.querySelector(".btn.primary")?.click()})},M=z=>{const j=Mu({title:"Activity on this device",sub:dd(z)+(z.current?" · this device":""),body:`<p class="st-act-note">Sign-ins, account changes and failed attempts recorded from ${z.ip?`IP <b>${x(z.ip)}</b>`:"this device"} since it signed in on ${x(jC(z.created_at))}. Note changes and agent work are in Activity.</p>
|
|
12807
12827
|
<ul class="st-act" id="sActList"><li><span class="e"><span>Loading…</span></span></li></ul>`,foot:`<button type="button" class="btn" id="sActLogs">${V("activity")}Open Activity</button>`});j.querySelector("#sActLogs").onclick=()=>{j.querySelector("[data-x]")?.click(),te.go("logs")},Oe("/api/settings/sessions/activity?id="+encodeURIComponent(z.id)).then(ce=>{const I=j.querySelector("#sActList");if(!I)return;const U=ce.events||[];I.innerHTML=U.length?U.map(Y=>`<li><span class="w" title="${x(new Date(Y.at*1e3).toLocaleString())}">${x($i(Y.at))}</span>
|
|
12808
|
-
<span class="e${/fail|denied|blocked/.test(Y.event)?" bad":""}"><b>${x(Yj(Y.event))}</b>${Y.detail||Y.user?`<span>${x([Y.user,Y.detail].filter(Boolean).join(" · "))}</span>`:""}</span></li>`).join(""):'<li><span class="e"><span>Nothing recorded from this device yet.</span></span></li>'}).catch(ce=>{const I=j.querySelector("#sActList");I&&(I.innerHTML=`<li><span class="e bad"><b>Could not load</b><span>${x(ce.message)}</span></span></li>`)})},ee=(z,j)=>{pr(z,[{label:"Activity on this device",desc:"Sign-ins and account changes from it",icon:V("activity"),run:()=>M(j)},{label:"Rename device",desc:"Give it a name you recognise",icon:V("note"),run:()=>F(j)},{label:"",sep:!0},j.current?{label:"Sign out here",desc:"End the session in this browser",icon:V("logout"),danger:!0,run:()=>{se()}}:{label:"Sign out this device",desc:"It must sign in again and is told why",icon:V("logout"),danger:!0,run:()=>ue.confirm("Sign out this device?",`${dd(j)} will be signed out at once and must sign in again.`,"Sign out",async()=>{ue.close(),await zt(j)})}],{title:dd(j)+(j.current?" (this device)":""),lead:YC(j)})};Jt.onclick=()=>{const z=
|
|
12828
|
+
<span class="e${/fail|denied|blocked/.test(Y.event)?" bad":""}"><b>${x(Yj(Y.event))}</b>${Y.detail||Y.user?`<span>${x([Y.user,Y.detail].filter(Boolean).join(" · "))}</span>`:""}</span></li>`).join(""):'<li><span class="e"><span>Nothing recorded from this device yet.</span></span></li>'}).catch(ce=>{const I=j.querySelector("#sActList");I&&(I.innerHTML=`<li><span class="e bad"><b>Could not load</b><span>${x(ce.message)}</span></span></li>`)})},ee=(z,j)=>{pr(z,[{label:"Activity on this device",desc:"Sign-ins and account changes from it",icon:V("activity"),run:()=>M(j)},{label:"Rename device",desc:"Give it a name you recognise",icon:V("note"),run:()=>F(j)},{label:"",sep:!0},j.current?{label:"Sign out here",desc:"End the session in this browser",icon:V("logout"),danger:!0,run:()=>{se()}}:{label:"Sign out this device",desc:"It must sign in again and is told why",icon:V("logout"),danger:!0,run:()=>ue.confirm("Sign out this device?",`${dd(j)} will be signed out at once and must sign in again.`,"Sign out",async()=>{ue.close(),await zt(j)})}],{title:dd(j)+(j.current?" (this device)":""),lead:YC(j)})};Jt.onclick=()=>{const z=cn.filter(j=>!j.current).length;ue.confirm("Sign out other devices?",`${us(z,"other device")} will be signed out and must sign in again. This device stays signed in. Connected agents keep working.`,"Sign out others",async()=>{ue.close(),Nt(t,"#sOutSt","saving","Signing out…");try{const ce=(await Ve("/api/settings/sessions/revoke",{others:!0})).revoked||0;Nt(t,"#sOutSt","saved",ce?`${us(ce,"device")} signed out`:"No other devices")}catch(j){Nt(t,"#sOutSt","error",j.message)}dn()})};const se=async()=>{try{await Ve("/api/auth/logout"),location.href="/login"}catch(z){ye("Could not sign out: "+z.message,"err")}};t.querySelector("#sLogout").onclick=()=>{se()},t.querySelector("#sShutdown").onclick=()=>{eY()},dn(),a.then(z=>{const j=z||{};if(n!==ru||!t.contains(H("#sVaultNow")))return;j.user&&j.user!==r&&be(j.user),ft(),v(z?j:null),H("#sVaultNow").innerHTML=Dk(j.vault!==void 0?j:{vault:N.health.vault||i.vault||null});let ce={vault:j.vault??null,notes:j.stats?.notes};UC(H("#sVaultForm"),{id:"sv",suggested:j.vault_suggested,current:j.vault,submitLabel:"Check and switch…",confirm:(I,U)=>iY(ce,I,U),onDone:async I=>{const U=ce.vault;ce={vault:I.vault||null,notes:I.stats?.notes},H("#svPath").value="",H("#svCreate").checked=!1,H("#sVaultNow").innerHTML=Dk({vault:I.vault,stats:I.stats,vault_writable:!0});const Y=H("#svErr");Y.className="vf-ok",Y.innerHTML=`${x(`Checked and switched. Now using ${I.vault}${I.created?" (created)":""}: ${Pk(I.stats?.notes)}.`)}${U&&U!==I.vault?`<div class="st-back"><button type="button" class="btn sm" id="svBack">Switch back to ${x(U)}</button></div>`:""}`,Y.querySelector("#svBack")?.addEventListener("click",()=>{const pe=H("#svPath");pe.value=U||"",H("#svForm").requestSubmit()}),await BC(),cd().then(pe=>v(pe)).catch(()=>{}),ye("Notes folder switched","ok")}})});const he=t.querySelector("#sCollapsed");he.onclick=()=>{const z=he.getAttribute("aria-checked")!=="true";he.setAttribute("aria-checked",String(z)),Eo.collapsed=z,uu(),ye(z?"The sidebar starts collapsed":"The sidebar starts open","ok",1800)};const Le=t.querySelector("#sToasts"),ze=t.querySelector("#sToastKeys"),ge=()=>{ze.classList.toggle("off",Pa.off),ze.querySelectorAll(".cc-sw").forEach(z=>{z.disabled=Pa.off,z.setAttribute("aria-checked",String(!Pa.muted.includes(z.dataset.key||"")))})};Le.onclick=()=>{Pa.off=Le.getAttribute("aria-checked")==="true",Le.setAttribute("aria-checked",String(!Pa.off)),f2(),ge(),ye(Pa.off?"Agent pop-ups are off":"Agent pop-ups are on","ok",1800)},Oe("/api/keys").then(z=>{if(n!==ru)return;const j=Array.isArray(z)?z:z.keys||[];if(Sd(j),!j.length){ze.innerHTML='<span class="st-tk-empty">No agents connected yet.</span>';return}ze.innerHTML=j.map((ce,I)=>{const U=ce.name||ce.id;return`<div class="st-tk"><span class="dot" style="background:${x(An(U,ce.id))}"></span><span class="nm" id="sTk${I}">${x(U)}${ce.enabled===!1?" <em>turned off</em>":""}</span>${Ed("sTkSw"+I,!0,"Pop-ups for "+U,` aria-labelledby="sTk${I}" data-key="${x(ce.id)}"`)}</div>`}).join(""),ze.querySelectorAll(".cc-sw").forEach(ce=>{ce.onclick=()=>{if(Pa.off)return;const I=ce.dataset.key||"",U=new Set(Pa.muted);U.has(I)?U.delete(I):U.add(I),Pa.muted=[...U],f2(),ge()}}),ge()}).catch(()=>{n===ru&&(ze.innerHTML='<span class="st-tk-empty">The agent list could not be loaded. Reload the page to try again.</span>')}),t.querySelector("#sClearPins").onclick=()=>{ue.confirm("Remove all pins?","The Pinned list empties on every browser and device. The notes and folders themselves stay where they are.","Remove all pins",()=>{ue.close(),jR().then(()=>{Vr(),Ol().length||ye("Pins removed","ok")})})},t.querySelector("#sClearIdx").onclick=()=>{Bv(),N.tags.built=!1,N.tags.index=null,ye("Tag list cleared. It is rebuilt the next time tags are used.","ok")},lY(t),sY(t),zj(t)}async function sY(t){const e=t.querySelector("#sImgStore"),n=t.querySelector("#sImgForm");if(!e||!n)return;const a=t.querySelector("#sImgMb"),i=o=>o<1048576?`${Math.max(.1,o/1024).toFixed(1)} KB`:`${(o/1048576).toFixed(1)} MB`;try{const o=await Oe("/api/vault/storage");if(!t.contains(e))return;e.innerHTML=`<div class="st-figs"><div><small>Notes</small><b>${i(o.note_bytes)}</b><span>${o.notes.toLocaleString("en-US")} files</span></div><div><small>Images</small><b>${i(o.image_bytes)}</b><span>${o.images.toLocaleString("en-US")} files</span></div><div><small>Together</small><b>${i(o.total_bytes)}</b></div></div>`,a.value=String(Math.round(o.max_image_bytes/1048576*10)/10)}catch(o){e.innerHTML=`<span class="st-note">Could not count the storage: ${x(o.message)}</span>`}n.onsubmit=async o=>{o.preventDefault();const s=Number(a.value);if(!(s>=.1&&s<=50)){ye("Choose between 0.1 and 50 MB","err");return}try{const r=await Ve("/api/settings/media",{max_image_mb:s});a.value=String(r.max_image_mb),ye(`Images can now be up to ${r.max_image_mb} MB`,"ok")}catch(r){ye(r.message,"err")}}}function QC(t){return t?new Date(t*1e3).toLocaleDateString(void 0,{day:"numeric",month:"short",year:"numeric"}):""}function rY(t,e,n){return!t||!t.lines?!1:t.bytes>e*1024*1024?!0:!!(n&&t.oldest&&t.oldest<Date.now()/1e3-n*86400)}async function lY(t){const e=t.querySelector("#sLogForm");if(!e)return;const n=t.querySelector("#sLogMb"),a=t.querySelector("#sLogDays"),i=Array.from(e.querySelectorAll("[data-days]")),o=()=>i.forEach(c=>c.setAttribute("aria-pressed",String(c.dataset.days===a.value))),s=c=>{const d=c.stats,p=d.max_bytes?Math.min(100,d.bytes/d.max_bytes*100):0,h=d.bytes>0?Math.max(1,Math.round(p/100*32)):0,u=t.querySelector("#sLogBar");u&&(u.style.width=(h/32*100).toFixed(3)+"%");const f=QC(d.oldest),v=(g,m)=>{const b=t.querySelector("#"+g);b&&(b.textContent=m)};v("sLogPct",`${p<1&&d.bytes>0?"Under 1":Math.round(p)}% used`),v("sLogCap",`Limit ${c.max_mb} MB`),v("sLogUsed",VC(d.bytes)),v("sLogOf",`of ${c.max_mb} MB`),v("sLogN",d.lines.toLocaleString()),v("sLogSince",f||"None yet"),v("sLogKeep",c.max_days?us(c.max_days,"day"):"No age limit")};let r=null;const l=c=>{r=c.stats,n.value=String(c.max_mb),a.value=String(c.max_days),o(),s(c)};i.forEach(c=>{c.onclick=()=>{a.value=c.dataset.days||"0",o(),Nt(t,"#sLogSt","")}}),a.oninput=()=>{o(),Nt(t,"#sLogSt","")},n.oninput=()=>Nt(t,"#sLogSt",""),e.onsubmit=c=>{c.preventDefault();const d=Math.round(Number(n.value)),p=Math.round(Number(a.value));if(!(d>=1&&d<=512))return Nt(t,"#sLogSt","error","Size: 1 to 512 MB");if(!(p>=0&&p<=3650))return Nt(t,"#sLogSt","error","Days: 0 to 3650");const h=t.querySelector("#sLogSave"),u=rY(r,d,p),f=()=>{h.disabled=!0,Nt(t,"#sLogSt","saving"),Ve("/api/logs/settings",{max_mb:d,max_days:p}).then(g=>{l(g),Nt(t,"#sLogSt","saved",u?"Saved. Older entries were removed.":"Saved")}).catch(g=>Nt(t,"#sLogSt","error",g.message)).finally(()=>h.disabled=!1)};if(!u||!r)return f();const v=QC(r.oldest);ue.confirm("Remove older activity now?",`The log holds ${r.lines.toLocaleString()} entries (${VC(r.bytes)}${v?", since "+v:""}). With a limit of ${d} MB${p?` and ${us(p,"day")}`:""}, the oldest entries are removed right away to fit. They cannot be brought back.`,"Save and remove",()=>{ue.close(),f()})};try{l(await Oe("/api/logs/settings"))}catch(c){const d=t.querySelector("#sLogPct");d&&(d.textContent="Could not read the log settings: "+c.message)}}const Av=`<p align="center">
|
|
12809
12829
|
<img src="docs/assets/memora-logo.png" alt="Memora" width="96" height="96">
|
|
12810
12830
|
</p>
|
|
12811
12831
|
|
|
@@ -13608,6 +13628,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
13608
13628
|
|
|
13609
13629
|
## [Unreleased]
|
|
13610
13630
|
|
|
13631
|
+
## [2.1.8] - 2026-11-17
|
|
13632
|
+
|
|
13633
|
+
\`@mnemo\` requests are never dropped.
|
|
13634
|
+
|
|
13635
|
+
### Fixed
|
|
13636
|
+
|
|
13637
|
+
- An \`@mnemo:\` request Mnemo could not answer (the AI provider or the
|
|
13638
|
+
network down, or no model yet) is no longer struck through with "Could
|
|
13639
|
+
not answer": it stays open in the note and is tried again after 1, 3, 10
|
|
13640
|
+
and 30 minutes, then hourly (up to about a day; any change to the note
|
|
13641
|
+
starts over). A retry runs the same message in the note's chat instead of
|
|
13642
|
+
asking twice, and only the answer to that request is written back.
|
|
13643
|
+
- What's new: the release row starts flush left and fades only on a side
|
|
13644
|
+
with more to scroll to; an arrow shows only where there is somewhere to go.
|
|
13645
|
+
- Opening Mnemo at \`/mnemo/<id>\` shows that chat's title right away instead
|
|
13646
|
+
of "New chat" while it loads.
|
|
13647
|
+
- Fresh ideas shows a shimmer on the button and placeholder cards while
|
|
13648
|
+
Mnemo writes, instead of a spinning icon.
|
|
13649
|
+
|
|
13611
13650
|
## [2.1.7] - 2026-11-17
|
|
13612
13651
|
|
|
13613
13652
|
Skills, fleeting chats, suggestions that change, and a note's chats that
|