vertigo 0.14.5

Reactive Real-DOM library with SSR for Rust
Documentation
1
2
const e=new TextDecoder("utf-8"),t=new TextEncoder;class n{constructor(e,t){this.getUint8Memory=e,this.pointer=0,this.ptr=Number(t>>32n),this.size=Number(t%2n**32n),this.dataView=new DataView(this.getUint8Memory().buffer,this.ptr,this.size)}getByte(){const e=this.dataView.getUint8(this.pointer);return this.pointer+=1,e}setByte(e){this.dataView.setUint8(this.pointer,e),this.pointer+=1}getU16(){const e=this.dataView.getUint16(this.pointer);return this.pointer+=2,e}setU16(e){this.dataView.setUint16(this.pointer,e),this.pointer+=2}getU32(){const e=this.dataView.getUint32(this.pointer);return this.pointer+=4,e}setU32(e){this.dataView.setUint32(this.pointer,e),this.pointer+=4}getF64(){const e=this.dataView.getFloat64(this.pointer);return this.pointer+=8,e}setF64(e){this.dataView.setFloat64(this.pointer,e),this.pointer+=8}getBuffer(){const e=this.getU32(),t=this.getUint8Memory().subarray(this.ptr+this.pointer,this.ptr+this.pointer+e);return this.pointer+=e,t}setBuffer(e){const t=e.length;this.setU32(t);this.getUint8Memory().subarray(this.ptr+this.pointer,this.ptr+this.pointer+t).set(e),this.pointer+=t}getString(){return e.decode(this.getBuffer())}setString(e){const n=t.encode(e);this.setBuffer(n)}}const s=1,o=2,r=3,i=4,a=5,c=6,l=7,d=8,h=9,u=e=>JSON.parse(e),f=e=>JSON.stringify(e,(e,t)=>t instanceof Uint8Array?Array.from(t):t),m=e=>{if(!0===e||!1===e||null==e)return 1;if("string"==typeof e)return 5+t.encode(e).length;if("number"==typeof e)return 9;if(e instanceof Uint8Array)return 5+e.length;if(Array.isArray(e)){let t=5;for(const n of e)t+=m(n);return t}if("object"==typeof e){let n=3;for(const[s,o]of Object.entries(e))n+=4+t.encode(s).length,n+=m(o);return n}throw new Error("jsJsonGetSize: Unknown type "+typeof e)},g=e=>{const t=e.getByte();if(t===s)return!0;if(t===o)return!1;if(t===r)return null;if(t!==i){if(t===a)return e.getString();if(t===c)return e.getF64();if(t===l){const t=e.getU32(),n=[];for(let s=0;s<t;s++)n.push(g(e));return n}if(t===d){const t=e.getU16(),n={};for(let s=0;s<t;s++){const t=e.getString(),s=g(e);n[t]=s}return n}if(t===h)return e.getBuffer().slice();throw new Error(`jsJsonDecodeItem: Unknown type id ${t}`)}},p=(e,t)=>{if(!0!==e)if(!1!==e)if(null!==e)if(void 0!==e){if("string"==typeof e)return t.setByte(a),void t.setString(e);if("number"==typeof e)return t.setByte(c),void t.setF64(e);if(e instanceof Uint8Array)return t.setByte(h),void t.setBuffer(e);if(!Array.isArray(e)){if("object"==typeof e){const n=Object.entries(e);t.setByte(d),t.setU16(n.length);for(const[e,s]of n)t.setString(e),p(s,t);return}throw new Error("saveJsJsonToBufferItem: Unknown type "+typeof e)}t.setByte(l),t.setU32(e.length);for(const n of e)p(n,t)}else t.setByte(i);else t.setByte(r);else t.setByte(o);else t.setByte(s)},w=new Map,v=async(e,t)=>{const s=await(async(e,t)=>{const n=await w.get(e);if(n)return{module:n,instance:await WebAssembly.instantiate(n,t)};if("function"==typeof WebAssembly.instantiateStreaming){const n=fetch(e);try{return await WebAssembly.instantiateStreaming(n,t)}catch(e){console.warn("`WebAssembly.instantiateStreaming` failed. This could happen if your server does not serve wasm with `application/wasm` MIME type, but check the original error too. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}}console.info("fetchModule by WebAssembly.instantiate");const s=await fetch(e),o=await s.arrayBuffer();return await WebAssembly.instantiate(o,t)})(e,t);let o=new Uint8Array(1);const r=()=>{if(s.instance.exports.memory instanceof WebAssembly.Memory)return o.buffer!==s.instance.exports.memory.buffer&&(o=new Uint8Array(s.instance.exports.memory.buffer)),o;throw Error("Missing memory")},i=s.instance.exports;return{exports:i,getUint8Memory:r,wasmCommand:e=>{const t=m(e),s=i.vertigo_export_alloc_block(t),o=new n(r,s);p(e,o);const a=i.vertigo_export_wasm_command(s);if(0n===a)return null;const c=new n(r,a),l=g(c);return i.vertigo_export_free_block(a),l}}};class b{constructor(){this.events=new Set}on(e){let t=!0;const n=n=>{t&&e(n)};return this.events.add(n),()=>{t=!1,this.events.delete(n)}}trigger(e){const t=Array.from(this.events.values());for(const n of t)try{n(e)}catch(e){console.error(e)}}}class y{constructor(){this.resolveFirst=null,this.resolve=e=>{const t=this.resolveFirst;this.resolveFirst=null,t?.(e)},this.isFulfilled=()=>null===this.resolveFirst,this.promise=new Promise(e=>{this.resolveFirst=e})}}const k=async(e,t)=>{console.info(`${e} wait ${t}ms`),await(async e=>new Promise(t=>{setTimeout(t,e)}))(t),console.info(`${e} go forth`)};class E{constructor(e){this.host=e,this.formatLog=e=>`Socket ${this.host} ==> ${e}`}}class T{constructor(e,t){this.eventMessage=new b,this.close=e,this.send=t}static connect(e,t,n){const s=new y,o=new y,r=new WebSocket(t);r.binaryType="arraybuffer";let i=!1;console.info(e.formatLog("starting ..."));const a=t=>{i||(console.info(e.formatLog("close")),i=!0,s.resolve(null),o.resolve({code:t?.code??1001,reason:t?.reason??""}),r.close())},c=new T(a,e=>{i||r.send(e)});setTimeout(()=>{s.isFulfilled()||(console.error(e.formatLog(`timeout (${n}ms)`)),a())},n);return r.addEventListener("open",()=>{console.info(e.formatLog("open")),s.resolve(c)}),r.addEventListener("error",t=>{i||console.error(e.formatLog("error"),t)}),r.addEventListener("close",a),r.addEventListener("message",e=>{if(i)return;const t=e.data;c.eventMessage.trigger("string"==typeof t?t:new Uint8Array(t))}),{close:a,socket:s.promise,done:o.promise}}static startSocket(e,t,n){let s=!0,o=()=>{};const r=new E(e);return(async()=>{for(;s;){const i=T.connect(r,e,t);o=i.close;const a=await i.socket;if(!s)return void console.info(r.formatLog("disconnect (3)"));let c;if(null===a)c=n({type:"close",code:1006,reason:"",connected:!1});else{n({type:"socket",socket:a}),a.eventMessage.on(e=>{n({type:"message",message:e})});const e=await i.done;if(c=n({type:"close",...e,connected:!0}),!s)return void console.info(r.formatLog("disconnect (1)"))}if("number"!=typeof c)return void console.info(r.formatLog("stop"));await k(r.formatLog("reconnect"),c)}console.info(r.formatLog("disconnect (2)"))})().catch(e=>{console.error(e)}),{dispose:()=>{s=!1,o()}}}}const C=e=>{try{return u(e)}catch{throw console.error("Failed to parse websocket message",e),Error(e)}},x=(e,t,n)=>e.wasmCommand({Websocket:{callback:t,message:n}});class A{constructor(e){this.websocket_register_callback=(e,t,n)=>{const s=()=>this.start(e,t,n);this.starts.set(t,s),s()},this.websocket_unregister_callback=e=>{const t=this.controllerList.get(e);void 0!==t?(t.dispose(),this.controllerList.delete(e),this.starts.delete(e)):console.error("Expected controller")},this.websocket_send_message=(e,t)=>{const n=this.socket.get(e);void 0===n?console.error(`Missing socket connection for callback_id=${e}`):n.send(t instanceof Uint8Array?t:f(t))},this.getWasm=e,this.controllerList=new Map,this.socket=new Map,this.starts=new Map,window.addEventListener("pagehide",e=>{if(e.persisted)for(const e of this.controllerList.values())e.dispose()}),window.addEventListener("pageshow",e=>{if(e.persisted)for(const e of this.starts.values())e()})}start(e,t,n){const s=this.getWasm();this.controllerList.get(t)?.dispose();const o=T.startSocket(e,n,e=>{if(this.controllerList.get(t)===o){if("socket"===e.type)return this.socket.set(t,e.socket),void x(s,t,"Connected");if("message"===e.type){const n=e.message;return void x(s,t,{Message:{message:"string"==typeof n?C(n):n}})}return"close"===e.type?(this.socket.delete(t),x(s,t,{Disconnected:{code:e.code,reason:e.reason,connected:e.connected}})):(e=>{throw console.error(e),Error("unknown message")})(e)}});this.controllerList.set(t,o)}}const _=e=>{const t={};for(const{k:n,v:s}of e)t[n]=s;return t},M=e=>{if("None"!==e)return f(e.Data.data)},N=e=>0===e.length?null:u(e),L=(e,t)=>{if((e=>"text/plain"===e?.split(";")[0]?.trim().toLowerCase())(e))return{Text:t};try{return{Json:N(t)}}catch{return{Text:t}}},S=async(e,t,n)=>{const s=e(),o=e=>{s.wasmCommand({FetchExecResponse:{response:e,callback:t}})};try{const e=await fetch(n.url,{method:n.method,headers:_(n.headers),body:M(n.body)});o(await(async e=>{const t=e.status,n=e.headers.get("Content-Type");try{return{Ok:{status:t,response:L(n,await e.text())}}}catch(e){return{Err:{message:String(e)}}}})(e))}catch(e){console.error("fetch error (1)",e);o({Err:{message:new String(e).toString()}})}};class R{constructor(e){this.timerSet=(e,t,n)=>{switch(n){case"Interval":{const n=setInterval(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Interval",timerId:n});break}case"Timeout":{const n=setTimeout(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Timeout",timerId:n});break}}},this.timerClear=e=>{const t=this.data.get(e);if(void 0===t)throw Error("panic");switch(t.kind){case"Interval":clearInterval(t.timerId);break;case"Timeout":clearTimeout(t.timerId)}},this.getWasm=e,this.data=new Map}}class U{constructor(e){this.request=null,this.start=()=>{null===this.request&&(this.request=requestAnimationFrame(this.frame))},this.stop=()=>{null!==this.request&&(cancelAnimationFrame(this.request),this.request=null)},this.frame=e=>{this.request=requestAnimationFrame(this.frame),this.getWasm().wasmCommand({AnimationFrame:{time:e}})},this.getWasm=e}}class I{constructor(e,t,n,s,o){this.getWasm=e,this.get=n,this.pushValue=s,this.replaceValue=o,this.callback=new Map,this.trigger=()=>{for(const e of Array.from(this.callback.values()))e()},this.add=e=>{this.callback.set(e,()=>{this.getWasm().wasmCommand({LocationCall:{callback:e,value:this.get()}})})},this.remove=e=>{this.callback.delete(e)},this.push=e=>{this.get()!==e&&this.pushValue(e,this.trigger)},this.replace=e=>{this.get()!==e&&this.replaceValue(e,this.trigger)},window.addEventListener(t,this.trigger)}}class ${constructor(e,t){this.mountPoint=t,this.callback=(e,t,n)=>{switch(t){case"Add":return void this.locations[e].add(n);case"Remove":return void this.locations[e].remove(n)}},this.set=(e,t,n)=>{switch(t){case"Push":return void this.locations[e].push(n);case"Replace":return void this.locations[e].replace(n)}},this.get=e=>this.locations[e].get(),this.locations={Hash:new I(e,"hashchange",()=>decodeURIComponent(location.hash.slice(1)),(e,t)=>{location.hash=e,t()},e=>{history.replaceState(null,"",`#${e}`)}),History:new I(e,"popstate",()=>window.location.pathname+window.location.search+window.location.hash,(e,t)=>{window.history.pushState(null,"",e),t()},(e,t)=>{window.history.replaceState(null,"",e),t()})}}}class B{constructor(){this.get=e=>{for(const t of document.cookie.split(";")){if(""===t)continue;const n=t.trim().split("=");if(2!==n.length){console.warn(`Cookies.get: Incorrect number of cookieChunk => ${n.length} in ${t}`);continue}const s=n[0],o=n[1];if(void 0!==s&&void 0!==o){if(s===e)return decodeURIComponent(o)}else console.warn(`Cookies.get: Broken cookie part => ${t}`)}return""},this.getJson=e=>{const t=this.get(e);if(0!==t.length)try{return u(t)}catch(e){console.error("Error deserializing cookie",e)}return null},this.set=(e,t,n)=>{const s=encodeURIComponent(t),o=new Date;o.setTime(o.getTime()+1e3*n);const r="expires="+o.toUTCString();document.cookie=`${e}=${s};${r};path=/; samesite=Strict`},this.setJson=(e,t,n)=>{const s=f(t);this.set(e,s,n)}}}const F=(e,t)=>{const n=t-e+1;return e+Math.floor(Math.random()*n)},W=e=>void 0!==e.languages&&e.languages.length>0?[...e.languages]:e.language?[e.language]:[],O=e=>e.arrayBuffer().then(t=>({name:e.name,data:new Uint8Array(t)}));const D=(e,t,n)=>{Promise.all(e).then(e=>{const n=[];for(const t of e)n.push([t.name,Array.from(t.data)]);t([n])}).catch(e=>{console.error(n,e)})},H=(e,t)=>{t(void 0)},P=(e,t)=>{e.preventDefault(),t(void 0)},z=(e,t)=>{t(void 0)&&e.preventDefault()},V=(e,t)=>{try{t()}catch(t){console.warn(e,t)}},K=(e,t,n)=>{null===t||"object"!=typeof t||Array.isArray(t)||("stop_propagation"in t&&!0===t.stop_propagation&&e.stopPropagation(),"prevent_default"in t&&!0===t.prevent_default&&e.preventDefault(),n&&"capture_pointer"in t&&!0===t.capture_pointer&&V("capture_pointer",n.capture),n&&"release_pointer"in t&&!0===t.release_pointer&&V("release_pointer",n.release))},q=e=>(t,n)=>{if(!(t instanceof PointerEvent&&e instanceof Element))throw Error("#pointer");const s=e.getBoundingClientRect();K(t,n([t.pointerId,t.pointerType,t.isPrimary,t.button,t.buttons,t.clientX-s.left,t.clientY-s.top,s.width,s.height,t.altKey,t.ctrlKey,t.shiftKey,t.metaKey]),{capture:()=>{e.setPointerCapture(t.pointerId)},release:()=>{const e=t.target;e instanceof Element&&e.hasPointerCapture(t.pointerId)&&e.releasePointerCapture(t.pointerId)}})},G=(e,t)=>{q(e.currentTarget)(e,t)},J=(e,t)=>{t([e.scrollTop,e.scrollLeft,e.scrollWidth,e.scrollHeight,e.clientWidth,e.clientHeight])},j=e=>(t,n)=>{const s=t.target;s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||e&&s instanceof HTMLSelectElement?n(s.value):console.warn("event input ignore",s)},Y=(e,t)=>{if(e instanceof KeyboardEvent){return void(!0===t([e.key,e.code,e.altKey,e.ctrlKey,e.shiftKey,e.metaKey])&&(e.preventDefault(),e.stopPropagation()))}console.warn("keydown ignore",e)},X=["loadedmetadata","durationchange","timeupdate","progress","play","playing","pause","waiting","seeked","ended","volumechange","error"],Q=e=>{const{buffered:t,currentTime:n}=e;for(let e=0;e<t.length;e++)if(t.start(e)<=n&&n<=t.end(e))return t.end(e);return n},Z=(e,t,n)=>{n([t,e.currentTime,Number.isFinite(e.duration)?e.duration:null,e.paused,e.ended,e.muted,e.volume,Q(e)])};let ee=[];const te=e=>{ee?.push(e)};"undefined"!=typeof window&&window.addEventListener("message",te);const ne={click:(e,t)=>{const n=e.currentTarget;if(!(e instanceof MouseEvent&&n instanceof Element))throw Error("#click");let s=null;if(0!==e.detail){const t=n.getBoundingClientRect();s=[e.clientX-t.left,e.clientY-t.top,t.width,t.height]}K(e,t([e.altKey,e.ctrlKey,e.shiftKey,e.metaKey,s]))},submit:P,input:j(!1),change:j(!0),blur:H,focus:H,mousedown:z,mouseup:z,mouseenter:H,mouseleave:H,keydown:Y,drop:(e,t)=>{if(e.preventDefault(),e instanceof DragEvent)if(null===e.dataTransfer)console.error("dom -> drop -> dataTransfer null");else{const n=function(e){const t=[];for(let n=0;n<e.length;n++){const s=e[n];if(void 0===s)console.error("dom -> drop -> item - undefined");else{const e=s.getAsFile();null===e?console.error(`dom -> drop -> index:${n} -> It's not a file`):t.push(O(e))}}return t}(e.dataTransfer.items);n.length?D(n,t,"callback_drop -> promise.all -> "):console.error("No files to send")}else console.warn("event drop ignore",e)},load:P,change_file:(e,t)=>{const n=e.target;if(n instanceof HTMLInputElement&&null!==n.files&&n.files.length>0){const e=[];for(let t=0;t<n.files.length;t++){const s=n.files[t];void 0!==s&&e.push(O(s))}return void(e.length>0&&D(e,t,"changeFile ->"))}console.warn("changeFile: not a file input or no files",n)},change_checked:(e,t)=>{const n=e.target;n instanceof HTMLInputElement?t(n.checked):console.warn("changeChecked: not an input",n)},wheel:(e,t)=>{const n=e.currentTarget;if(!(e instanceof WheelEvent&&n instanceof Element))throw Error("#wheel");const s=n.getBoundingClientRect();K(e,t([e.deltaX,e.deltaY,e.deltaZ,e.deltaMode,e.clientX-s.left,e.clientY-s.top,s.width,s.height,e.altKey,e.ctrlKey,e.shiftKey,e.metaKey]))},scroll:(e,t)=>{const n=e.currentTarget;if(!(n instanceof Element))throw Error("#scroll");J(n,t)},pointerdown:G,pointermove:G,pointerup:G,pointercancel:G},se={hook_keydown:["keydown",()=>Y],hook_pointermove:["pointermove",q],hook_pointerup:["pointerup",q],hook_pointercancel:["pointercancel",q]},oe=e=>"change_file"===e||"change_checked"===e?"change":e;class re{constructor(e){this.getWasm=e,this.callbacks=new Map,this.observers=new Map}add(e,t,n,s){if("intersect"===n)return void this.intersectAdd(e,t,s);if("resize"===n)return void this.resizeAdd(e,t,s);const o=e=>this.wasmCallback(s,e),r=e=>{const t=ne[n];void 0!==t?t(e,o):console.error(`No support for the event ${n}`)};if(this.callbacks.has(s))return void console.error(`There was already a callback added with the callback_id=${s}`);if("media"===n){const n=e.get("callback_add",t);if(!(n instanceof HTMLMediaElement))throw Error(`on_media: expected id=${t} as HTMLMediaElement`);const r=e=>Z(n,e.type,o);return this.callbacks.set(s,r),X.forEach(e=>n.addEventListener(e,r,!1)),void(null!==n.error?queueMicrotask(()=>Z(n,"error",o)):n.readyState>=1&&queueMicrotask(()=>Z(n,"loadedmetadata",o)))}if("message"===n){const n=e.get("callback_add",t);if(!(n instanceof HTMLIFrameElement))throw Error(`on_message: expected id=${t} as HTMLIFrameElement`);const r=e=>{e instanceof MessageEvent&&null!==e.source&&e.source===n.contentWindow&&((e,t)=>{let n;try{n=u(f(e.data)??"null")}catch{n=null}t([e.origin,n])})(e,o)};this.callbacks.set(s,r),window.addEventListener("message",r,!1);const i=[...ee??[]];return void(i.length>0&&queueMicrotask(()=>i.forEach(r)))}const i=se[n];if(void 0!==i){const[n,r]=i,a=r(e.getNode("callback_add",t)),c=e=>{a(e,o)};return this.callbacks.set(s,c),void document.addEventListener(n,c,!1)}this.callbacks.set(s,r);const a=e.get("callback_add",t);a.addEventListener(oe(n),r,"wheel"===n&&{passive:!1}),"scroll"===n&&e.hasInitNodes()&&queueMicrotask(()=>{a instanceof Element&&(0!==a.scrollTop||0!==a.scrollLeft)&&J(a,o)})}remove(e,t,n,s){if("intersect"===n||"resize"===n)return void this.observerRemove(s);const o=this.callbacks.get(s);if(this.callbacks.delete(s),void 0===o)return void console.error(`The callback is missing with the id=${s}`);const r=se[n];if("media"===n){const n=e.get("callback_remove",t);X.forEach(e=>n.removeEventListener(e,o))}else if("message"===n)window.removeEventListener("message",o);else if(void 0!==r)document.removeEventListener(r[0],o);else{e.get("callback_remove",t).removeEventListener(oe(n),o)}}forgetEarlyMessages(){null!==ee&&(window.removeEventListener("message",te),ee=null)}wasmCallback(e,t){return this.getWasm().wasmCommand({CallbackCall:{callback_id:e,value:t}})}intersectAdd(e,t,n){if(this.observers.has(n))return void console.error(`There was already an intersect observer added with the callback_id=${n}`);const s=e.getNode("callback_add",t),o=new IntersectionObserver(e=>{for(const t of e)this.wasmCallback(n,[t.isIntersecting,t.intersectionRatio,t.boundingClientRect.top,t.boundingClientRect.bottom,t.boundingClientRect.height])});o.observe(s),this.observers.set(n,o)}resizeAdd(e,t,n){if(this.observers.has(n))return void console.error(`There was already a resize observer added with the callback_id=${n}`);const s=e.getNode("callback_add",t),o=new ResizeObserver(()=>{const e=s.getBoundingClientRect();this.wasmCallback(n,[e.width,e.height])});o.observe(s,{box:"border-box"}),this.observers.set(n,o)}observerRemove(e){const t=this.observers.get(e);this.observers.delete(e),void 0!==t?t.disconnect():console.error(`The observer is missing with the id=${e}`)}}function ie(e,t){e.addEventListener("click",n=>{const s=e.getAttribute("href");if(null===s||s.startsWith("#"))return;if(!((o=n)instanceof MouseEvent&&0===o.button)||o.ctrlKey||o.metaKey||o.shiftKey||o.altKey||e.hasAttribute("download")||!function(e){const t=e.getAttribute("target");return null===t||""===t||"_self"===t}(e))return;var o;const r=function(e,t,n){if(e.matches('[rel~="external" i]'))return null;let s;try{s=new URL(t,document.baseURI)}catch{return null}if(s.protocol!==window.location.protocol||s.host!==window.location.host)return null;const o=n.replace(/\/+$/,"");if(""!==o&&s.pathname!==o&&!s.pathname.startsWith(`${o}/`))return null;return s.pathname+s.search+s.hash}(e,s,t.mountPoint);null!==r&&(n.preventDefault(),t.set("History","Push",r),function(e){const t=le(e),n=fe(t);if(ce=null,null!==n)return void ue(n);window.scrollTo(0,0),""!==t&&"top"!==ge(t).toLowerCase()&&de(e,t)}(r))})}const ae=1e4;let ce=null;function le(e){const t=e.indexOf("#");return-1===t?"":e.slice(t+1)}function de(e,t){ce={path:e,fragment:t,until:Date.now()+ae,scrollY:window.scrollY}}function he(){if(null===ce)return;if(window.location.pathname+window.location.search+window.location.hash!==ce.path||window.scrollY>ce.scrollY||Date.now()>ce.until)return void(ce=null);ce.scrollY=window.scrollY;const e=fe(ce.fragment);null!==e&&(ce=null,ue(e))}function ue(e){for(let t=e;null!==t;t=t.parentElement){"until-found"===t.getAttribute("hidden")?.toLowerCase()&&(t.dispatchEvent(new Event("beforematch",{bubbles:!0})),t.removeAttribute("hidden"));const e=t.parentElement;"DETAILS"===e?.tagName&&t!==e.querySelector(":scope > summary")&&e.setAttribute("open","")}e.scrollIntoView()}function fe(e){return""===e?null:me(e)??me(ge(e))}function me(e){return document.getElementById(e)??Array.from(document.getElementsByName(e)).find(e=>"A"===e.tagName)??null}function ge(e){try{return decodeURIComponent(e)}catch{return e}}const pe=new Set(["animate","animateMotion","animateTransform","circle","clipPath","defs","desc","discard","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","hatch","hatchpath","image","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tspan","use","view","svg:a","svg:title","svg:desc","svg:script","svg:style"]);class we{constructor(e,t,n){this.depth=-1,this.matched=0,this.discarded=0,this.nodes=t,this.appLocation=n,this.virtualNodes=this.createVirtualNodes(e)}hydrate(){const e=this.virtualNodes.get(3),t=this.virtualNodes.get(2);e&&(this.hydrateNode(3,document.body),t&&this.hydrateNode(2,document.head));const n={rootFound:void 0!==e,matched:this.matched,...this.countHydratable(),total:this.virtualNodes.size,discarded:this.discarded};if(!e)return console.error("Hydration skipped: the first DOM batch carries no <body> (node id 3), so the server-rendered markup cannot be matched and will be replaced. The app flushed DOM changes before the root element was built - see `mount` in exports.rs.",n),this.publish(n),n;const s=0===n.hydratable?"100.00":(100*n.matched/n.hydratable).toFixed(2),o=`Hydration complete: ${n.matched}/${n.hydratable} matched (${s}%), ${n.discarded} server nodes discarded, ${n.skipped} markers skipped, ${n.total} vnodes in batch.`;return n.matched<n.hydratable||n.discarded>0?console.warn(o):console.log(o),this.publish(n),n}publish(e){try{window.__vertigo_hydration=e}catch(e){}}countHydratable(){let e=0,t=0;const n=new Set,s=(o,r)=>{if(n.has(o))return;n.add(o);const i=this.virtualNodes.get(o);if(r||(void 0===i||void 0===i.name&&!(e=>void 0!==e.value&&""!==e.value)(i)?t++:e++),i)for(const e of i.children)s(e,!1)};return s(3,!0),s(2,!0),{hydratable:e,skipped:t}}hydrateNode(e,t){const n=this.virtualNodes.get(e);if(!n)return;const s=Array.from(t.childNodes);let o=0;this.depth++;let r=!1;for(const e of n.children){const t=this.virtualNodes.get(e);if(t&&""!==t.value)if(r&&void 0!==t.value)this.matched++;else{r=!1;for(let n=o;n<s.length;n++){const i=s[n];if(!i)continue;let a=!1;if(t.name?a=this.checkElementMatch(i,t):void 0!==t.value&&(i.nodeType===Node.TEXT_NODE?(this.checkTextMatch(i,t),a=!0,r=!0):console.error(`Hydration ${this.depth}: Text node mismatch`,t,i)),a){this.removeSkippedNodes(s,o,n),this.claimNode(i,e),this.matched++,t.name&&this.hydrateNode(e,i),o=n+1;break}}}}this.removeSkippedNodes(s,o,s.length),this.depth--}checkElementMatch(e,t){let n=!1;const s=void 0===t.name?void 0:(o=t.name,pe.has(o)?o.replace("svg:",""):o.toUpperCase());var o;if(e.nodeType===Node.ELEMENT_NODE&&e.tagName===s){n=!0;const s=e,o=t.attributes;for(const e of s.getAttributeNames())o&&o.has(e)||"open"===e&&"DETAILS"===s.tagName||s.removeAttribute(e);if(o)for(const[e,t]of o)s.getAttribute(e)!==t&&s.setAttribute(e,t)}return n}checkTextMatch(e,t){e.textContent?.replace("\n"," ").trim()!==t.value?.replace("\n"," ").trim()&&(e.textContent=t.value||"")}claimNode(e,t){var n,s;(e instanceof Element||e instanceof Comment||e instanceof Text)&&(this.nodes.claimNode(t,e),e instanceof Element&&(n=e,s=this.appLocation,"a"===n.tagName.toLowerCase()&&ie(n,s)))}place(){for(const e of[...this.virtualNodes.values()].reverse()){const t=this.nodes.getAnyOption(e.id);if(!t)continue;const n=1===e.id;let s=t.firstChild;for(const o of e.children){const e=this.nodes.getAnyOption(o);e&&(e===s||n&&e.parentNode===t?s=e.nextSibling:t.insertBefore(e,s))}}}removeSkippedNodes(e,t,n){for(let s=t;s<n;s++){const t=e[s];t&&(0!==this.depth&&t.nodeType!==Node.TEXT_NODE&&(console.warn(`Hydration ${this.depth}: Removing node`,t),this.discarded++),t.remove())}}createVirtualNodes(e){const t=new Map,n=e=>{let n=t.get(e);return n||(n={id:e,children:[]},t.set(e,n)),n},s=new Map,o=e=>{const t=s.get(e);t&&(t.children.splice(t.children.indexOf(e),1),s.delete(e))},r=e=>{o(e),t.delete(e)};for(const i of e)if("CreateNode"in i){n(i.CreateNode.id).name=i.CreateNode.name}else if("CreateText"in i){n(i.CreateText.id).value=i.CreateText.value}else if("UpdateText"in i){n(i.UpdateText.id).value=i.UpdateText.value}else if("InsertBefore"in i){const e=n(i.InsertBefore.parent),t=e.children,r=i.InsertBefore.child,a=i.InsertBefore.ref_id;if(o(r),s.set(r,e),null===a)t.push(r);else{const e=t.length-1,n=t[e]===a?e:t.indexOf(a);-1!==n?t.splice(n,0,r):(console.warn(`Hydration: ref_id ${a} not found in parent ${i.InsertBefore.parent}`),t.push(r))}}else if("SetAttr"in i){const e=n(i.SetAttr.id);e.attributes||(e.attributes=new Map),e.attributes.set(i.SetAttr.name,i.SetAttr.value)}else"RemoveAttr"in i?t.get(i.RemoveAttr.id)?.attributes?.delete(i.RemoveAttr.name):"RemoveNode"in i?r(i.RemoveNode.id):"RemoveText"in i?r(i.RemoveText.id):"RemoveComment"in i&&r(i.RemoveComment.id);return t}}const ve=1,be=2,ye=3,ke=4,Ee=5,Te=6,Ce=7,xe=8,Ae=9,_e=10,Me=11,Ne=12,Le=13,Se=14;class Re{constructor(e){this.bytes=e,this.at=0}isEmpty(){return this.at>=this.bytes.length}where(){return`offset ${this.at} of ${this.bytes.length}`}byte(){const e=this.bytes[this.at];if(void 0===e)throw new Error("dom command: buffer ended early");return this.at+=1,e}varint(){let e=0,t=1;for(;;){const n=this.byte();if(e+=(127&n)*t,!(128&n))return e;t*=128}}string(){return e.decode(this.bytesView())}bytesView(){const e=this.varint(),t=this.at+e;if(t>this.bytes.length)throw new Error("dom command: bytes run past the end of the buffer");const n=this.bytes.subarray(this.at,t);return this.at=t,n}name(e){const t=this.varint(),n=e[t];if(void 0===n)throw new Error(`dom command: name index ${t} is not in the dictionary`);return n}optionalId(){const e=this.varint();return 0===e?null:e}}const Ue=e=>{const t=e.varint(),n=[];for(let s=0;s<t;s++)n.push(e.string());return n},Ie=e=>e.varint(),$e=e=>e.string(),Be=(e,t)=>e.name(t),Fe={[ve]:["CreateNode",[["id",Ie],["name",Be]]],[be]:["CreateText",[["id",Ie],["value",$e]]],[ye]:["UpdateText",[["id",Ie],["value",$e]]],[ke]:["SetAttr",[["id",Ie],["name",Be],["value",$e]]],[Ee]:["RemoveAttr",[["id",Ie],["name",Be]]],[Te]:["RemoveNode",[["id",Ie]]],[Ce]:["RemoveText",[["id",Ie]]],[xe]:["InsertBefore",[["parent",Ie],["child",Ie],["ref_id",e=>e.optionalId()]]],[Ae]:["InsertCss",[["selector",e=>0===e.byte()?null:e.string()],["value",$e]]],[_e]:["CreateComment",[["id",Ie],["value",$e]]],[Me]:["RemoveComment",[["id",Ie]]],[Ne]:["CallbackAdd",[["id",Ie],["event_name",$e],["callback_id",Ie]]],[Le]:["CallbackRemove",[["id",Ie],["event_name",$e],["callback_id",Ie]]],[Se]:["CanvasDraw",[["id",Ie],["drawing",e=>e.bytesView().slice()]]]};class We{constructor(){this.data=new Map,this.initNodes=[...this.getRootHead().childNodes,...this.getRootBody().childNodes],this.style=document.createElement("style")}getRootHtml(){return document.documentElement}getRootHead(){return document.head}getRootBody(){return document.body}set(e,t){1===e||2===e||3===e||this.data.set(e,t)}getAnyOption(e){return 1===e?this.getRootHtml():2===e?this.getRootHead():3===e?this.getRootBody():this.data.get(e)}getAny(e,t){const n=this.getAnyOption(t);if(void 0===n)throw Error(`${e} -> item not found=${t}`);return n}get(e,t){const n=this.getAnyOption(t);if(void 0===n)throw new Error(`${e}->get: Item id not found = ${t}`);return n}expect(e,t,n,s){const o=this.get(e,t);if(o instanceof n)return o;throw Error(`Expected id=${t} as ${s}`)}getNode(e,t){return this.expect(e,t,Element,"Element")}getText(e,t){return this.expect(e,t,Text,"Text")}delete(e,t){const n=this.getAnyOption(t);if(this.data.delete(t),void 0===n)throw new Error(`${e}->delete: Item id not found = ${t}`);return n}insertCss(e,t){if(null!==e){const n=document.createTextNode(`\n${e} { ${t} }`);this.style.appendChild(n)}else{const e=document.createTextNode(`\n${t}`);this.style.appendChild(e)}}removeInitNodes(){const e=this.initNodes;if(this.initNodes=null,null!==e)for(const t of e)t.remove()}insertBefore(e,t,n){const s=this.get("insert_before",e),o=this.getAny("insert_before child",t);if(null==n)s.insertBefore(o,null);else{const e=this.getAny("insert_before ref",n);s.insertBefore(o,e)}}addStyles(){const e=this.getRootHead();e.lastChild!==this.style&&e.appendChild(this.style)}hasInitNodes(){return null!==this.initNodes}claimNode(e,t){if(this.data.set(e,t),this.initNodes){const e=this.initNodes.indexOf(t);e>-1&&this.initNodes.splice(e,1)}}has(e){return 1===e||2===e||3===e||this.data.has(e)}}const Oe=1,De=2,He=3,Pe=4,ze=5,Ve=6,Ke=7,qe=8,Ge=9,Je=10,je=11,Ye=12,Xe=13,Qe=14,Ze=15,et=16,tt=17,nt=18,st=19,ot=20,rt=21,it=22,at=23,ct=24,lt=25,dt=26,ht=27,ut=28,ft=29,mt=30,gt=31,pt=32,wt=33,vt=34,bt=35,yt=36,kt=37,Et=38,Tt=39,Ct=40,xt=41,At=42,_t=43,Mt=44,Nt=45,Lt=0,St=1,Rt=2,Ut=3,It=4,$t=5,Bt=6,Ft=["butt","round","square"],Wt=["miter","round","bevel"],Ot=["low","medium","high"],Dt=(e,t,n)=>{const s=document.createElement("canvas");return s.width=t,s.height=n,s.getContext("2d")?.putImageData(new ImageData(new Uint8ClampedArray(e),t,n),0,0),s},Ht=(e,t)=>e.replace(/(\d*\.?\d+(?:e[+-]?\d+)?)px/gi,(e,n)=>Number(n)*t+"px"),Pt=(t,n,s,o,r,i=()=>null,a=Dt)=>{const c=new DataView(n.buffer,n.byteOffset,n.byteLength);let l=0;const d=()=>{const e=c.getFloat32(l,!0);return l+=4,e},h=()=>{const e=c.getUint32(l,!0);return l+=4,e},u=()=>{const t=c.getUint16(l,!0),s=e.decode(n.subarray(l+2,l+2+t));return l+=2+t,s},f=()=>{t.globalAlpha=1,t.fillStyle="#000",t.strokeStyle="#000",t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.setLineDash([]),t.lineDashOffset=0,t.font="10px sans-serif",t.textAlign="start",t.textBaseline="alphabetic",t.globalCompositeOperation="source-over",t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0,t.filter="none",t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="low"};t.save();let m=0,g=!1;try{t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,s,o),f();let p=r,w=[r,0,0,r,0,0];if(1===c.getUint8(l++)){const e=d(),t=d(),n=d(),r=d();p=[e,t,n,r].every(isFinite)&&n>0&&r>0?Math.min(s/n,o/r):NaN,w=[p,0,0,p,(s-n*p)/2-e*p,(o-r*p)/2-t*p]}if(t.setTransform(...w),!(p>0&&isFinite(p)))return!1;let v=p;const b=()=>{if(null===v){const{a:e,b:n,c:s,d:o}=t.getTransform();v=Math.sqrt(Math.abs(e*o-n*s))}return v},y=()=>r/b(),k=(e,n)=>{t.beginPath();for(let n=0;n<e;n++){const e=d(),s=d();0===n?t.moveTo(e,s):t.lineTo(e,s)}n&&t.closePath()},E=()=>{const t=new Path2D((()=>{const t=h(),s=e.decode(n.subarray(l,l+t));return l+=t,s})());for(let e=h();e>0;e--){const e=c.getUint8(l++);switch(e){case Lt:t.moveTo(d(),d());break;case St:t.lineTo(d(),d());break;case Rt:t.quadraticCurveTo(d(),d(),d(),d());break;case Ut:t.bezierCurveTo(d(),d(),d(),d(),d(),d());break;case It:t.arcTo(d(),d(),d(),d(),Math.max(d(),0));break;case $t:t.ellipse(d(),d(),Math.max(d(),0),Math.max(d(),0),d(),d(),d(),1===c.getUint8(l++));break;case Bt:t.closePath();break;default:throw new Error(`canvas: unknown path command ${e} at byte ${l-1}`)}}return t},T=()=>1===c.getUint8(l++)?"evenodd":"nonzero",C=e=>{Reflect.set(t,e,u())},x=new Map,A=(e,n)=>{const s=`${n} ${e}`;if(!x.has(s)){const o=i(e),r=null===o?null:t.createPattern(o,"repeat");r?.setTransform({a:n,b:0,c:0,d:n,e:0,f:0}),x.set(s,r)}return x.get(s)??null},_=(e,n)=>{0===e?t.fillStyle=n:t.strokeStyle=n},M=(e,t,n)=>{let s=null;try{s=t()}catch{}let o=null;const r=c.getUint16(l,!0);l+=2;for(let e=0;e<r;e++){const e=Math.min(Math.max(d(),0),1),t=u();if(null!==s&&!Number.isNaN(e))try{s.addColorStop(e,t),(null===o||e>=o.offset)&&(o={offset:e,color:t})}catch{}}null!==s&&_(e,n&&null!==o?o.color:s)},N=e=>{const n=u(),s=d(),o=d(),r=b();g=!0,[s,o,r].every(isFinite)&&r>0&&(t.save(),t.translate(s,o),t.scale(1/r,1/r),t.font=Ht(t.font,r),0===e?t.fillText(n,0,0):(t.lineWidth*=r,t.strokeText(n,0,0)),t.restore())},L=(e,n,s)=>{t.beginPath(),t.arc(e,n,Math.max(s,0),0,2*Math.PI)};for(;l<n.length;){const e=c.getUint8(l++);switch(e){case Oe:t.fillStyle=u();break;case De:t.strokeStyle=u();break;case He:t.globalAlpha=d();break;case Pe:t.lineWidth=d();break;case ze:t.lineWidth=d()*y();break;case Ve:t.lineCap=Ft[c.getUint8(l++)]??"butt";break;case Ye:t.lineJoin=Wt[c.getUint8(l++)]??"miter";break;case Ct:t.miterLimit=d();break;case Tt:{const e=1===c.getUint8(l++)?y():1,n=c.getUint16(l,!0);l+=2,t.setLineDash(Array.from({length:n},()=>d()*e)),t.lineDashOffset=d()*e;break}case Ke:t.fillRect(d(),d(),d(),d());break;case mt:t.strokeRect(d(),d(),d(),d());break;case gt:t.clearRect(d(),d(),d(),d());break;case qe:L(d(),d(),d()),t.fill();break;case Ge:L(d(),d(),d()*y()),t.fill();break;case Je:L(d(),d(),d()),t.stroke();break;case je:{const e=h();k(e,!1),e>1&&t.stroke();break}case Xe:{const e=h();k(e,!0),e>2&&t.fill();break}case Qe:{const e=h();k(e,!0),e>2&&t.stroke();break}case ht:{const e=T();t.fill(E(),e);break}case ut:t.stroke(E());break;case ft:{const e=T();t.clip(E(),e);break}case Ze:{const e=i(u()),[n,s,o,r,a,c,l,h]=[d(),d(),d(),d(),d(),d(),d(),d()];null!==e&&t.drawImage(e,n,s,o,r,a,c,l,h);break}case Nt:{const e=h(),s=h(),[o,r,i,c]=[d(),d(),d(),d()],u=e*s*4,f=a(n.subarray(l,l+u),e,s);l+=u,null!==f&&t.drawImage(f,o,r,i,c);break}case et:{const e=c.getUint8(l++),t=u(),n=d(),s=0!==n&&isFinite(n)?A(t,n):null;null!==s&&_(e,s);break}case tt:{const e=c.getUint8(l++),[n,s,o,r]=[d(),d(),d(),d()];M(e,()=>t.createLinearGradient(n,s,o,r),n===o&&s===r);break}case kt:{const e=c.getUint8(l++),[n,s,o,r,i,a]=[d(),d(),d(),d(),d(),d()];M(e,()=>t.createRadialGradient(n,s,o,r,i,a),n===r&&s===i&&o===a);break}case Et:{const e=c.getUint8(l++),[n,s,o]=[d(),d(),d()];M(e,()=>t.createConicGradient(n,s,o),!1);break}case pt:t.font=u();break;case wt:t.font=Ht(u(),y());break;case vt:C("textAlign");break;case bt:C("textBaseline");break;case yt:N(c.getUint8(l++));break;case xt:C("globalCompositeOperation");break;case At:t.shadowColor=u(),t.shadowBlur=d()*r,t.shadowOffsetX=d()*r,t.shadowOffsetY=d()*r;break;case _t:t.filter=Ht(u(),r);break;case Mt:{const e=c.getUint8(l++);t.imageSmoothingEnabled=e>0,t.imageSmoothingQuality=Ot[e-1]??"low";break}case ot:t.save(),m++;break;case nt:t.save(),m++,f();break;case rt:case st:m>0&&(t.restore(),m--,v=null);break;case it:t.translate(d(),d());break;case at:t.rotate(d());break;case ct:t.scale(d(),d()),v=null;break;case lt:t.transform(d(),d(),d(),d(),d(),d()),v=null;break;case dt:t.setTransform(...w),v=p;break;default:throw new Error(`canvas: unknown operation ${e} at byte ${l-1}`)}}return g}finally{for(;m>0;m--)t.restore();t.restore()}};class zt{constructor(e,t){this.kept=e,this.loaded=t,this.images=new Map,this.waiting=new Map,this.used=new Map,this.unused=new Set}load(e){let t=this.images.get(e);return void 0===t&&(t=new Image,t.onload=()=>{const t=this.waiting.get(e)??new Set;this.waiting.delete(e);for(const e of t)this.loaded(e)},t.onerror=()=>{this.waiting.delete(e),console.error(`canvas: the image ${e} failed to load`)},t.src=e,this.images.set(e,t)),t}preload(e){this.load(e),this.unused.delete(e)}get(e,t){const n=this.load(e);if(n.complete)return n.naturalWidth>0?n:null;const s=this.waiting.get(e)??new Set;return s.add(t),this.waiting.set(e,s),null}use(e,t){const n=this.used.get(e)??[];this.used.set(e,t);for(const e of t)this.unused.delete(e);const s=[...this.used.values()];for(const e of n)s.some(t=>t.has(e))||this.unused.add(e);for(const e of this.unused){if(this.unused.size<=this.kept)break;this.unused.delete(e);const t=this.images.get(e);void 0!==t&&(t.onload=null,t.onerror=null,this.images.delete(e)),this.waiting.delete(e)}}forget(e){for(const t of this.waiting.values())t.delete(e);this.use(e,new Set),this.used.delete(e)}}class Vt{constructor(e=64){this.drawings=new WeakMap,this.sizes=new WeakMap,this.unscaled=new WeakSet,this.drawn=new Set,this.writing=new Set,this.listening=!1,this.observer=null,this.images=new zt(e,e=>this.repaint(e))}draw(e,t){if(!(e instanceof HTMLCanvasElement))throw new Error("draw: the element is not a canvas");const n=this.drawings.has(e);this.drawings.set(e,t.slice()),n||this.observe(e),this.drawn.add(e)}paintDrawn(){for(const e of this.drawn)this.repaint(e);this.drawn.clear()}preload(e){this.images.preload(e)}forget(e){e instanceof HTMLCanvasElement&&this.drawings.has(e)&&(this.observer?.unobserve(e),this.drawings.delete(e),this.sizes.delete(e),this.unscaled.delete(e),this.drawn.delete(e),this.writing.delete(e),this.images.forget(e))}observe(e){if("undefined"!=typeof ResizeObserver){null===this.observer&&(this.observer=new ResizeObserver(e=>{for(const t of e){const e=t.target;if(!(e instanceof HTMLCanvasElement))throw Error("#canvas");const n=window.devicePixelRatio||1;this.sizes.set(e,{width:Math.round(t.contentRect.width*n),height:Math.round(t.contentRect.height*n),ratio:n}),this.repaint(e)}}));try{this.observer.observe(e,{box:"device-pixel-content-box"})}catch{this.observer.observe(e)}}}wrote(e,t){t?(this.writing.add(e),this.listening||"undefined"==typeof document||(this.listening=!0,document.fonts.addEventListener("loadingdone",()=>{for(const e of[...this.writing])this.repaint(e)}))):this.writing.delete(e)}repaint(e){const t=this.drawings.get(e);if(void 0!==t)try{this.paint(e,t)}catch(e){console.error(e)}}size(e){if(this.unscaled.has(e))return{width:e.width,height:e.height,ratio:1};const t=window.devicePixelRatio||1,n=this.sizes.get(e)??(e.isConnected?{width:Math.round(e.clientWidth*t),height:Math.round(e.clientHeight*t),ratio:t}:null);return null!==n&&n.width>0&&n.height>0?n:null}paint(e,t){let n=this.size(e);if(null===n)return;if(e.width!==n.width||e.height!==n.height){const[t,s]=[e.width,e.height],[o,r]=[e.clientWidth,e.clientHeight];e.width!==n.width&&(e.width=n.width),e.height!==n.height&&(e.height=n.height),1!==n.ratio&&e.clientWidth-o===n.width-t&&e.clientHeight-r===n.height-s&&(e.width=t,e.height=s,this.unscaled.add(e),n={width:t,height:s,ratio:1})}const s=e.getContext("2d");if(null!==s){const o=new Set;let r=!1;try{r=Pt(s,t,n.width,n.height,n.ratio,t=>(o.add(t),this.images.get(t,e)))}finally{this.images.use(e,o),this.wrote(e,r)}}}}const Kt=(e,t)=>{console.error("bulk_update - item",t,e)},qt=(e,t)=>e.findIndex(e=>e.toLowerCase()===t);class Gt{constructor(e,t,n){this.metadata=e,this.canvases=new Vt,this.update=e=>{const t=this.nodes.hasInitNodes()&&this.metadata.getEnabledHydration()?((e,t,n)=>{const s=new we(e,t,n);return{report:s.hydrate(),place:()=>s.place()}})((e=>{const t=new Re(e),n=Ue(t),s=[];for(;!t.isEmpty();){const e=t.byte(),o=Fe[e];if(void 0===o)throw new Error(`dom command: unknown tag ${e}`);const[r,i]=o,a={};for(const[e,s]of i)a[e]=s(t,n);s.push({[r]:a})}return s})(e),this.nodes,this.appLocation):null,n=t?.report.rootFound?t:null,s=new Re(e),o=Ue(s),r=qt(o,"autofocus"),i=qt(o,"a"),a=new Set;try{for(;!s.isEmpty();){const e=s.byte();switch(e){case ve:{const e=s.varint(),t=s.varint();try{this.createNode(e,o[t]??"",t===i)}catch(e){Kt(e,"CreateNode")}break}case be:{const e=s.varint(),t=s.string();try{this.createText(e,t)}catch(e){Kt(e,"CreateText")}break}case ye:{const e=s.varint(),t=s.string();try{this.updateText(e,t)}catch(e){Kt(e,"UpdateText")}break}case ke:{const e=s.varint(),t=s.varint(),n=s.string();t===r&&a.add(e);try{this.writeAttr("set_attribute",e,o[t]??"",n)}catch(e){Kt(e,"SetAttr")}break}case Ee:{const e=s.varint(),t=s.varint();try{this.writeAttr("remove_attribute",e,o[t]??"",null)}catch(e){Kt(e,"RemoveAttr")}break}case Te:{const e=s.varint();try{this.removeNode(e)}catch(e){Kt(e,"RemoveNode")}break}case Ce:{const e=s.varint();try{this.removeText(e)}catch(e){Kt(e,"RemoveText")}break}case xe:{const e=s.varint(),t=s.varint(),o=s.optionalId();if(null===n)try{this.nodes.insertBefore(e,t,o)}catch(e){Kt(e,"InsertBefore")}break}case Ae:{const e=0===s.byte()?null:s.string(),t=s.string();try{this.nodes.insertCss(e,t)}catch(e){Kt(e,"InsertCss")}break}case _e:{const e=s.varint(),t=s.string();try{this.nodes.set(e,document.createComment(t))}catch(e){Kt(e,"CreateComment")}break}case Me:{const e=s.varint();try{this.nodes.delete("remove_comment",e).remove()}catch(e){Kt(e,"RemoveComment")}break}case Ne:{const e=s.varint(),t=s.string(),n=s.varint();try{this.callbacks.add(this.nodes,e,t,n)}catch(e){Kt(e,"CallbackAdd")}break}case Le:{const e=s.varint(),t=s.string(),n=s.varint();try{this.callbacks.remove(this.nodes,e,t,n)}catch(e){Kt(e,"CallbackRemove")}break}case Se:{const e=s.varint(),t=s.bytesView();try{this.canvases.draw(this.nodes.getNode("canvas_draw",e),t)}catch(e){Kt(e,"CanvasDraw")}break}default:throw new Error(`bulk_update: unknown command tag ${e}`)}}}catch(e){console.error(`bulk_update - stream is unreadable at ${s.where()}, dropping the rest of the batch`,e)}n?.place(),a.size>0&&setTimeout(()=>{for(const e of a){const t=this.nodes.getAnyOption(e);t instanceof HTMLElement&&t.focus()}},0),this.nodes.removeInitNodes(),this.callbacks.forgetEarlyMessages(),this.nodes.addStyles(),this.canvases.paintDrawn(),he()},this.appLocation=t,this.nodes=new We,this.callbacks=new re(n),document.addEventListener("dragover",e=>{e.preventDefault()})}preloadImage(e){this.canvases.preload(e)}createNode(e,t,n){if(1===e||2===e||3===e)return;if(this.nodes.has(e))return;const s=(e=>pe.has(e)?document.createElementNS("http://www.w3.org/2000/svg",e.replace("svg:","")):document.createElement(e))(t);this.nodes.set(e,s),n&&ie(s,this.appLocation)}writeAttr(e,t,n,s){const o=this.nodes.getNode(e,t);if(null===s?o.removeAttribute(n):o.getAttribute(n)!==s&&o.setAttribute(n,s),"value"==n){const e=s??"";if(o instanceof HTMLInputElement)return void(o.value=e);if(o instanceof HTMLTextAreaElement)return o.value=e,void(o.defaultValue=e)}"checked"==n&&o instanceof HTMLInputElement&&(o.checked=null!==s)}removeNode(e){if(1===e||2===e||3===e)return;const t=this.nodes.delete("remove_node",e);this.canvases.forget(t),t.remove()}createText(e,t){if(this.nodes.has(e))return;const n=document.createTextNode(t);this.nodes.set(e,n)}removeText(e){this.nodes.delete("remove_node",e).remove()}updateText(e,t){this.nodes.getText("set_attribute",e).textContent=t}}const Jt={Debug:"debug",Info:"info",Log:"log",Warn:"warn",Error:"error"};class jt{constructor(e,t){this.metadata=e,this.getWasm=t;const n=new $(t,e.getEnv("vertigo-mount-point")??"/");this.dom=new Gt(e,n,t),this.websocket=new A(t),this.interval=new R(t),this.animationFrames=new U(t),this.location=n,this.cookie=new B}exec(e){const t=e;if("FetchCacheGet"===t)return{data:this.metadata.getFetchCache()};if("IsBrowser"===t)return{value:!0};if("GetDateNow"===t)return{value:Date.now()};if("TimezoneOffset"===t)return{value:(new Date).getTimezoneOffset()};if("Languages"===t)return{value:W(navigator)};if("HistoryBack"===t)return window.history.back(),null;if("AnimationFrameStart"===t)return this.animationFrames.start(),null;if("AnimationFrameStop"===t)return this.animationFrames.stop(),null;const n=t,[s,o]=Object.entries(n)[0]??[];switch(s){case"FetchExec":return S(this.getWasm,o.callback,o.request),null;case"WebsocketRegister":return this.websocket.websocket_register_callback(o.host,o.callback,o.connect_timeout),null;case"WebsocketSendMessage":return this.websocket.websocket_send_message(o.callback,o.message),null;case"WebsocketUnregister":return this.websocket.websocket_unregister_callback(o.callback),null;case"TimerSet":return this.interval.timerSet(o.callback,o.duration,o.kind),null;case"TimerClear":return this.interval.timerClear(o.callback),null;case"LocationGet":return{value:this.location.get(o.target)};case"LocationCallback":return this.location.callback(o.target,o.mode,o.callback),null;case"LocationSet":return this.location.set(o.target,o.mode,o.value),"History"===o.target&&function(e){const t=le(e);ce=null,""!==t&&(de(e,t),setTimeout(he,0))}(this.location.get("History")),null;case"CookieGet":return{value:this.cookie.get(o.name)};case"CookieSet":return this.cookie.set(o.name,o.value,o.expires_in),null;case"CookieJsonGet":return{value:this.cookie.getJson(o.name)};case"CookieJsonSet":return this.cookie.setJson(o.name,o.value,o.expires_in),null;case"GetEnv":return{value:this.metadata.getEnv(o.name)};case"Log":return console[Jt[o.kind]](o.message,o.arg2,o.arg3,o.arg4),null;case"GetRandom":return{value:F(o.min,o.max)};case"ImagePreload":return this.dom.preloadImage(o.url),null;case"JsApiCall":return this.executeJsApiCall(o.commands);case"DomBulkUpdate":return this.dom.update(o.commands),null;default:return console.info("exec_command: Arg",t),(()=>{throw Error("assert never")})()}}executeJsApiCall(e){let t=null;for(const n of e)if("Root"in n)if("window"===n.Root.name)t=window;else{if("document"!==n.Root.name)return console.error(`Unknown root: ${n.Root.name}`),null;t=document}else if("RootElement"in n){const e=n.RootElement.dom_id,s=this.dom.nodes.getAnyOption(e);if(void 0===s)return console.error(`Element not found: ${e}`),null;t=s}else if("Get"in n){if(null===t)return console.error("Get called on null"),null;t=t[n.Get.property]}else if("Set"in n){if(null===t)return console.error("Set called on null"),null;t[n.Set.property]=n.Set.value,t=void 0}else if("Call"in n){if(null===t)return console.error("Call called on null"),null;t=t[n.Call.method](...n.Call.args)}const n=e=>{if(null==e)return null;if("boolean"==typeof e)return e;if("string"==typeof e)return e;if("number"==typeof e)return e;if(e instanceof Uint8Array)return e.slice();if(Array.isArray(e))return e.map(e=>n(e));if((e=>{if(null===e)return!1;if("object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e)){const t={};for(const s of Object.keys(e))t[s]=n(e[s]);return t}return null};return n(t)}}class Yt{constructor(){this.get=e=>this.metadata.getAttribute(e),this.getEnabledHydration=()=>"true"!==this.get("data-env-disable-hydration");const e=document.getElementById("v-metadata");if(null===e)throw Error("Expected v-metadata");this.metadata=e,e.remove()}getEnv(e){return this.get(`data-env-${e}`)}getFetchCache(){return this.get("data-fetch-cache")}}class Xt{constructor(e){this.wasm=e}vertigoEntryFunction(e,t){this.wasm.exports.vertigo_entry_function(e,t)}static async create(t){let s=null;const o=()=>{if(null===s)throw Error("Wasm is no initialized");return s},r=new Yt,i=new jt(r,o);return window.$vertigoApi=i,s=await v(t,{mod:{panic_message:t=>{const n=Number(t%2n**32n),s=Number(t>>32n),r=o().getUint8Memory().subarray(s,s+n),i=e.decode(r);console.error("PANIC",i)},dom_access:e=>{if(0n===e)return console.error("dom_access - null pointer"),0n;const t=new n(()=>o().getUint8Memory(),e),s=g(t);o().exports.vertigo_export_free_block(e);const r=i.exec(s),a=m(r),c=o().exports.vertigo_export_alloc_block(a),l=new n(()=>o().getUint8Memory(),c);return p(r,l),c}}}),new Xt(s)}}const Qt=new Set,Zt=()=>{document.querySelectorAll("*[data-vertigo-run-wasm]").forEach(e=>{const t=e.getAttribute("data-vertigo-run-wasm");"string"==typeof t?(async e=>{if(Qt.has(e))return;if(Qt.size>0)return void console.error("Only one wasm module can be run",{moduleRun:Qt,wasm:e});Qt.add(e),console.info(`Wasm module: "${e}" -> start`);const t=await Xt.create(e);console.info(`Wasm module: "${e}" -> initialized`),t.vertigoEntryFunction(0,14),console.info(`Wasm module: "${e}" -> launched vertigoEntryFunction with version 0.14`)})(t):console.error("Run error",e)})};document.querySelectorAll("*[data-vertigo-run-wasm][data-vertigo-preload]").forEach(e=>{const t=e.getAttribute("data-vertigo-run-wasm");"string"==typeof t&&(e=>{if(w.has(e)||"function"!=typeof WebAssembly.compileStreaming)return;const t=WebAssembly.compileStreaming(fetch(e,{priority:"low"})).catch(e=>(console.warn("Preloading wasm failed, it will be fetched again once the page has loaded. Original error:\n",e),null));w.set(e,t)})(t)}),window.addEventListener("load",Zt),setTimeout(Zt,3e3);
//# sourceMappingURL=wasm_run.js.map