@rr0/ufoathome 0.194.0 → 0.195.0
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/dist-embed-scene/rr0-scene.mjs +4 -4
- package/dist-embed-sighting/{CaseReportExport-B9iaGKNP.js → CaseReportExport-BeKawC8S.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +8 -8
- package/dist-embed-sighting-editor/{CaseElement-DzwFIDZZ.js → CaseElement-CVi_yfyW.js} +1 -1
- package/dist-embed-sighting-editor/{CaseReportExport-D0GXupCT.js → CaseReportExport-DisXbZ3b.js} +1 -1
- package/dist-embed-sighting-editor/{SightingElement-BfxNhmfn.js → SightingElement-Bdkf99VT.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +17 -16
- package/dist-embed-ufoathome/{AdsbLolArchiveProvider-DXRO-h2K.js → AdsbLolArchiveProvider-veDw9Mxo.js} +1 -1
- package/dist-embed-ufoathome/{BallesterGuaspAssessor-ZSDHMhXN.js → BallesterGuaspAssessor-BVygSN0R.js} +1 -1
- package/dist-embed-ufoathome/{BeamEditor-BvF4J204.js → BeamEditor-eDeeNBE9.js} +1 -1
- package/dist-embed-ufoathome/{BeamSystem-Yg5JRiCT.js → BeamSystem-B5u4ithz.js} +1 -1
- package/dist-embed-ufoathome/{BodyEditor-CRJFVGzZ.js → BodyEditor-23Dua2K5.js} +1 -1
- package/dist-embed-ufoathome/{CaseEditorElement-MwO-zwnP.js → CaseEditorElement-DYMt7oB4.js} +13 -12
- package/dist-embed-ufoathome/{CaseElement-Ch0QzF7-.js → CaseElement-C6KVIESP.js} +3 -3
- package/dist-embed-ufoathome/{CaseReportExport-D9YyGZHP.js → CaseReportExport-Cgs2Y0v3.js} +3 -3
- package/dist-embed-ufoathome/{CaseTimeline-CnP5rqaK.js → CaseTimeline-BwCuVg5N.js} +3 -3
- package/dist-embed-ufoathome/{ContrailSystem-O_yvjart.js → ContrailSystem-CtQPQFyc.js} +1 -1
- package/dist-embed-ufoathome/{ControlPasses-BaglOE-7.js → ControlPasses-B_uf1Wmh.js} +1 -1
- package/dist-embed-ufoathome/{CoverageAssessor-CBh0sDI1.js → CoverageAssessor-JQCFe16i.js} +1 -1
- package/dist-embed-ufoathome/{Flightradar24Provider-C8Uj-qTs.js → Flightradar24Provider-BR8_7wmx.js} +1 -1
- package/dist-embed-ufoathome/{GLTFLoader-B4SVqjkZ.js → GLTFLoader-DrBMau2Y.js} +1 -1
- package/dist-embed-ufoathome/{GeoJsonExport-C-daFhc2.js → GeoJsonExport-wUgEVyel.js} +1 -1
- package/dist-embed-ufoathome/{GeographicFigures-N4WyX3J_.js → GeographicFigures-CpbFopao.js} +1 -1
- package/dist-embed-ufoathome/{HeadlightSystem-7mtgTwud.js → HeadlightSystem-YXD1Zdpn.js} +1 -1
- package/dist-embed-ufoathome/{HynekAssessor-DdoHR-Qt.js → HynekAssessor-BV2nWUx8.js} +1 -1
- package/dist-embed-ufoathome/{InterviewEditorElement-BSXLlt4e.js → InterviewEditorElement-DiT6FZnj.js} +1 -1
- package/dist-embed-ufoathome/{InterviewElement-Dwk9iHNv.js → InterviewElement-DFcCnZtF.js} +1 -1
- package/dist-embed-ufoathome/{KmlExport-CX-tTjIv.js → KmlExport-wWr2S8H-.js} +1 -1
- package/dist-embed-ufoathome/{LaserBeam-DUL1O57g.js → LaserBeam-CejB0H9v.js} +1 -1
- package/dist-embed-ufoathome/{LaunchEditor-X_zWEOTY.js → LaunchEditor-ConcMLIe.js} +1 -1
- package/dist-embed-ufoathome/{LaunchPlume-CcfhClxb.js → LaunchPlume-BQEYjeSf.js} +1 -1
- package/dist-embed-ufoathome/{LaunchSimulation-C9gbGzGM.js → LaunchSimulation-BIiU6D8P.js} +1 -1
- package/dist-embed-ufoathome/{ModelSource-BtuW2Ztg.js → ModelSource-B93j0IA6.js} +1 -1
- package/dist-embed-ufoathome/{ModelThumbnails-CacTTCW4.js → ModelThumbnails-3U8M50_n.js} +1 -1
- package/dist-embed-ufoathome/{ModelViewer-BlFPQJAr.js → ModelViewer-Cnxj0Oi9.js} +1 -1
- package/dist-embed-ufoathome/{ModuleConformance-qYpBoQH9.js → ModuleConformance-BlrRirPF.js} +2 -2
- package/dist-embed-ufoathome/{ModuleSession-D4LhYKvL.js → ModuleSession-Cdilmebx.js} +3 -3
- package/dist-embed-ufoathome/{ModuleThree-DLikU-uy.js → ModuleThree-Dpv5uvYp.js} +1 -1
- package/dist-embed-ufoathome/{ModulesPanelElement-GY7cTQ5t.js → ModulesPanelElement-CwgqBVUI.js} +3 -3
- package/dist-embed-ufoathome/{NearestApproach-4ntSx6IQ.js → NearestApproach-CQ2w9ctm.js} +1 -1
- package/dist-embed-ufoathome/{PictureRegistration-BLs4DkTI.js → PictureRegistration-DOSDjiOf.js} +1 -1
- package/dist-embed-ufoathome/{PoherAssessor-6t5qvmJy.js → PoherAssessor-C8g5YvJi.js} +1 -1
- package/dist-embed-ufoathome/{RailwaySystem-Dm-PbG_D.js → RailwaySystem-D8B965iv.js} +1 -1
- package/dist-embed-ufoathome/{ReentryEditor-C7A3Kh3_.js → ReentryEditor-CEbb0oLd.js} +1 -1
- package/dist-embed-ufoathome/{ReentrySimulation-BlgfVSxb.js → ReentrySimulation-D_JX7wWS.js} +1 -1
- package/dist-embed-ufoathome/{ReferenceSystem-Bv62TprV.js → ReferenceSystem-xm8mzWiT.js} +1 -1
- package/dist-embed-ufoathome/{ShareDialogElement-DLr5u_tk.js → ShareDialogElement-BBMLOqSW.js} +11 -11
- package/dist-embed-ufoathome/{SightingElement-DuNE_Yt0.js → SightingElement-e9ZcWa58.js} +2 -2
- package/dist-embed-ufoathome/{TraceSystem-Cl5kzaIr.js → TraceSystem-BL6qfrHF.js} +1 -1
- package/dist-embed-ufoathome/{VideoButton-DXPI7_Vt.js → VideoButton-DA48Qz2E.js} +1 -1
- package/dist-embed-ufoathome/{WaterSystem-CTGGh-Y-.js → WaterSystem-BLy0L9qC.js} +1 -1
- package/dist-embed-ufoathome/rr0-ufoathome.mjs +2 -2
- package/dist-embed-ufoathome/{surroundingsSources-CVKKb8h6.js → surroundingsSources-Dlyt6moH.js} +1 -1
- package/dist-embed-ufoathome/{trafficRuntime-DvKPyJcx.js → trafficRuntime-B_bwWY8d.js} +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./LanternEditor-M887ltwe.js","./SkyEventEditorStyle-CvY_AhbI.js","./SkyLantern-B7UlFgmB.js","./BirdEditor-DV3ndYff.js","./BirdFlock-O7K_g8y7.js","./DroneEditor-DRsM2ash.js","./DroneFlight-Fr4Vgso3.js","./SightingEditorMessages_en-CTQYcybj.js","./SightingLabels_en-oIpytoq_.js","./SightingEditorMessages_fr-DjUByAq4.js","./SightingLabels_fr-D69zENbW.js","./SightingEditorMessages_es-D-ASD5a3.js","./SightingLabels_es-DUh1CTXl.js","./SightingEditorMessages_it-Eat0U-4p.js","./SightingLabels_it-COLZ2Qth.js","./SightingMessages_en-CYzanHjT.js","./SightingMessages_fr-BtfWbIP7.js","./SightingMessages_es-hjvESK6f.js","./SightingMessages_it-Bqm4pewZ.js","./ShareCodeEditor-CF7IVeXv.js","./index-DSNA74v6.js","./BeamSystem-odg570aR.js","./LaserBeam-Drpkr84G.js","./BeamEditor-CI8-9VOc.js","./LaunchSimulation-C1ZWpKZT.js","./LaunchPlume-CrzPcqw7.js","./LaunchEditor-BjAk4XZR.js","./ReentryEditor-DfDGpL5C.js","./HynekAssessor-DlXalbph.js","./NearestApproach-O8k2n_qL.js","./BallesterGuaspAssessor-BTmq0r-G.js","./CoverageAssessor-DjY8iKp5.js","./ContrailSystem-BddkU7fj.js","./ContrailGrowth-DwHS8If9.js","./ReferenceSystem-DvcQp167.js","./PictureFetch-C3wgf1ZV.js","./trafficRuntime-C5BXL-G6.js","./GenerativeKit-BmhvjjzB.js","./browser-CltifEM0.js","./VideoExport-B8ZhHNnd.js","./ModelThumbnails-DSshyLu2.js","./ModelSource-Bko_3OJt.js","./ModelViewer-_yhAYvNy.js","./SightingFileEditor-0VZmtiOX.js","./sightingSchema-CgwoRMl-.js","./ModulesPanelElement-VPRCdjmv.js","./ModuleSession-jKFl1FMo.js","./KmlExport-Bh4eTycx.js","./GeographicFigures-DqhWddS9.js","./GeoJsonExport-BZ-0v8fM.js","./GhostSearchView-Dlhj3xWa.js","./CaseElement-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./LanternEditor-M887ltwe.js","./SkyEventEditorStyle-CvY_AhbI.js","./SkyLantern-B7UlFgmB.js","./BirdEditor-DV3ndYff.js","./BirdFlock-O7K_g8y7.js","./DroneEditor-DRsM2ash.js","./DroneFlight-Fr4Vgso3.js","./SightingEditorMessages_en-CTQYcybj.js","./SightingLabels_en-oIpytoq_.js","./SightingEditorMessages_fr-DjUByAq4.js","./SightingLabels_fr-D69zENbW.js","./SightingEditorMessages_es-D-ASD5a3.js","./SightingLabels_es-DUh1CTXl.js","./SightingEditorMessages_it-Eat0U-4p.js","./SightingLabels_it-COLZ2Qth.js","./SightingMessages_en-CYzanHjT.js","./SightingMessages_fr-BtfWbIP7.js","./SightingMessages_es-hjvESK6f.js","./SightingMessages_it-Bqm4pewZ.js","./ShareCodeEditor-CF7IVeXv.js","./index-DSNA74v6.js","./BeamSystem-odg570aR.js","./LaserBeam-Drpkr84G.js","./BeamEditor-CI8-9VOc.js","./LaunchSimulation-C1ZWpKZT.js","./LaunchPlume-CrzPcqw7.js","./LaunchEditor-BjAk4XZR.js","./ReentryEditor-DfDGpL5C.js","./HynekAssessor-DlXalbph.js","./NearestApproach-O8k2n_qL.js","./BallesterGuaspAssessor-BTmq0r-G.js","./CoverageAssessor-DjY8iKp5.js","./ContrailSystem-BddkU7fj.js","./ContrailGrowth-DwHS8If9.js","./ReferenceSystem-DvcQp167.js","./PictureFetch-C3wgf1ZV.js","./trafficRuntime-C5BXL-G6.js","./GenerativeKit-BmhvjjzB.js","./browser-CltifEM0.js","./VideoExport-B8ZhHNnd.js","./ModelThumbnails-DSshyLu2.js","./ModelSource-Bko_3OJt.js","./ModelViewer-_yhAYvNy.js","./SightingFileEditor-0VZmtiOX.js","./sightingSchema-CgwoRMl-.js","./ModulesPanelElement-VPRCdjmv.js","./ModuleSession-jKFl1FMo.js","./KmlExport-Bh4eTycx.js","./GeographicFigures-DqhWddS9.js","./GeoJsonExport-BZ-0v8fM.js","./GhostSearchView-Dlhj3xWa.js","./CaseElement-CVi_yfyW.js","./SightingElement-Bdkf99VT.js","./InterviewEditorElement-Bbkze5KE.js","./InterviewMedia-CvAxC62V.js","./InterviewElement-B3tm7y49.js","./interviewJson-CsMHIcZ-.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
const A_="modulepreload",T_=function(l,e){return new URL(l,e).href},tx={},H=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let r=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};const a=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),c=o?.nonce||o?.getAttribute("nonce");s=r(t.map(h=>{if(h=T_(h,i),h in tx)return;tx[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(!!i)for(let m=a.length-1;m>=0;m--){const g=a[m];if(g.href===h&&(!d||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":A_,d||(f.as="script"),f.crossOrigin="",f.href=h,c&&f.setAttribute("nonce",c),document.head.appendChild(f),d)return new Promise((m,g)=>{f.addEventListener("load",m),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${h}`)))})}))}function n(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return s.then(r=>{for(const a of r||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})};class Wt{constructor(e){this.entries=e}static free(e){return e?.basis==="assumed"||e?.basis==="fitted"}static empty(){return new Wt(new Map)}get size(){return this.entries.size}at(e){return this.entries.get(e)}paths(){return[...this.entries.keys()]}sourced(){return[...this.entries].filter(([,e])=>e.source!==void 0).map(([e,t])=>({path:e,basis:t.basis,source:t.source}))}interviewsCited(){const e=[];for(const{source:t}of this.sourced()){const i=t.said?.interview;i!==void 0&&!e.includes(i)&&e.push(i)}return e}pathsFromInterview(e){return this.sourced().filter(({source:t})=>t.said!==void 0&&t.said.interview===e).map(({path:t})=>t)}set(e,t){t.basis==="stated"&&t.rationale===void 0&&t.how===void 0&&t.range===void 0&&t.source===void 0?this.entries.delete(e):this.entries.set(e,t)}clear(e){for(const t of this.entries.keys())(t===e||t.startsWith(`${e}.`))&&this.entries.delete(t)}static strip(e){const t=new Wt(new Map);return{recording:Wt.stripValue(e,[],t),provenance:t}}static restore(e,t){if(t.size===0)return e;const i={...e},s=new Set([i]);for(const n of t.paths()){const r=t.at(n),a=n.split("."),o=Wt.writableHolderOf(i,a,s);if(!o)continue;const c=a[a.length-1],h=o[c];h!==void 0&&(r.of!==void 0&&JSON.stringify(r.of)!==JSON.stringify(h)||(o[c]={value:h,...r.basis==="stated"?{}:{basis:r.basis},...r.rationale===void 0?{}:{rationale:r.rationale},...r.how===void 0?{}:{how:r.how},...r.range===void 0?{}:{range:r.range},...r.source===void 0?{}:{source:r.source}}))}return i}static isWrapper(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"value"in e}static stripValue(e,t,i){return Wt.isWrapper(e)?(i.set(t.join("."),{basis:e.basis??"stated",...e.rationale===void 0?{}:{rationale:e.rationale},...e.how===void 0?{}:{how:e.how},...e.range===void 0?{}:{range:e.range},...e.source===void 0?{}:{source:e.source},of:e.value}),Wt.stripValue(e.value,t,i)):Array.isArray(e)?e.map((s,n)=>Wt.stripValue(s,[...t,String(n)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([s,n])=>[s,Wt.stripValue(n,[...t,s],i)])):e}static writableHolderOf(e,t,i){let s=e;for(const n of t.slice(0,-1)){const r=s[n];if(typeof r!="object"||r===null)return;if(i.has(r)){s=r;continue}const a=Array.isArray(r)?[...r]:{...r};i.add(a),s[n]=a,s=a}return s}}class Yp extends Error{constructor(e,t,i){super(typeof t=="number"&&Number.isInteger(t)&&t>=1?`This ${e} file is in version ${t} of its format; this UFO@home reads version ${i}. Read it with the UFO@home that reads its version.`:`This ${e} file states ${JSON.stringify(t)} as its format version, which is not a version.`),this.format=e,this.found=t,this.supported=i,this.name="FormatVersionError"}said(e){return e.replace("{found}",typeof this.found=="number"?String(this.found):JSON.stringify(this.found)).replace("{supported}",String(this.supported))}}class An{static CURRENT={sighting:4,case:1,interview:1};static SCHEMA_BASE="https://ufoathome.org/schema";static schemaUrl(e,t=An.CURRENT[e]){return`${An.SCHEMA_BASE}/${t}/${e}.schema.json`}static of(e){if(typeof e!="object"||e===null)return 1;const t=e.version;return t===void 0?1:typeof t=="object"&&t!==null&&"value"in t?t.value:t}static recording(e){return An.check(e,"sighting")}static check(e,t){const i=An.of(e),s=An.CURRENT[t];if(typeof i!="number"||!Number.isInteger(i)||i!==s)throw new Yp(t,i,s);return e}}class hi{static built=new WeakMap;static computers=new WeakMap;static loading=new WeakMap;static loaded(e,t){return t.every(i=>hi.itemsOf(e,i.key).length===0||hi.computers.has(i))}static load(e,t){return Promise.all(t.filter(i=>hi.itemsOf(e,i.key).length>0&&!hi.computers.has(i)).map(i=>{let s=hi.loading.get(i);return s||(s=i.compute().then(n=>{hi.computers.set(i,n)}),s.catch(()=>hi.loading.delete(i)),hi.loading.set(i,s)),s.catch(()=>{})})).then(()=>{})}static of(e){let t=hi.built.get(e);return t||(t=e.create(),hi.built.set(e,t)),t}static itemsOf(e,t){const i=e?.[t];return Array.isArray(i)?i:[]}static computes(e,t){return t.some(i=>hi.itemsOf(e,i.key).length>0)}static expand(e,t,i){return hi.expandWithKinds(e,t,i).interpretation}static expandWithKinds(e,t,i){const s=new Map,n=new Map;if(!e||!hi.computes(e,t))return{interpretation:e,kindOf:s,phenomenonOf:n};const r=t.flatMap(a=>hi.itemsOf(e,a.key).flatMap(o=>{const c=hi.computers.get(a);if(!c)return[];const h=c(o,i),d=a.phenomenon?.(o);for(const u of h)s.set(u.id,a),d&&n.set(u.id,d);return h}));return{interpretation:{...e,bodies:[...e.bodies,...r]},kindOf:s,phenomenonOf:n}}static computedPart(e,t){const i={};for(const s of t){const n=hi.itemsOf(e,s.key);n.length>0&&(i[s.key]=[...n])}return i}static saysNothing(e,t){return e.bodies.length===0&&e.title===void 0&&e.smoke===void 0&&t.every(i=>e[i.key]===void 0)}}class gT extends Error{constructor(e,t,i,s){super(`Module "${e}" gives "${i}" at ${t}, which module "${s}" already gives`),this.moduleId=e,this.point=t,this.sourceId=i,this.ownerId=s,this.name="ModuleConflictError"}}class I_{constructor(e){this.id=e}sources=[];owners=new Map;ownerOf(e){return this.owners.get(e)}conflict(e,t){for(const i of t){const s=this.owners.get(i.id);if(s!==void 0&&s!==e)return{sourceId:i.id,ownerId:s}}}provide(e,t){const i=this.conflict(e,t);if(i)throw new gT(e,this.id,i.sourceId,i.ownerId);this.withdraw(e);const s=e===Xe.BUILT_IN?this.sources.findIndex(n=>this.owners.get(n.id)!==Xe.BUILT_IN):-1;s<0?this.sources.push(...t):this.sources.splice(s,0,...t);for(const n of t)this.owners.set(n.id,e);return this.sources}withdraw(e){for(let t=this.sources.length-1;t>=0;t--){const i=this.sources[t].id;this.owners.get(i)===e&&(this.sources.splice(t,1),this.owners.delete(i))}}}class Xe{static BUILT_IN="ufoathome";static changes=new EventTarget;static points=new Map;static modules=new Map;static point(e){let t=Xe.points.get(e);return t||(t=new I_(e),Xe.points.set(e,t)),t}static install(e){if(e.id===Xe.BUILT_IN)throw new Error(`"${Xe.BUILT_IN}" is the id of the built-in module`);const t=Xe.contributionsOf(e);for(const[n,r]of t){const a=Xe.point(n).conflict(e.id,r);if(a)throw new gT(e.id,n,a.sourceId,a.ownerId)}const i=new Set(t.map(([n])=>n)),s=Xe.modules.get(e.id);if(s)for(const[n]of Xe.contributionsOf(s))i.add(n);for(const n of i)Xe.point(n).withdraw(e.id);for(const[n,r]of t)Xe.point(n).provide(e.id,r);Xe.modules.set(e.id,e);for(const n of i)Xe.announce(n)}static uninstall(e){const t=Xe.modules.get(e);if(t){Xe.modules.delete(e);for(const[i]of Xe.contributionsOf(t))Xe.point(i).withdraw(e),Xe.announce(i)}}static installed(){return[...Xe.modules.values()]}static contributionsOf(e){return Object.entries(e.contributes).filter(t=>Array.isArray(t[1])&&t[1].length>0)}static announce(e){Xe.changes.dispatchEvent(new CustomEvent("change",{detail:e}))}}const __=["en","fr","es","it"];class ui{static catalog(e){const t=new Map;return{load(i){const s=ui.languageOf(i);let n=t.get(s);return n||(n=e[s](),t.set(s,n),n.catch(()=>t.delete(s))),n}}}static none(){return new Proxy({},{get:()=>""})}static blank(){const e=new Proxy(()=>e,{get:(t,i)=>i===Symbol.toPrimitive?()=>"":i===Symbol.iterator?function*(){}:i==="toString"||i==="valueOf"?()=>"":i==="then"?void 0:e,apply:()=>e,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{}});return e}static languageOf(e){const t=e.toLowerCase().split("-")[0];return __.includes(t)?t:"en"}}const D_=ui.catalog({en:()=>H(()=>import("./FlareKindMessages_en-j3CY_TxX.js"),[],import.meta.url).then(l=>l.flareKindMessages_en),fr:()=>H(()=>import("./FlareKindMessages_fr-B2MezoN2.js"),[],import.meta.url).then(l=>l.flareKindMessages_fr),es:()=>H(()=>import("./FlareKindMessages_es-CZgrFIOO.js"),[],import.meta.url).then(l=>l.flareKindMessages_es),it:()=>H(()=>import("./FlareKindMessages_it-CmZmb3RP.js"),[],import.meta.url).then(l=>l.flareKindMessages_it)}),ix={key:"flares",messages:D_,phenomenon:()=>"DecoyFlare",compute:()=>H(async()=>{const{DecoyFlare:l}=await import("./DecoyFlare-DUt1_LcW.js");return{DecoyFlare:l}},[],import.meta.url).then(({DecoyFlare:l})=>e=>l.bodiesOf(e))},k_=ui.catalog({en:()=>H(()=>import("./LanternKindMessages_en-CQXdJ-k6.js"),[],import.meta.url).then(l=>l.lanternKindMessages_en),fr:()=>H(()=>import("./LanternKindMessages_fr-D7tQa_tQ.js"),[],import.meta.url).then(l=>l.lanternKindMessages_fr),es:()=>H(()=>import("./LanternKindMessages_es-BOO6kPjs.js"),[],import.meta.url).then(l=>l.lanternKindMessages_es),it:()=>H(()=>import("./LanternKindMessages_it-B8J-29Mj.js"),[],import.meta.url).then(l=>l.lanternKindMessages_it)}),sx={key:"lanterns",messages:k_,phenomenon:()=>"SkyLantern",compute:()=>H(async()=>{const{SkyLantern:l}=await import("./SkyLantern-B7UlFgmB.js");return{SkyLantern:l}},[],import.meta.url).then(({SkyLantern:l})=>(e,t)=>l.bodiesOf(e,t?.obstacles)),editor:()=>H(async()=>{const{LanternEditor:l}=await import("./LanternEditor-M887ltwe.js");return{LanternEditor:l}},__vite__mapDeps([0,1,2]),import.meta.url).then(({LanternEditor:l})=>(e,t,i)=>new l(e,t,i))},R_=ui.catalog({en:()=>H(()=>import("./BirdKindMessages_en-c_-L7frF.js"),[],import.meta.url).then(l=>l.birdKindMessages_en),fr:()=>H(()=>import("./BirdKindMessages_fr-C1TuqqEj.js"),[],import.meta.url).then(l=>l.birdKindMessages_fr),es:()=>H(()=>import("./BirdKindMessages_es-8Zo2t0o4.js"),[],import.meta.url).then(l=>l.birdKindMessages_es),it:()=>H(()=>import("./BirdKindMessages_it-DQZcrCkf.js"),[],import.meta.url).then(l=>l.birdKindMessages_it)}),nx={key:"birds",messages:R_,phenomenon:()=>"Birds",compute:()=>H(async()=>{const{BirdFlock:l}=await import("./BirdFlock-O7K_g8y7.js").then(e=>e.b);return{BirdFlock:l}},[],import.meta.url).then(({BirdFlock:l})=>(e,t)=>l.bodiesOf(e,t?.obstacles)),editor:()=>H(async()=>{const{BirdEditor:l}=await import("./BirdEditor-DV3ndYff.js");return{BirdEditor:l}},__vite__mapDeps([3,1,4]),import.meta.url).then(({BirdEditor:l})=>(e,t,i)=>new l(e,t,i))},C_=ui.catalog({en:()=>H(()=>import("./DroneKindMessages_en-CLygXcsv.js"),[],import.meta.url).then(l=>l.droneKindMessages_en),fr:()=>H(()=>import("./DroneKindMessages_fr-CAX15_pk.js"),[],import.meta.url).then(l=>l.droneKindMessages_fr),es:()=>H(()=>import("./DroneKindMessages_es-B9XFRYnQ.js"),[],import.meta.url).then(l=>l.droneKindMessages_es),it:()=>H(()=>import("./DroneKindMessages_it-CSGsCaJQ.js"),[],import.meta.url).then(l=>l.droneKindMessages_it)}),rx={quadcopter:"ConsumerDrone",saucer:"ConsumerDrone","fixed-wing":"MilitaryDrone"},ax={key:"drones",messages:C_,phenomenon:l=>rx[l.airframe]??rx.quadcopter,compute:()=>H(async()=>{const{DroneFlight:l}=await import("./DroneFlight-Fr4Vgso3.js").then(e=>e.c);return{DroneFlight:l}},[],import.meta.url).then(({DroneFlight:l})=>e=>l.bodiesOf(e)),editor:()=>H(async()=>{const{DroneEditor:l}=await import("./DroneEditor-DRsM2ash.js");return{DroneEditor:l}},__vite__mapDeps([5,1,6]),import.meta.url).then(({DroneEditor:l})=>(e,t,i)=>new l(e,t,i))},O_=Xe.point("interpretations").provide(Xe.BUILT_IN,[{id:ix.key,name:"Decoy flares",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>ix},{id:sx.key,name:"Sky lanterns",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>sx},{id:nx.key,name:"Birds",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>nx},{id:ax.key,name:"Drones",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>ax}]);class mc{static kinds(){return O_.map(e=>hi.of(e))}}class Vi{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static INTERVIEW_EVENT="interview";static check(e){return An.check(e,"case")}static isCase(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Array.isArray(e.events)&&!("timeline"in e)}static sightingUrls(e,t){return(e.events??[]).filter(i=>i.eventType===Vi.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,t).href)}static accountIds(e,t,i,s){const n=(e.events??[]).filter(r=>r.eventType===Vi.SIGHTING_EVENT&&r.id!==void 0&&typeof r.url=="string"&&i!==void 0&&new URL(r.url,t).href===i).map(r=>r.id);return s!==void 0&&n.push(s),n}static interpretationEvents(e,t){const i=[t].flat().filter(s=>!!s);return i.length===0?[]:(e.events??[]).filter(s=>s.eventType===Vi.INTERPRETATION_EVENT?s.sighting!==void 0&&i.includes(s.sighting):s.eventType!==Vi.SIGHTING_EVENT||s.interpretationOf===void 0?!1:[s.interpretationOf].flat().some(n=>i.includes(n))).map(s=>s)}static problems(e,t){const i=e.events??[],s=new Set,n=new Set;for(const a of i)a.id!==void 0&&(s.has(a.id)&&n.add(a.id),s.add(a.id));const r=[];for(const a of i){const o=a.eventType===Vi.SIGHTING_EVENT?a.interpretationOf:a.eventType===Vi.INTERVIEW_EVENT?a.interviewOf:void 0;if(o!==void 0)for(const c of[o].flat())!s.has(c)&&!t.includes(c)&&r.push({reading:a.url??a.id??"",reference:c})}return{duplicateIds:[...n],unresolved:r}}static async interpretationOf(e,t,i){if(e.bodies)return Vi.withModelsFrom(Wt.strip({title:e.title,bodies:e.bodies??[],smoke:e.smoke,findings:e.findings,...hi.computedPart(e,mc.kinds())}).recording,t);if(!e.url)return{title:e.title,bodies:[]};const s=new URL(e.url,t).href,n=await i(s),r="timeline"in n&&n.interpretation?n.interpretation:n;return Vi.withModelsFrom(Wt.strip({title:e.title??r.title,bodies:r.bodies??[],smoke:r.smoke,findings:r.findings,...hi.computedPart(r,mc.kinds())}).recording,s)}static withModelsFrom(e,t){return{...e,bodies:e.bodies.map(i=>i.model?.url?{...i,model:{...i.model,url:new URL(i.model.url,t).href}}:i)}}}class de{static draw(e,t="none"){return`<svg class="icon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="${t}" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">${e}</svg>`}static TRASH=de.draw('<path d="M2.5 4.5h11"/><path d="M6 4.5V3h4v1.5"/><path d="M4 4.5l.7 9h6.6l.7-9"/><path d="M6.8 7v4.5M9.2 7v4.5"/>');static TARGET=de.draw('<circle cx="8" cy="8" r="5"/><circle cx="8" cy="8" r="1.6"/><path d="M8 1v2.2M8 12.8V15M1 8h2.2M12.8 8H15"/>');static PLAY=de.draw('<path d="M5 3.2v9.6L12.6 8z"/>',"currentColor");static PAUSE=de.draw('<path d="M5.5 3.5v9M10.5 3.5v9"/>');static RECORD=de.draw('<circle cx="8" cy="8" r="4.2" fill="var(--error, #d93025)" stroke="none"/>');static STOP=de.draw('<rect x="4" y="4" width="8" height="8" rx="1.2"/>',"currentColor");static PREVIOUS_MARK=de.draw('<path d="M6.5 4 2.5 8l4 4"/><path d="M11 5.2 13.8 8 11 10.8 8.2 8z"/>');static NEXT_MARK=de.draw('<path d="M9.5 4l4 4-4 4"/><path d="M5 5.2 7.8 8 5 10.8 2.2 8z"/>');static CLOSE=de.draw('<path d="M4 4l8 8M12 4l-8 8"/>');static PLUS=de.draw('<path d="M8 3v10M3 8h10"/>');static COPY=de.draw('<rect x="5.5" y="5.5" width="8" height="8" rx="1.3"/><path d="M10.5 3.2h-7a1.3 1.3 0 0 0-1.3 1.3v7"/>');static CLOCK=de.draw('<circle cx="8" cy="8" r="6"/><path d="M8 4.6V8l2.4 1.6"/>');static INTERVIEW=de.draw('<path d="M13.3 9.2a1.6 1.6 0 0 1-1.6 1.6H6.2L3 13.4V4.4a1.6 1.6 0 0 1 1.6-1.6h7.1a1.6 1.6 0 0 1 1.6 1.6z"/><path d="M5.8 6.1h5.1M5.8 8.4h3.2"/>');static LOCK=de.draw('<rect x="3.2" y="7.2" width="9.6" height="6.4" rx="1.4"/><path d="M5.6 7.2V5.4a2.4 2.4 0 0 1 4.8 0v1.8"/>');static LOCK_OPEN=de.draw('<rect x="3.2" y="7.2" width="9.6" height="6.4" rx="1.4"/><path d="M5.6 7.2V5.4a2.4 2.4 0 0 1 4.6-.7"/>');static METEOR=de.draw('<path d="M2.5 2.5l7 7"/><path d="M5.5 2.5l5 5"/><circle cx="11.5" cy="11.5" r="2"/>');static COMET=de.draw('<circle cx="11" cy="11" r="2.4"/><path d="M9.3 9.3 2.5 2.5M9 11.2 3 7M11.2 9 7 3"/>');static STAR=de.draw('<path d="M8 2.2l1.7 3.6 3.9.5-2.9 2.7.8 3.9L8 11l-3.5 1.9.8-3.9-2.9-2.7 3.9-.5z"/>');static SATELLITE=de.draw('<rect x="6.3" y="6.3" width="3.4" height="3.4" transform="rotate(45 8 8)"/><path d="M5.4 5.4 3 3M10.6 10.6 13 13"/><path d="M1.8 4.2 4.2 1.8M11.8 14.2l2.4-2.4"/><path d="M10.5 3.5a3 3 0 0 1 2 2"/>');static FIREBALL=de.draw('<circle cx="10.5" cy="10.5" r="2.6"/><path d="M8.6 8.6 3 3M8 10.6 4.5 8.5M10.6 8 8.5 4.5"/>');static SUMMARY=de.draw('<rect x="3" y="2" width="10" height="12" rx="1.5"/><path d="M5.5 5.5h5M5.5 8h5M5.5 10.5h3"/>');static WITNESS=de.draw('<circle cx="8" cy="5" r="2.6"/><path d="M2.8 14c.6-3 2.6-4.6 5.2-4.6s4.6 1.6 5.2 4.6"/>');static LOCATION=de.draw('<path d="M8 14.3s4.5-4.3 4.5-7.8a4.5 4.5 0 0 0-9 0c0 3.5 4.5 7.8 4.5 7.8z"/><circle cx="8" cy="6.5" r="1.6"/>');static DATE=de.draw('<rect x="2.3" y="3.3" width="11.4" height="10.4" rx="1.5"/><path d="M2.3 6.6h11.4M5.3 1.8v2.8M10.7 1.8v2.8"/>');static ENVIRONMENT=de.draw('<path d="M1.5 14h13"/><path d="M2.8 14V8.3L6.3 5.5l3.5 2.8V14"/><path d="M12.2 14V9.4"/><circle cx="12.2" cy="7.4" r="2.1"/>');static SKY=de.draw('<path d="M4.6 12.5h7a2.6 2.6 0 0 0 .3-5.2 3.8 3.8 0 0 0-7.3-.6 2.9 2.9 0 0 0 0 5.8z"/>');static PHENOMENON=de.draw('<ellipse cx="8" cy="9" rx="6.3" ry="2.1"/><path d="M4.6 7.8a3.4 3.4 0 0 1 6.8 0"/><path d="M5 13.4l.6-1.4M11 13.4l-.6-1.4M8 14v-1.4"/>');static SOUND=de.draw('<path d="M2.5 6.2h2.3L8 3.5v9L4.8 9.8H2.5z"/><path d="M10.5 6a2.8 2.8 0 0 1 0 4M12.3 4.2a5.4 5.4 0 0 1 0 7.6"/>');static PICTURES=de.draw('<rect x="2" y="3" width="12" height="10" rx="1.5"/><circle cx="5.8" cy="6.4" r="1.2"/><path d="M2.5 12l3.8-3.6 2.4 2.2 2.2-1.8 2.6 2.5"/>');static FILES=de.draw('<path d="M4 1.8h5.2L12.5 5v9.2H4z"/><path d="M9 1.8V5.2h3.5"/>');static BY_GLYPH={"🗑":de.TRASH,"🎯":de.TARGET,"+":de.PLUS,"✕":de.CLOSE,"▶":de.PLAY,"⏸":de.PAUSE,"⏺":de.RECORD,"⏹":de.STOP};static show(e,t){if(e.dataset.icon===t&&e.firstChild)return;const i=de.BY_GLYPH[t];i?e.innerHTML=i:e.textContent=t,e.dataset.icon=t}static CSS=`
|
|
3
3
|
.icon { display: block; flex: none; }
|
|
4
4
|
button:has(> .icon:only-child) { display: inline-flex; align-items: center; justify-content: center; }
|
|
@@ -445,8 +445,8 @@ button.event-mark:focus-visible { outline: 2px solid var(--tl-sky); outline-offs
|
|
|
445
445
|
<button id="copy" class="share-copy" type="button"></button>
|
|
446
446
|
</div>
|
|
447
447
|
</dialog>
|
|
448
|
-
`;class qd extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(qd.TAG)||customElements.define(qd.TAG,qd)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=J_;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.pin=e("pin"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=await H_.load(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.pin.checked;this.linkField.value=t?po.pinnedLink(e.link(),"0.
|
|
449
|
-
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages;if(!e)return;const t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("pin-label",e.pin.replace("{version}","0.194.0")),this.pin.parentElement.title=e.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=H(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([19,20]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{t.select()}}}class zr extends Error{}class jg{constructor(e){this.name=e}validate(e){return!0}}class yT extends jg{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new zr(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new zr(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Pi{name;min;max;duration;subUnit;validator;constructor(e,t,i,s,n=new yT(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=s,this.duration=s?(s.max-s.min+1)*s.duration:1,this.validator=n}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class Iw{millisecond;second;minute;hour;day;month;year}class Q_ extends Iw{}class wT extends Q_{millisecond=new Pi("millisecond",0,999,void 0);second=new Pi("second",0,59,this.millisecond);minute=new Pi("minute",0,59,this.second);hour=new Pi("hour",0,23,this.minute);day=new Pi("day",1,31,this.hour);month=new Pi("month",1,12,this.day);year=new Pi("year",0,9999,this.month)}const gt=new wT;class MT extends yT{constructor(e=1,t=12){super("month",e,t)}}class _d extends Pi{static Month28=new _d(28);static Month29=new _d(29);static ThirtyDays=new _d(30);static ThirtyOneDays=new _d(31);constructor(e,t=new MT(1,e)){super("month",1,e,gt.day,t)}static create(e,t){switch(e){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return t%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new zr("Unsupported month",e,t)}}}class xo{static instance=new xo;render(e){return e.value.toString()}}class Jn{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new jg(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=xo.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Be{static#e=new Map;static register(e,t){Be.#e.set(e,t)}static get(e){const t=Be.#e.get(e);if(!t)throw new zr(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class pu extends Jn{constructor(e=new Date().getFullYear(),t=gt.year){super(e,t)}static fromString(e,t=Be.get(pu)){return new pu(t.parse(e))}}class Po extends xo{static default=new Po("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class fu extends Jn{constructor(e=new Date().getMonth()+1,t=gt.month){super(e,t)}static fromString(e,t=Be.get(fu)){return new fu(t.parse(e))}toString(e=Po.default){return super.toString(e)}}class mu extends Jn{constructor(e=new Date().getDate(),t=gt.day){super(e,t)}static fromString(e,t=Be.get(mu)){const i=t.parse(e);return new mu(i)}toString(e=Po.default){return super.toString(e)}}class gu extends Jn{constructor(e=new Date().getHours(),t=gt.hour){super(e,t)}static fromString(e,t=Be.get(gu)){return new gu(t.parse(e))}toString(e=Po.default){return super.toString(e)}}class vu extends Jn{constructor(e=new Date().getMinutes(),t=gt.minute){super(e,t)}static fromString(e,t=Be.get(vu)){return new vu(t.parse(e))}toString(e=Po.default){return super.toString(e)}}class bu extends Jn{constructor(e=new Date().getSeconds(),t=gt.second){super(e,t)}static fromString(e,t=Be.get(bu)){return new bu(t.parse(e),gt.second)}toString(e=Po.default){return super.toString(e)}}class Dl extends Jn{static renderer=new Po("0",3);constructor(e,t=gt.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=Dl.renderer){return super.toString(e)}}class e5{render(e){return e.toString()}}class t5 extends e5{render(e){const t=e.value,i=Math.abs(t),s=Math.floor(i/60),n=i%60;if(s===0&&n===0)return"Z";{const r=t<0?"-":"+",a=s.toString().padStart(2,"0"),o=n>0?":"+n.toString().padEnd(2,"0"):"";return r+a+o}}}class Ml{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=Be.get(Ml),i=void 0){const s=t.parse(e,i);return new Ml(s)}toString(e=new t5){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class $n{static timeshift(e,t){return e+($n.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:s}=e,n=e.hour??12;if(![t,i,s].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=$n.rule(t);if(!r)return!1;const a=$n.rank(i,s,n);return a>=$n.rank(r.start.month,r.start.day,2)&&a<$n.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:$n.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:$n.sunday(e,3,2)},end:{month:11,day:$n.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:$n.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:$n.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const s=new Date(Date.UTC(2e3,t-1,1));s.setUTCFullYear(e);const n=1+(7-s.getUTCDay())%7;if(i>0)return n+7*(i-1);const r=[31,$n.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=n;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const i5={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},s5={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},n5={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},r5={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},a5={name:"PT",timeshift:l=>$n.timeshift(-480,l),title:"Pacific Time (US)"},o5={name:"MT",timeshift:l=>$n.timeshift(-420,l),title:"Mountain Time (US)"},c5={name:"CT",timeshift:l=>$n.timeshift(-360,l),title:"Central Time (US)"},l5={name:"ET",timeshift:l=>$n.timeshift(-300,l),title:"Eastern Time (US)"},h5={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},d5={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},u5={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},p5={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},f5={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},m5={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},g5={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},v5={name:"Z",timeshift:"Z",title:"UTC"},b5={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},y5={name:"BST",timeshift:"+01",title:"British Summer Time"},w5={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},M5={name:"CET",timeshift:"+01",title:"Central European Time"},x5={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},E5={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},S5={name:"BJT",timeshift:"+08",title:"Beijing Time"},A5={name:"CST",timeshift:"-06",title:"Central Standard Time"},T5={name:"JST",timeshift:"+09",title:"Japan Standard Time"},I5={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},_5={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},D5={name:"LST",timeshift:"?",title:"Local Sideral Time"},ox=[m5,I5,f5,S5,y5,A5,d5,M5,w5,c5,h5,p5,u5,l5,b5,E5,T5,D5,n5,x5,r5,o5,_5,s5,i5,a5,g5,v5];class Zg{static instance=new Zg;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const s=t.join("-"),n=e.timeshift?e.timeshift.toString():"",r=i.join(":")+n;return s+(r.length>0?"T"+r:"")}}class Xl extends zr{constructor(e="method is abstract"){super(e)}}class _w{units;constructor(e){this.units=e}newYear(e){throw new Xl}newMonth(e){throw new Xl}newDay(e){throw new Xl}newHour(e){throw new Xl}newMinute(e){throw new Xl}newSecond(e){throw new Xl}}class k5 extends Iw{millisecond=new Pi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Pi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Pi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Pi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Pi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Pi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Pi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Wf=new k5;class Jg{static instance=new Jg;render(e){const t=Ha.toSpec(e);let i="P";const s=t.years;s&&(i+=s.toString()+"Y");const n=t.months;n&&(i+=n.toString(xo.instance)+"MM");const r=t.days;r&&(i+=r.toString(xo.instance)+"D");const a=t.hours;a&&(i+=a.toString(xo.instance)+"H");const o=t.minutes;o&&(i+=o.toString(xo.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(xo.instance)+"S"),i}}class Ha extends Jn{constructor(e={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof e=="number"?e:+(e.years?e.years*gt.year.duration:0)+(e.months?e.months*gt.month.duration:0)+(e.days?e.days*gt.day.duration:0)+(e.hours?e.hours*gt.hour.duration:0)+(e.minutes?e.minutes*gt.minute.duration:0)+(e.seconds?e.seconds*gt.second.duration:0)},new Pi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=C5){let i=typeof e=="number"?e:e.value;const s=i>0?1:-1;i=Math.abs(i);const n={},r=i/gt.year.duration,a=Math.floor(r);a>0&&(n.years=t.newYear(s*a),i-=a*gt.year.duration);const o=i/gt.month.duration,c=Math.floor(o);c>0&&(n.months=t.newMonth(s*c),i-=c*gt.month.duration);const h=i/gt.day.duration,d=Math.floor(h);d>0&&(n.days=t.newDay(s*d),i-=d*gt.day.duration);const u=i/gt.hour.duration,p=Math.floor(u);p>0&&(n.hours=t.newHour(s*p),i-=p*gt.hour.duration);const f=i/gt.minute.duration,m=Math.floor(f);m>0&&(n.minutes=t.newMinute(s*m),i-=m*gt.minute.duration);const g=i/gt.second.duration,v=Math.floor(s*g);return v>0&&(n.seconds=t.newSecond(v)),n}static fromString(e,t=Be.get(Ha)){return new Ha(t.parse(e))}static between(e,t){const i=t.getTime(),s=e.getTime();return new Ha(i-s)}toSpec(){return Ha.toSpec(this)}toString(e=Jg.instance){return e.render(this)}}class xT extends _w{constructor(e){super(e)}newYear(e){return new pu(e,this.units.year)}newMonth(e){return new fu(e,this.units.month)}newDay(e){return new mu(e,this.units.day)}newHour(e){return new gu(e,this.units.hour)}newMinute(e){return new vu(e,this.units.minute)}newSecond(e){return new bu(e,this.units.second)}newMillisecond(e){return new Dl(e,this.units.millisecond)}newTimeshift(e){return new Ml(typeof e=="number"?e:e.value)}}const R5=new xT(gt),C5=new xT(Wf);class En{#e;#t;#i;#s;#n;#r;#a;#o;constructor(e={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:En.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof Jn?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof Jn?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof Jn?e:this.factory.newDay(e)}get hour(){return this.#s}set hour(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newHour(e):!e||e.start||e instanceof Jn?e:this.factory.newHour(e)}get minute(){return this.#n}set minute(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newMinute(e):!e||e.start||e instanceof Jn?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof Jn?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof Jn)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof Ml)?this.factory.newTimeshift(e):e}get factory(){return R5}static fromString(e,t=Be.get(En)){const{year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:c,timeshift:h}=t.parse(e);return new En({year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new En({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:En.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return En.fromString(i)}#c(e){if(this.constructor.name!==e.constructor.name)throw new jg(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#c(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new Ha(t)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new En(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Zg.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const s=this.day?.toSpec();s&&(e.day=s);const n=this.hour?.toSpec();n&&(e.hour=n);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const o=this.millisecond?.toSpec();o&&(e.millisecond=o);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class Dw{static instance=new Dw;render(e){return(e.start?e.start.toString():"")+"/"+(e.end?e.end.toString():"")}}class qp{constructor(e,t){this.start=e,this.end=t}_start;get start(){return this._start}set start(e){if(typeof e=="string"&&(e=En.fromString(e)),e&&!(e instanceof En)&&!(e instanceof Ha))throw new zr("Interval start is not a level 0 date or duration: "+e);this._start=e}_end;get end(){return this._end}set end(e){if(typeof e=="string"&&(e=En.fromString(e)),e&&!(e instanceof En)&&!(e instanceof Ha))throw new zr("Interval end is not a level 0 date or duration: "+e);this._end=e}static fromString(e,t=Be.get(qp)){const{start:i,end:s}=t.parse(e);return new qp(i,s)}toString(e=Dw.instance){return e.render(this)}[Symbol.iterator](){let e=this.start;return{next:()=>{const t={done:e>this.end,value:e};return e++,t}}}}class $f extends xo{static instance=new $f(Po.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class Co extends Jn{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=$f.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class ET extends wT{year=new Pi("year",-9999,9999,this.month);yearExtended=new Pi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const R0=new ET;class sl extends Co{constructor(e,t=R0.year){super(e,t)}static fromString(e,t=R0.year,i=Be.get(sl)){const s=i.parse(e),n=s.value.start;if(e.startsWith("Y")&&(t=R0.yearExtended),n!==void 0){const r=new sl(Object.assign({...s},{value:Math.max(n,t.min)})),a=new sl(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new sl(s,t)}}class ST extends jg{monthValidator=new MT;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class nl extends Co{constructor(e,t=new Pi(gt.month.name,1,24,gt.day,new ST)){super(e,t)}static fromString(e,t=Be.get(nl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=gt.month;const r=new nl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new nl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new nl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class rl extends Co{constructor(e,t=gt.day){super(e,t)}static fromString(e,t=Be.get(rl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=gt.day;const r=new rl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new rl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new rl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class al extends Co{constructor(e,t=gt.hour){super(e,t)}static fromString(e,t=Be.get(al)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=gt.hour;const r=new al(Object.assign({...i},{value:Math.max(s,n.min)})),a=new al(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new al(i)}}class ol extends Co{constructor(e,t=gt.minute){super(e,t)}static fromString(e,t=Be.get(ol)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.minute,r=new ol(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ol(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ol(i)}toString(e=$f.instance){return super.toString(e)}}class cl extends Co{constructor(e,t=gt.second){super(e,t)}static fromString(e,t=Be.get(cl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.second,r=new cl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new cl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new cl(i)}}class Th extends Ml{static fromString(e,t=Be.get(Th),i=void 0){return new Th(t.parse(e,i))}}class AT extends _w{constructor(e){super(e)}newYear(e){return new sl(e,this.units.year)}newMonth(e){return new nl(e,this.units.month)}newDay(e){return new rl(e,this.units.day)}newHour(e){return new al(e,this.units.hour)}newMinute(e){return new ol(e,this.units.minute)}newSecond(e){return new cl(e,this.units.second)}newMillisecond(e){return new Dl(e,this.units.millisecond)}newTimeshift(e){return new Th(typeof e=="number"?e:e.value)}}const O5=new AT(R0),L5=new AT(Wf);class Fr extends En{constructor(e){super(e)}get factory(){return O5}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(e){return new Fr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:En.timeshiftOf(e)})}static fromString(e,t=Be.get(Fr)){const i=t.parse(e);return new Fr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Fr.fromString(i)}clone(){return new Fr(this.toSpec())}}const nn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class Qg extends Jg{static instance=new Qg;render(e){return super.render(e)}}class Zs extends Co{constructor(e){super(typeof e=="number"||e.hasOwnProperty("value")?e:{value:Zs.getValue(e,nn.year)+Zs.getValue(e,nn.month)+Zs.getValue(e,nn.day)+Zs.getValue(e,nn.hour)+Zs.getValue(e,nn.minute)+Zs.getValue(e,nn.second),uncertain:Zs.getBoolean(e,nn.uncertain),approximate:Zs.getBoolean(e,"approximate")},Wf.millisecond)}static getBoolean(e,t){return e[t]||e[nn.year+"s"]?.[t]||e[nn.month+"s"]?.[t]||e[nn.day+"s"]?.[t]||e[nn.hour+"s"]?.[t]||e[nn.minute+"s"]?.[t]||e[nn.second+"s"]?.[t]||!1}static getValue(e,t){let i=0,s=e[t+"s"];if(s instanceof Co?s=s.value:typeof e=="number"&&(s=e),s){const n=gt[t];i=s*n.duration}return i}static toSpec(e,t=L5){return{...Ha.toSpec(e,t),uncertain:e.uncertain||!1,approximate:e.approximate||!1}}static fromString(e,t=Be.get(Zs)){const i=t.parse(e);return new Zs(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new Zs(i-s)}toString(e=Qg.instance){return super.toString(e)}toSpec(){return Zs.toSpec(this)}}class jp extends qp{constructor(e,t){super(e,t)}get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=Fr.fromString(e)),e&&!(e instanceof Fr)&&!(e instanceof Zs))throw new zr("Interval start is not a level 1 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=Fr.fromString(e)),e&&!(e instanceof Fr)&&!(e instanceof Zs))throw new zr("Interval end is not a level 1 date or duration: "+e);this._end=e}static fromString(e,t=Be.get(jp)){const{start:i,end:s}=t.parse(e);return new jp(i,s)}}class ku extends Co{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class P5 extends ET{year=new Pi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Ry=new P5;class rc extends ku{constructor(e,t=Ry.year){super(e,t)}static fromString(e,t=Ry.year,i=Be.get(rc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new rc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new rc(Object.assign({...s},{value:Math.min(s.value.end,t.max)})),o={start:r,end:a},c=s.value.estimate;return c&&(o.estimate=c),o}else return new rc(s)}}class N5 extends ST{validate(e){switch(e){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(e)}}}class ac extends ku{constructor(e,t=new Pi(gt.month.name,1,41,gt.day,new N5)){super(e,t)}static fromString(e,t=Be.get(ac)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.month,r=new ac(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ac(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ac(i)}toString(e){return super.toString(e).padStart(2,"0")}}class oc extends ku{constructor(e,t=gt.day){super(e,t)}static fromString(e,t=Be.get(oc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.day,r=new oc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new oc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new oc(i)}toString(e){return super.toString(e).padStart(2,"0")}}class cc extends ku{constructor(e,t=gt.hour){super(e,t)}static fromString(e,t=Be.get(cc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.hour,r=new cc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new cc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new cc(i)}}class lc extends ku{constructor(e,t=gt.minute){super(e,t)}static fromString(e,t=Be.get(lc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.minute,r=new lc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new lc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new lc(i)}}class hc extends ku{constructor(e,t=gt.second){super(e,t)}static fromString(e,t=gt.second,i=Be.get(hc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new hc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new hc(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new hc(s,t)}}class TT extends Th{}class F5 extends $f{qualifier(){return""}}class Hc extends Zg{static instance=new Hc;static valueRenderer=new F5(Po.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],s=Hc.names.slice(Hc.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),n=Hc.qualifier(i.uncertainComponent,i.approximateComponent),r=Hc.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!s.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!s.some(a=>a.approximate));return n+i.toString(Hc.valueRenderer)+r}}class IT extends _w{constructor(e){super(e)}newYear(e){return new rc(e,this.units.year)}newMonth(e){return new ac(e,this.units.month)}newDay(e){return new oc(e,this.units.day)}newHour(e){return new cc(e,this.units.hour)}newMinute(e){return new lc(e,this.units.minute)}newSecond(e){return new hc(e,this.units.second)}newMillisecond(e){return new Dl(e,this.units.millisecond)}newTimeshift(e){return new TT(typeof e=="number"?e:e.value)}}const U5=new IT(Ry),B5=new IT(Wf);class br extends Fr{constructor(e){super(e)}toString(e=Hc.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return U5}static fromDate(e){return new br({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:En.timeshiftOf(e)})}static fromString(e,t=Be.get(br)){const i=t.parse(e);return new br(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return br.fromString(i)}clone(){return new br(this.toSpec())}}class Sc{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new zr(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Xl(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class Dd extends Qg{static instance=new Dd;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(e,t){return e?t?"%":"?":t?"~":""}render(e){const t=Dd.qualifier(e.uncertainDuration,e.approximateDuration);if(!e.hasQualifiedComponent)return t+super.render(e);let i=t+"P";for(const[s,n]of Dd.designators){const r=e.components[s];r&&(i+=Dd.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+n)}return i}}class qs extends Zs{#e;constructor(e){if(super(typeof e=="number"?e:{value:qs.valueFromSpec(e),uncertain:e.uncertain===!0,approximate:e.approximate===!0},Wf.millisecond),typeof e!="number"){const t={};for(const i of qs.componentNames)e[i]instanceof Co&&(t[i]=e[i]);Object.keys(t).length>0&&(this.#e=t)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#e}#t(e){return this.#e?Object.values(this.#e).some(t=>t[e]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#t("uncertain")}set uncertain(e){super.uncertain=e}get approximate(){return super.approximate||this.#t("approximate")}set approximate(e){super.approximate=e}get hasQualifiedComponent(){return this.#e?Object.values(this.#e).some(e=>e.uncertainComponent||e.approximateComponent):!1}static valueFromSpec(e){return qs.getValue(e,nn.year)+qs.getValue(e,nn.month)+qs.getValue(e,nn.day)+qs.getValue(e,nn.hour)+qs.getValue(e,nn.minute)+qs.getValue(e,nn.second)}static toSpec(e,t=B5){const i=Zs.toSpec(e,t);if(e instanceof qs&&e.hasQualifiedComponent)for(const s of qs.componentNames)delete i[s],e.components[s]&&(i[s]=e.components[s]);return i}static fromString(e,t=Be.get(qs)){const i=t.parse(e);return new qs(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new qs(i-s)}toSpec(){return qs.toSpec(this)}toString(e=Dd.instance){return super.toString(e)}}class Zp extends jp{get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=br.fromString(e)),e&&!(e instanceof br)&&!(e instanceof qs))throw new zr("Interval start is not a level 2 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=br.fromString(e)),e&&!(e instanceof br)&&!(e instanceof qs))throw new zr("Interval end is not a level 2 date or duration: "+e);this._end=e}static fromString(e,t=Be.get(Zp)){const{start:i,end:s}=t.parse(e);return new Zp(i,s)}}class q0 extends Set{constructor(e,t){super(e),this.exclusive=t}has(e){const t=e.toString().replace("..","/");for(const i of this)if(i.toString()===t)return!0;return!1}static fromString(e,t=Be.get(q0)){const{exclusive:i,values:s}=t.parse(e);return new q0(s,i)}}class Ac extends Sc{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return Ac.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new zr(`${this.name} cannot be negative`);return super.parse(e)}}class U{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return U.optional(U.group(e,...t))}static optionalNonCapturingGroup(...e){return U.optional(U.nonCapturingGroup(...e))}static numberGroup(e,t,i,s="\\d"){return U.group(e,`${i||""}[${s}]${t}`)}}const cx="yearValue";class Jp extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,cx),"{4}",void 0)}constructor(){super(cx,Jp.format())}}const lx="monthValue";class Qp extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,lx),"{1,2}",void 0)}constructor(){super(lx,Qp.format())}}const hx="dayValue";class jd extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,hx),"{1,2}",void 0)}constructor(){super(hx,jd.format())}}const dx="hourValue";class Zd extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,dx),"{1,2}",void 0)}constructor(){super(dx,Zd.format())}}const ux="minuteValue";class ef extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,ux),"{1,2}",void 0)}constructor(){super(ux,ef.format())}}const px="secondValue";class tf extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,px),"{1,2}",void 0)}constructor(){super(px,tf.format())}}const fx="timeshiftValue",mx="shiftHour",gx="shiftMinute";class yu extends Sc{static format(e=""){return ox.map(t=>t.name).join("|")+"|"+U.nonCapturingGroup(U.group(e+mx,U.numberGroup(U.groupName(e,fx),"{2}","[+-]")),U.optionalNonCapturingGroup(":?",U.numberGroup(U.groupName(e,gx),"{2}",void 0)))}constructor(){super(fx,yu.format())}parse(e,t){let i=0;const s=ox.find(n=>n.name===e);if(s){if(typeof s.timeshift=="function")try{return s.timeshift(t??{})}catch(n){throw new zr(`The time zone ${e} depends on the date: ${n.message}`)}e=s.timeshift}if(e!=="Z"){const n=this.regexGroups(e),r=n[mx];r&&(i+=parseInt(r,10)*60);const a=n[gx];a&&(i+=parseInt(a,10))}return i}}const vx="year",bx="month",yx="day",wx="hour",Mx="minute",xx="second",Ex="millisecond",Sx="timeshift";class ih extends Sc{static format(e=""){return U.group(U.groupName(e,vx),Jp.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,bx),Qp.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,yx),jd.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,wx),Zd.format(e)),":?",U.group(U.groupName(e,Mx),ef.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,xx),tf.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,Ex),"\\d+"))),"\\s*",U.optionalGroup(U.groupName(e,Sx),yu.format(e)))))}constructor(){super("date",ih.format())}parse(e){const t=this.regexGroups(e),i=t[vx],s=t[bx],n=t[yx],r=t[wx],a=t[Mx],o=t[xx],c=t[Ex],h=t[Sx],d=i?new pu(Jp.read(i)):void 0,u=s?Qp.read(s):void 0;return{year:d,month:u?new fu(u,_d.create(u.value,d?.value)):void 0,day:n?new mu(jd.read(n)):void 0,hour:r?new gu(Zd.read(r)):void 0,minute:a?new vu(ef.read(a)):void 0,second:o?new bu(tf.read(o)):void 0,millisecond:c?Dl.parseFraction(c):void 0,timeshift:h?Ml.fromString(h,new yu,{year:d?.value,month:u?.value,day:n?jd.read(n).value:void 0,hour:r?Zd.read(r).value:void 0}):void 0}}}const Ax="years",Iv="months",z5="days",Tx="hours",Ix="minutes",_x="seconds";class kw extends Sc{static format(e=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Ax),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Iv),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,z5),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Tx),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Ix),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,_x),"+",void 0,"\\d"),"S")}constructor(){super("duration",kw.format())}parseGroups(e){return{years:e[Ax],months:e[Iv],days:e[Iv],hours:e[Tx],minutes:e[Ix],seconds:e[_x]}}}const _v="start",Dv="end";class Rw extends Sc{static format=U.group(_v,ih.format(_v))+"/"+U.group(Dv,ih.format(Dv));constructor(){super("interval",Rw.format)}parse(e){const t=this.regexGroups(e),i=t[_v],s=t[Dv];return{start:i?En.fromString(i,new ih):void 0,end:s?En.fromString(s,new ih):void 0}}}Be.register(En,()=>new ih);Be.register(mu,()=>new jd);Be.register(Ha,()=>new kw);Be.register(gu,()=>new Zd);Be.register(qp,()=>new Rw);Be.register(vu,()=>new ef);Be.register(fu,()=>new Qp);Be.register(bu,()=>new tf);Be.register(Ml,()=>new yu);Be.register(pu,()=>new Jp);class Zi extends Ac{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Zi.uncertainGroup+Zi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return U.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(U.groupName(Zi.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(Zi.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(Zi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return U.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let s=0,n;for(n=0;n<t.length;n++){const c=t[n];if(c==="X")break;s=s*10+parseInt(c,10)}if(n<t.length){let c=1;for(let u=0;u<t.length-n;u++)c*=10;const h=i*s*c,d=h+c-1;s={start:h,end:d}}else s*=i;const r=e[U.groupName(Zi.uncertainAndApproximateGroup,this.name)],a=e[U.groupName(Zi.approximateGroup,this.name)]||r,o=e[U.groupName(Zi.uncertainGroup,this.name)]||r;return{value:s,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const Dx="yearValue";class sf extends Zi{constructor(){super(Dx,sf.format())}static format(e=""){return"Y?"+Zi.numberFormat(U.groupName(e,Dx),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const kx="monthValue";class nf extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,kx),"{1,2}",void 0)}constructor(){super(kx,nf.format())}}const Rx="dayValue";class rf extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Rx),"{1,2}",void 0)}constructor(){super(Rx,rf.format())}}const Cx="hourValue";class af extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Cx),"{1,2}",void 0)}constructor(){super(Cx,af.format())}}const Ox="minuteValue";class of extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Ox),"{1,2}",void 0)}constructor(){super(Ox,of.format())}}const Lx="secondValue";class cf extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Lx),"{1,2}",void 0)}constructor(){super(Lx,cf.format())}}class lf extends yu{}class os extends Sc{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(e=os.format()){super("date",e)}static format(e=""){return U.group(U.groupName(e,os.yearGroup),sf.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,os.monthGroup),nf.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,os.dayGroup),rf.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,os.hourGroup),af.format(e)),":",U.group(U.groupName(e,os.minuteGroup),of.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,os.secondGroup),cf.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,os.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(e,os.timeshiftGroup),lf.format(e)))))}parseGroups(e){const t=e[os.millisecondGroup],i=t?Dl.parseFraction(t):void 0,s=e[os.secondGroup],n=s?cl.fromString(s,new cf):void 0,r=e[os.minuteGroup];let a;r&&(a=ol.fromString(r,new of),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[os.hourGroup];let c;o&&(c=al.fromString(o,new af),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[os.dayGroup];let d;h&&(d=rl.fromString(h,new rf),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[os.monthGroup];let p;u&&(p=nl.fromString(u,new nf),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[os.yearGroup];let m;f&&(m=sl.fromString(f,void 0,new sf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[os.timeshiftGroup],v=g?Th.fromString(g,new lf,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:n,millisecond:i,timeshift:v}}}const Px="years",Nx="months",Fx="days",Ux="hours",Bx="minutes",zx="seconds";class sh extends Zi{static format(e=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Px),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Nx),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Fx),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Ux),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Bx),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,zx),"+",void 0,"\\d"),"S")+this.formatSuffix(e)}constructor(){super("duration",sh.format())}parseGroups(e){return{years:e[Px],months:e[Nx],days:e[Fx],hours:e[Ux],minutes:e[Bx],seconds:e[zx],uncertain:!!e[Zi.uncertainGroup],approximate:!!e[Zi.approximateGroup]}}}const H5="dates",kv="start",Rv="end",Hx="durations",Cv="durationMin",Ov="durationMax";class Cw extends Sc{static format=U.group(H5,U.optionalGroup(kv,U.group("openStart","\\.\\.")+"|"+os.format(kv))+"/"+U.optionalGroup(Rv,U.group("openEnd","\\.\\.")+"|"+os.format(Rv)))+"|"+U.group(Hx,U.group(Cv,sh.format(Cv))+"/"+U.group(Ov,sh.format(Ov)));constructor(e="interval",t=Cw.format){super(e,t)}parseGroups(e){let t,i;if(e[Hx]){const n=e[Cv];t=Zs.fromString(n,new sh);const r=e[Ov];i=Zs.fromString(r,new sh)}else{const n=e[kv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=Fr.fromString(n,new os)}const r=e[Rv];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Fr.fromString(r,new os)}}return{start:t,end:i}}}Be.register(Fr,()=>new os);Be.register(rl,()=>new rf);Be.register(Zs,()=>new sh);Be.register(al,()=>new af);Be.register(jp,()=>new Cw);Be.register(ol,()=>new of);Be.register(nl,()=>new nf);Be.register(cl,()=>new cf);Be.register(Th,()=>new lf);Be.register(sl,()=>new sf);class oi extends Zi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=oi.uncertainGroup+oi.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(U.groupName(oi.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(oi.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(oi.uncertainAndApproximateGroup,e),"%")+Zi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[U.groupName(oi.uncertainAndApproximateGroup,this.name)];return(e[U.groupName(oi.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[U.groupName(oi.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Pu="yearValue",Gx="exp",Vx="signif";class hf extends oi{constructor(){super(Pu,hf.format())}static format(e=""){return"Y?"+U.nonCapturingGroup(U.group(U.groupName(e,Gx),"[-]?\\d+E\\d+")+"|"+oi.numberFormat(U.groupName(e,Pu),"+","[-]?")+U.optionalGroup(U.groupName(e,Vx),"S\\d+"))}parseGroups(e){const t=e[Gx];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[Pu]=c.toString()}const i=e[Vx],s=e[Pu];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:o}=this.getValueAndSign(e);let c="";for(let h=0;h<a.length;h++)c+=h<r?a.charAt(h):"X";e[Pu]=(o<0?"-":"")+c}const n=super.parseGroups(e);return i&&(n.value.estimate=parseInt(s,10)),n}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const Wx="monthValue";class df extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Wx),"{1,2}",void 0)}constructor(){super(Wx,df.format())}}const $x="dayValue";class uf extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,$x),"{1,2}",void 0)}constructor(){super($x,uf.format())}}const Kx="hourValue";class pf extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Kx),"{1,2}",void 0)}constructor(){super(Kx,pf.format())}}const Xx="secondValue";class ff extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Xx),"{1,2}",void 0)}constructor(){super(Xx,ff.format())}}const Yx="minuteValue";class mf extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Yx),"{1,2}",void 0)}constructor(){super(Yx,mf.format())}}class G5 extends lf{}class fi extends Sc{static yearGroup=os.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",fi.format())}static format(e=""){return U.group(U.groupName(e,fi.yearGroup),hf.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,fi.monthGroup),df.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,fi.dayGroup),uf.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,fi.hourGroup),pf.format(e)),":",U.group(U.groupName(e,fi.minuteGroup),mf.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,fi.secondGroup),ff.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,fi.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(e,fi.timeshiftGroup),G5.format(e)))))}parseGroups(e){const t=e[fi.millisecondGroup],i=t?Dl.parseFraction(t):void 0,s=e[fi.secondGroup];let n;s&&(n=hc.fromString(s,void 0,new ff),n.uncertain=n?.uncertain||!1,n.approximate=n?.approximate||!1);const r=e[fi.minuteGroup];let a;r&&(a=lc.fromString(r,new mf),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[fi.hourGroup];let c;o&&(c=cc.fromString(o,new pf),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[fi.dayGroup];let d;h&&(d=oc.fromString(h,new uf),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[fi.monthGroup];let p;u&&(p=ac.fromString(u,new df),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[fi.yearGroup];let m;f&&(m=rc.fromString(f,void 0,new hf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[fi.timeshiftGroup],v=g?TT.fromString(g,new lf,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:n,millisecond:i,timeshift:v}}}const qx="durationValue";class Ow extends oi{static format(e=""){return"^"+oi.numberFormat(U.groupName(e,qx),"+",void 0)}constructor(){super(qx,Ow.format())}}class V5 extends Iw{millisecond=new Pi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new Pi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Pi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new Pi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new Pi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new Pi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new Pi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const Uh=new V5;class ht extends oi{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new Ow;static componentFormat(e,t,i,s,n=""){const r=U.group(U.groupName(e,ht.quantityGroup(t)),oi.numberFormat(U.groupName(e,i),"+",void 0,"\\d"));return U.group(U.groupName(e,t),r,s,n)}static quantityGroup(e){return e+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",ht.format())}static format(e=""){const t=U.groupName(e,ht.durationGroup);return this.qualifierFormat(U.groupName(oi.uncertainGroup,t),"?")+this.qualifierFormat(U.groupName(oi.approximateGroup,t),"~")+this.qualifierFormat(U.groupName(oi.uncertainAndApproximateGroup,t),"%")+"P"+U.optional(ht.componentFormat(e,ht.yearsGroup,fi.yearGroup,"Y"))+U.optionalNonCapturingGroup(ht.componentFormat(e,ht.monthsGroup,fi.monthGroup,"MM")+"|"+ht.componentFormat(e,ht.isoMonthsGroup,"isoMonth","M",ht.isoMonthsLookahead))+U.optional(ht.componentFormat(e,ht.daysGroup,fi.dayGroup,"D"))+"T?"+U.optional(ht.componentFormat(e,ht.hoursGroup,fi.hourGroup,"H"))+U.optional(ht.componentFormat(e,ht.minutesGroup,fi.minuteGroup,"M"))+U.optional(ht.componentFormat(e,ht.secondsGroup,fi.secondGroup,"S"))+U.optionalGroup(U.groupName(e,ht.suffixGroup),"[?~%]")}static parseComponent(e,t,i){const s=ht.componentParser.parse(e);return new t(s,i)}parseGroups(e){const t=e[ht.quantityGroup(ht.secondsGroup)];let i;t&&(i=ht.parseComponent(t,hc,Uh.second),i.uncertain=!!e[U.groupName(oi.uncertainGroup,ht.secondsGroup)]||!1,i.approximate=!!e[U.groupName(oi.approximateGroup,ht.secondsGroup)]||!1);const s=e[ht.quantityGroup(ht.minutesGroup)];let n;s&&(n=ht.parseComponent(s,lc,Uh.minute),n.uncertain=n.uncertain||i?.uncertain||!1,n.approximate=n.approximate||i?.approximate||!1);const r=e[ht.quantityGroup(ht.hoursGroup)];let a;r&&(a=ht.parseComponent(r,cc,Uh.hour),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[ht.quantityGroup(ht.daysGroup)];let c;o&&(c=ht.parseComponent(o,oc,Uh.day),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[ht.quantityGroup(ht.monthsGroup)]||e[ht.quantityGroup(ht.isoMonthsGroup)];let d;h&&(d=ht.parseComponent(h,ac,Uh.month),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[ht.quantityGroup(ht.yearsGroup)];let p;u&&(p=ht.parseComponent(u,rc,Uh.year),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ht.suffixGroup],m=!!e[U.groupName(oi.uncertainAndApproximateGroup,ht.durationGroup)]||f==="%",g=m||!!e[U.groupName(oi.uncertainGroup,ht.durationGroup)]||f==="?",v=m||!!e[U.groupName(oi.approximateGroup,ht.durationGroup)]||f==="~";return{years:p,months:d,days:c,hours:a,minutes:n,seconds:i,uncertain:g,approximate:v}}}const W5="dates",Lv="start",Pv="end",jx="durations",Nv="durationMin",Fv="durationMax";class ev extends Sc{static format=U.group(W5,U.optionalGroup(Lv,U.group("openStart","\\.\\.")+"|"+fi.format(Lv))+"/"+U.optionalGroup(Pv,U.group("openEnd","\\.\\.")+"|"+fi.format(Pv)))+"|"+U.group(jx,U.group(Nv,ht.format(Nv))+"/"+U.group(Fv,ht.format(Fv)));constructor(e="interval",t=ev.format){super(e,t)}parseGroups(e){let t,i;if(e[jx]){const n=e[Nv];t=qs.fromString(n,new ht);const r=e[Fv];i=qs.fromString(r,new ht)}else{const n=e[Lv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=br.fromString(n,new fi)}const r=e[Pv];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=br.fromString(r,new fi)}}return{start:t,end:i}}}class $5{parse(e){e=e.trim();const t=e.startsWith("["),s=e.substring(1,e.length-1).split(","),n=[];for(const r of s){let a;r.includes("..")?a=Zp.fromString(r.replace("..","/"),new ev):a=br.fromString(r,new fi),n.push(a)}return{values:n,exclusive:t}}}Be.register(br,()=>new fi);Be.register(oc,()=>new uf);Be.register(qs,()=>new ht);Be.register(cc,()=>new pf);Be.register(Zp,()=>new ev);Be.register(lc,()=>new mf);Be.register(ac,()=>new df);Be.register(hc,()=>new ff);Be.register(q0,()=>new $5);Be.register(rc,()=>new hf);class Bs{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[Bs.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>Bs.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(Bs.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(c=>c===i))!==null&&s!==void 0?s:Object.keys(a).find(c=>Bs.base(c)===Bs.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}Bs.any=new Bs([]);var Zx;(function(l){l.abductee="abductee",l.actor="actor",l.artist="artist",l.anthropologist="anthropologist",l.archeologist="archeologist",l.astronaut="astronaut",l.astronomer="astronomer",l.astrologist="astrologist",l.astrophysicist="astrophysicist",l.banker="banker",l.barman="barman",l.biologist="biologist",l.biochemist="biochemist",l.biophysicist="biophysicist",l.bishop="bishop",l.businessman="businessman",l.botanist="botanist",l.cameraman="cameraman",l.chemist="chemist",l.contactee="contactee",l.cryptozoologist="cryptozoologist",l.dentist="dentist",l.director="director",l.diplomat="diplomat",l.diver="diver",l.electronics="electronics",l.engineer="engineer",l.ethnologist="ethnologist",l.exobiologist="exobiologist",l.farmer="farmer",l.firefighter="firefighter",l.flightAttendant="flightAttendant",l.geologist="geologist",l.geophysicist="geophysicist",l.geographer="geographer",l.historian="historian",l.houseWife="houseWife",l.hypnotherapist="hypnotherapist",l.illusionist="illusionist",l.journalist="journalist",l.judge="judge",l.lawyer="lawyer",l.leader="leader",l.librarian="librarian",l.logger="logger",l.mathematician="mathematician",l.mechanic="mechanic",l.meteorologist="meteorologist",l.military="military",l.musician="musician",l.neurologist="neurologist",l.neuroscientist="neuroscientist",l.neuropsychiatrist="neuropsychiatrist",l.nurse="nurse",l.oceanographer="oceanographer",l.painter="painter",l.parapsychologist="parapsychologist",l.philosopher="philosopher",l.photographer="photographer",l.physician="physician",l.physicist="physicist",l.pilot="pilot",l.politician="politician",l.policeman="policeman",l.priest="priest",l.producer="producer",l.prospector="prospector",l.psychologist="psychologist",l.psychiatrist="psychiatrist",l.radioastronomer="radioastronomer",l.radioamateur="radioamateur",l.salesman="salesman",l.sailor="sailor",l.sociologist="sociologist",l.softwareEngineer="softwareEngineer",l.stuntman="stuntman",l.taxiDriver="taxiDriver",l.teacher="teacher",l.telegrapher="telegrapher",l.truckDriver="truckDriver",l.ufologist="ufologist",l.ufoWitness="ufoWitness",l.ufoWitness2="ufoWitness2",l.worker="worker",l.writer="writer"})(Zx||(Zx={}));var Jx;(function(l){l.neutral="neutral",l.male="male",l.female="female"})(Jx||(Jx={}));class K5 extends Error{constructor(e,t){super(e),this.cause=t}}class Lw extends K5{constructor(e=Lw.defaultMessage,t){super(e,t)}}Lw.defaultMessage="Assertion failed";var Qx;(function(l){l.country="country",l.region="region",l.department="department",l.city="city",l.company="company"})(Qx||(Qx={}));var eE;(function(l){l.at="at",l.au="au",l.ar="ar",l.be="be",l.br="br",l.ca="ca",l.ch="ch",l.cn="cn",l.cl="cl",l.co="co",l.cy="cy",l.de="de",l.dk="dk",l.do="do",l.dz="dz",l.gr="gr",l.ec="ec",l.eg="eg",l.es="es",l.fi="fi",l.fr="fr",l.ga="ga",l.ge="ge",l.hu="hu",l.in="in",l.ie="ie",l.ir="ir",l.il="il",l.it="it",l.jp="jp",l.kr="kr",l.ma="ma",l.mx="mx",l.my="my",l.mz="mz",l.nl="nl",l.no="no",l.nz="nz",l.pa="pa",l.pe="pe",l.ph="ph",l.pl="pl",l.pt="pt",l.ro="ro",l.ru="ru",l.sc="sc",l.tr="tr",l.ua="ua",l.uk="uk",l.us="us",l.sa="sa",l.se="se",l.su="su",l.tn="tn",l.tw="tw",l.ve="ve",l.za="za"})(eE||(eE={}));class X5{static of(e){if(!(!e||e.length===0))return e.some(t=>t.outcome==="fails"&&t.against!=="supposed")?"incompatible":e.some(t=>t.outcome!=="holds")?"unsettled":"compatible"}}/**
|
|
448
|
+
`;class qd extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(qd.TAG)||customElements.define(qd.TAG,qd)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=J_;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.pin=e("pin"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=await H_.load(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.pin.checked;this.linkField.value=t?po.pinnedLink(e.link(),"0.195.0"):e.link(),this.fitLink();const s=`<script type="module" src="${t?po.pinned(e.module,"0.195.0"):po.current(e.module,import.meta.url,Ah.home())}"><\/script>
|
|
449
|
+
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages;if(!e)return;const t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("pin-label",e.pin.replace("{version}","0.195.0")),this.pin.parentElement.title=e.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=H(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([19,20]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{t.select()}}}class zr extends Error{}class jg{constructor(e){this.name=e}validate(e){return!0}}class yT extends jg{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new zr(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new zr(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Pi{name;min;max;duration;subUnit;validator;constructor(e,t,i,s,n=new yT(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=s,this.duration=s?(s.max-s.min+1)*s.duration:1,this.validator=n}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class Iw{millisecond;second;minute;hour;day;month;year}class Q_ extends Iw{}class wT extends Q_{millisecond=new Pi("millisecond",0,999,void 0);second=new Pi("second",0,59,this.millisecond);minute=new Pi("minute",0,59,this.second);hour=new Pi("hour",0,23,this.minute);day=new Pi("day",1,31,this.hour);month=new Pi("month",1,12,this.day);year=new Pi("year",0,9999,this.month)}const gt=new wT;class MT extends yT{constructor(e=1,t=12){super("month",e,t)}}class _d extends Pi{static Month28=new _d(28);static Month29=new _d(29);static ThirtyDays=new _d(30);static ThirtyOneDays=new _d(31);constructor(e,t=new MT(1,e)){super("month",1,e,gt.day,t)}static create(e,t){switch(e){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return t%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new zr("Unsupported month",e,t)}}}class xo{static instance=new xo;render(e){return e.value.toString()}}class Jn{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new jg(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=xo.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Be{static#e=new Map;static register(e,t){Be.#e.set(e,t)}static get(e){const t=Be.#e.get(e);if(!t)throw new zr(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class pu extends Jn{constructor(e=new Date().getFullYear(),t=gt.year){super(e,t)}static fromString(e,t=Be.get(pu)){return new pu(t.parse(e))}}class Po extends xo{static default=new Po("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class fu extends Jn{constructor(e=new Date().getMonth()+1,t=gt.month){super(e,t)}static fromString(e,t=Be.get(fu)){return new fu(t.parse(e))}toString(e=Po.default){return super.toString(e)}}class mu extends Jn{constructor(e=new Date().getDate(),t=gt.day){super(e,t)}static fromString(e,t=Be.get(mu)){const i=t.parse(e);return new mu(i)}toString(e=Po.default){return super.toString(e)}}class gu extends Jn{constructor(e=new Date().getHours(),t=gt.hour){super(e,t)}static fromString(e,t=Be.get(gu)){return new gu(t.parse(e))}toString(e=Po.default){return super.toString(e)}}class vu extends Jn{constructor(e=new Date().getMinutes(),t=gt.minute){super(e,t)}static fromString(e,t=Be.get(vu)){return new vu(t.parse(e))}toString(e=Po.default){return super.toString(e)}}class bu extends Jn{constructor(e=new Date().getSeconds(),t=gt.second){super(e,t)}static fromString(e,t=Be.get(bu)){return new bu(t.parse(e),gt.second)}toString(e=Po.default){return super.toString(e)}}class Dl extends Jn{static renderer=new Po("0",3);constructor(e,t=gt.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=Dl.renderer){return super.toString(e)}}class e5{render(e){return e.toString()}}class t5 extends e5{render(e){const t=e.value,i=Math.abs(t),s=Math.floor(i/60),n=i%60;if(s===0&&n===0)return"Z";{const r=t<0?"-":"+",a=s.toString().padStart(2,"0"),o=n>0?":"+n.toString().padEnd(2,"0"):"";return r+a+o}}}class Ml{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=Be.get(Ml),i=void 0){const s=t.parse(e,i);return new Ml(s)}toString(e=new t5){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class $n{static timeshift(e,t){return e+($n.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:s}=e,n=e.hour??12;if(![t,i,s].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=$n.rule(t);if(!r)return!1;const a=$n.rank(i,s,n);return a>=$n.rank(r.start.month,r.start.day,2)&&a<$n.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:$n.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:$n.sunday(e,3,2)},end:{month:11,day:$n.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:$n.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:$n.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const s=new Date(Date.UTC(2e3,t-1,1));s.setUTCFullYear(e);const n=1+(7-s.getUTCDay())%7;if(i>0)return n+7*(i-1);const r=[31,$n.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=n;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const i5={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},s5={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},n5={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},r5={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},a5={name:"PT",timeshift:l=>$n.timeshift(-480,l),title:"Pacific Time (US)"},o5={name:"MT",timeshift:l=>$n.timeshift(-420,l),title:"Mountain Time (US)"},c5={name:"CT",timeshift:l=>$n.timeshift(-360,l),title:"Central Time (US)"},l5={name:"ET",timeshift:l=>$n.timeshift(-300,l),title:"Eastern Time (US)"},h5={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},d5={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},u5={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},p5={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},f5={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},m5={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},g5={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},v5={name:"Z",timeshift:"Z",title:"UTC"},b5={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},y5={name:"BST",timeshift:"+01",title:"British Summer Time"},w5={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},M5={name:"CET",timeshift:"+01",title:"Central European Time"},x5={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},E5={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},S5={name:"BJT",timeshift:"+08",title:"Beijing Time"},A5={name:"CST",timeshift:"-06",title:"Central Standard Time"},T5={name:"JST",timeshift:"+09",title:"Japan Standard Time"},I5={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},_5={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},D5={name:"LST",timeshift:"?",title:"Local Sideral Time"},ox=[m5,I5,f5,S5,y5,A5,d5,M5,w5,c5,h5,p5,u5,l5,b5,E5,T5,D5,n5,x5,r5,o5,_5,s5,i5,a5,g5,v5];class Zg{static instance=new Zg;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const s=t.join("-"),n=e.timeshift?e.timeshift.toString():"",r=i.join(":")+n;return s+(r.length>0?"T"+r:"")}}class Xl extends zr{constructor(e="method is abstract"){super(e)}}class _w{units;constructor(e){this.units=e}newYear(e){throw new Xl}newMonth(e){throw new Xl}newDay(e){throw new Xl}newHour(e){throw new Xl}newMinute(e){throw new Xl}newSecond(e){throw new Xl}}class k5 extends Iw{millisecond=new Pi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Pi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Pi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Pi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Pi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Pi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Pi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Wf=new k5;class Jg{static instance=new Jg;render(e){const t=Ha.toSpec(e);let i="P";const s=t.years;s&&(i+=s.toString()+"Y");const n=t.months;n&&(i+=n.toString(xo.instance)+"MM");const r=t.days;r&&(i+=r.toString(xo.instance)+"D");const a=t.hours;a&&(i+=a.toString(xo.instance)+"H");const o=t.minutes;o&&(i+=o.toString(xo.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(xo.instance)+"S"),i}}class Ha extends Jn{constructor(e={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof e=="number"?e:+(e.years?e.years*gt.year.duration:0)+(e.months?e.months*gt.month.duration:0)+(e.days?e.days*gt.day.duration:0)+(e.hours?e.hours*gt.hour.duration:0)+(e.minutes?e.minutes*gt.minute.duration:0)+(e.seconds?e.seconds*gt.second.duration:0)},new Pi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=C5){let i=typeof e=="number"?e:e.value;const s=i>0?1:-1;i=Math.abs(i);const n={},r=i/gt.year.duration,a=Math.floor(r);a>0&&(n.years=t.newYear(s*a),i-=a*gt.year.duration);const o=i/gt.month.duration,c=Math.floor(o);c>0&&(n.months=t.newMonth(s*c),i-=c*gt.month.duration);const h=i/gt.day.duration,d=Math.floor(h);d>0&&(n.days=t.newDay(s*d),i-=d*gt.day.duration);const u=i/gt.hour.duration,p=Math.floor(u);p>0&&(n.hours=t.newHour(s*p),i-=p*gt.hour.duration);const f=i/gt.minute.duration,m=Math.floor(f);m>0&&(n.minutes=t.newMinute(s*m),i-=m*gt.minute.duration);const g=i/gt.second.duration,v=Math.floor(s*g);return v>0&&(n.seconds=t.newSecond(v)),n}static fromString(e,t=Be.get(Ha)){return new Ha(t.parse(e))}static between(e,t){const i=t.getTime(),s=e.getTime();return new Ha(i-s)}toSpec(){return Ha.toSpec(this)}toString(e=Jg.instance){return e.render(this)}}class xT extends _w{constructor(e){super(e)}newYear(e){return new pu(e,this.units.year)}newMonth(e){return new fu(e,this.units.month)}newDay(e){return new mu(e,this.units.day)}newHour(e){return new gu(e,this.units.hour)}newMinute(e){return new vu(e,this.units.minute)}newSecond(e){return new bu(e,this.units.second)}newMillisecond(e){return new Dl(e,this.units.millisecond)}newTimeshift(e){return new Ml(typeof e=="number"?e:e.value)}}const R5=new xT(gt),C5=new xT(Wf);class En{#e;#t;#i;#s;#n;#r;#a;#o;constructor(e={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:En.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof Jn?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof Jn?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof Jn?e:this.factory.newDay(e)}get hour(){return this.#s}set hour(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newHour(e):!e||e.start||e instanceof Jn?e:this.factory.newHour(e)}get minute(){return this.#n}set minute(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newMinute(e):!e||e.start||e instanceof Jn?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof Jn?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof Jn)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof Ml)?this.factory.newTimeshift(e):e}get factory(){return R5}static fromString(e,t=Be.get(En)){const{year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:c,timeshift:h}=t.parse(e);return new En({year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new En({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:En.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return En.fromString(i)}#c(e){if(this.constructor.name!==e.constructor.name)throw new jg(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#c(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new Ha(t)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new En(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Zg.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const s=this.day?.toSpec();s&&(e.day=s);const n=this.hour?.toSpec();n&&(e.hour=n);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const o=this.millisecond?.toSpec();o&&(e.millisecond=o);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class Dw{static instance=new Dw;render(e){return(e.start?e.start.toString():"")+"/"+(e.end?e.end.toString():"")}}class qp{constructor(e,t){this.start=e,this.end=t}_start;get start(){return this._start}set start(e){if(typeof e=="string"&&(e=En.fromString(e)),e&&!(e instanceof En)&&!(e instanceof Ha))throw new zr("Interval start is not a level 0 date or duration: "+e);this._start=e}_end;get end(){return this._end}set end(e){if(typeof e=="string"&&(e=En.fromString(e)),e&&!(e instanceof En)&&!(e instanceof Ha))throw new zr("Interval end is not a level 0 date or duration: "+e);this._end=e}static fromString(e,t=Be.get(qp)){const{start:i,end:s}=t.parse(e);return new qp(i,s)}toString(e=Dw.instance){return e.render(this)}[Symbol.iterator](){let e=this.start;return{next:()=>{const t={done:e>this.end,value:e};return e++,t}}}}class $f extends xo{static instance=new $f(Po.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class Co extends Jn{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=$f.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class ET extends wT{year=new Pi("year",-9999,9999,this.month);yearExtended=new Pi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const R0=new ET;class sl extends Co{constructor(e,t=R0.year){super(e,t)}static fromString(e,t=R0.year,i=Be.get(sl)){const s=i.parse(e),n=s.value.start;if(e.startsWith("Y")&&(t=R0.yearExtended),n!==void 0){const r=new sl(Object.assign({...s},{value:Math.max(n,t.min)})),a=new sl(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new sl(s,t)}}class ST extends jg{monthValidator=new MT;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class nl extends Co{constructor(e,t=new Pi(gt.month.name,1,24,gt.day,new ST)){super(e,t)}static fromString(e,t=Be.get(nl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=gt.month;const r=new nl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new nl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new nl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class rl extends Co{constructor(e,t=gt.day){super(e,t)}static fromString(e,t=Be.get(rl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=gt.day;const r=new rl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new rl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new rl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class al extends Co{constructor(e,t=gt.hour){super(e,t)}static fromString(e,t=Be.get(al)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=gt.hour;const r=new al(Object.assign({...i},{value:Math.max(s,n.min)})),a=new al(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new al(i)}}class ol extends Co{constructor(e,t=gt.minute){super(e,t)}static fromString(e,t=Be.get(ol)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.minute,r=new ol(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ol(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ol(i)}toString(e=$f.instance){return super.toString(e)}}class cl extends Co{constructor(e,t=gt.second){super(e,t)}static fromString(e,t=Be.get(cl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.second,r=new cl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new cl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new cl(i)}}class Th extends Ml{static fromString(e,t=Be.get(Th),i=void 0){return new Th(t.parse(e,i))}}class AT extends _w{constructor(e){super(e)}newYear(e){return new sl(e,this.units.year)}newMonth(e){return new nl(e,this.units.month)}newDay(e){return new rl(e,this.units.day)}newHour(e){return new al(e,this.units.hour)}newMinute(e){return new ol(e,this.units.minute)}newSecond(e){return new cl(e,this.units.second)}newMillisecond(e){return new Dl(e,this.units.millisecond)}newTimeshift(e){return new Th(typeof e=="number"?e:e.value)}}const O5=new AT(R0),L5=new AT(Wf);class Fr extends En{constructor(e){super(e)}get factory(){return O5}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(e){return new Fr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:En.timeshiftOf(e)})}static fromString(e,t=Be.get(Fr)){const i=t.parse(e);return new Fr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Fr.fromString(i)}clone(){return new Fr(this.toSpec())}}const nn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class Qg extends Jg{static instance=new Qg;render(e){return super.render(e)}}class Zs extends Co{constructor(e){super(typeof e=="number"||e.hasOwnProperty("value")?e:{value:Zs.getValue(e,nn.year)+Zs.getValue(e,nn.month)+Zs.getValue(e,nn.day)+Zs.getValue(e,nn.hour)+Zs.getValue(e,nn.minute)+Zs.getValue(e,nn.second),uncertain:Zs.getBoolean(e,nn.uncertain),approximate:Zs.getBoolean(e,"approximate")},Wf.millisecond)}static getBoolean(e,t){return e[t]||e[nn.year+"s"]?.[t]||e[nn.month+"s"]?.[t]||e[nn.day+"s"]?.[t]||e[nn.hour+"s"]?.[t]||e[nn.minute+"s"]?.[t]||e[nn.second+"s"]?.[t]||!1}static getValue(e,t){let i=0,s=e[t+"s"];if(s instanceof Co?s=s.value:typeof e=="number"&&(s=e),s){const n=gt[t];i=s*n.duration}return i}static toSpec(e,t=L5){return{...Ha.toSpec(e,t),uncertain:e.uncertain||!1,approximate:e.approximate||!1}}static fromString(e,t=Be.get(Zs)){const i=t.parse(e);return new Zs(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new Zs(i-s)}toString(e=Qg.instance){return super.toString(e)}toSpec(){return Zs.toSpec(this)}}class jp extends qp{constructor(e,t){super(e,t)}get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=Fr.fromString(e)),e&&!(e instanceof Fr)&&!(e instanceof Zs))throw new zr("Interval start is not a level 1 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=Fr.fromString(e)),e&&!(e instanceof Fr)&&!(e instanceof Zs))throw new zr("Interval end is not a level 1 date or duration: "+e);this._end=e}static fromString(e,t=Be.get(jp)){const{start:i,end:s}=t.parse(e);return new jp(i,s)}}class ku extends Co{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class P5 extends ET{year=new Pi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Ry=new P5;class rc extends ku{constructor(e,t=Ry.year){super(e,t)}static fromString(e,t=Ry.year,i=Be.get(rc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new rc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new rc(Object.assign({...s},{value:Math.min(s.value.end,t.max)})),o={start:r,end:a},c=s.value.estimate;return c&&(o.estimate=c),o}else return new rc(s)}}class N5 extends ST{validate(e){switch(e){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(e)}}}class ac extends ku{constructor(e,t=new Pi(gt.month.name,1,41,gt.day,new N5)){super(e,t)}static fromString(e,t=Be.get(ac)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.month,r=new ac(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ac(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ac(i)}toString(e){return super.toString(e).padStart(2,"0")}}class oc extends ku{constructor(e,t=gt.day){super(e,t)}static fromString(e,t=Be.get(oc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.day,r=new oc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new oc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new oc(i)}toString(e){return super.toString(e).padStart(2,"0")}}class cc extends ku{constructor(e,t=gt.hour){super(e,t)}static fromString(e,t=Be.get(cc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.hour,r=new cc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new cc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new cc(i)}}class lc extends ku{constructor(e,t=gt.minute){super(e,t)}static fromString(e,t=Be.get(lc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=gt.minute,r=new lc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new lc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new lc(i)}}class hc extends ku{constructor(e,t=gt.second){super(e,t)}static fromString(e,t=gt.second,i=Be.get(hc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new hc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new hc(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new hc(s,t)}}class TT extends Th{}class F5 extends $f{qualifier(){return""}}class Hc extends Zg{static instance=new Hc;static valueRenderer=new F5(Po.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],s=Hc.names.slice(Hc.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),n=Hc.qualifier(i.uncertainComponent,i.approximateComponent),r=Hc.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!s.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!s.some(a=>a.approximate));return n+i.toString(Hc.valueRenderer)+r}}class IT extends _w{constructor(e){super(e)}newYear(e){return new rc(e,this.units.year)}newMonth(e){return new ac(e,this.units.month)}newDay(e){return new oc(e,this.units.day)}newHour(e){return new cc(e,this.units.hour)}newMinute(e){return new lc(e,this.units.minute)}newSecond(e){return new hc(e,this.units.second)}newMillisecond(e){return new Dl(e,this.units.millisecond)}newTimeshift(e){return new TT(typeof e=="number"?e:e.value)}}const U5=new IT(Ry),B5=new IT(Wf);class br extends Fr{constructor(e){super(e)}toString(e=Hc.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return U5}static fromDate(e){return new br({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:En.timeshiftOf(e)})}static fromString(e,t=Be.get(br)){const i=t.parse(e);return new br(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return br.fromString(i)}clone(){return new br(this.toSpec())}}class Sc{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new zr(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Xl(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class Dd extends Qg{static instance=new Dd;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(e,t){return e?t?"%":"?":t?"~":""}render(e){const t=Dd.qualifier(e.uncertainDuration,e.approximateDuration);if(!e.hasQualifiedComponent)return t+super.render(e);let i=t+"P";for(const[s,n]of Dd.designators){const r=e.components[s];r&&(i+=Dd.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+n)}return i}}class qs extends Zs{#e;constructor(e){if(super(typeof e=="number"?e:{value:qs.valueFromSpec(e),uncertain:e.uncertain===!0,approximate:e.approximate===!0},Wf.millisecond),typeof e!="number"){const t={};for(const i of qs.componentNames)e[i]instanceof Co&&(t[i]=e[i]);Object.keys(t).length>0&&(this.#e=t)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#e}#t(e){return this.#e?Object.values(this.#e).some(t=>t[e]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#t("uncertain")}set uncertain(e){super.uncertain=e}get approximate(){return super.approximate||this.#t("approximate")}set approximate(e){super.approximate=e}get hasQualifiedComponent(){return this.#e?Object.values(this.#e).some(e=>e.uncertainComponent||e.approximateComponent):!1}static valueFromSpec(e){return qs.getValue(e,nn.year)+qs.getValue(e,nn.month)+qs.getValue(e,nn.day)+qs.getValue(e,nn.hour)+qs.getValue(e,nn.minute)+qs.getValue(e,nn.second)}static toSpec(e,t=B5){const i=Zs.toSpec(e,t);if(e instanceof qs&&e.hasQualifiedComponent)for(const s of qs.componentNames)delete i[s],e.components[s]&&(i[s]=e.components[s]);return i}static fromString(e,t=Be.get(qs)){const i=t.parse(e);return new qs(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new qs(i-s)}toSpec(){return qs.toSpec(this)}toString(e=Dd.instance){return super.toString(e)}}class Zp extends jp{get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=br.fromString(e)),e&&!(e instanceof br)&&!(e instanceof qs))throw new zr("Interval start is not a level 2 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=br.fromString(e)),e&&!(e instanceof br)&&!(e instanceof qs))throw new zr("Interval end is not a level 2 date or duration: "+e);this._end=e}static fromString(e,t=Be.get(Zp)){const{start:i,end:s}=t.parse(e);return new Zp(i,s)}}class q0 extends Set{constructor(e,t){super(e),this.exclusive=t}has(e){const t=e.toString().replace("..","/");for(const i of this)if(i.toString()===t)return!0;return!1}static fromString(e,t=Be.get(q0)){const{exclusive:i,values:s}=t.parse(e);return new q0(s,i)}}class Ac extends Sc{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return Ac.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new zr(`${this.name} cannot be negative`);return super.parse(e)}}class U{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return U.optional(U.group(e,...t))}static optionalNonCapturingGroup(...e){return U.optional(U.nonCapturingGroup(...e))}static numberGroup(e,t,i,s="\\d"){return U.group(e,`${i||""}[${s}]${t}`)}}const cx="yearValue";class Jp extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,cx),"{4}",void 0)}constructor(){super(cx,Jp.format())}}const lx="monthValue";class Qp extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,lx),"{1,2}",void 0)}constructor(){super(lx,Qp.format())}}const hx="dayValue";class jd extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,hx),"{1,2}",void 0)}constructor(){super(hx,jd.format())}}const dx="hourValue";class Zd extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,dx),"{1,2}",void 0)}constructor(){super(dx,Zd.format())}}const ux="minuteValue";class ef extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,ux),"{1,2}",void 0)}constructor(){super(ux,ef.format())}}const px="secondValue";class tf extends Ac{static format(e=""){return U.numberGroup(U.groupName(e,px),"{1,2}",void 0)}constructor(){super(px,tf.format())}}const fx="timeshiftValue",mx="shiftHour",gx="shiftMinute";class yu extends Sc{static format(e=""){return ox.map(t=>t.name).join("|")+"|"+U.nonCapturingGroup(U.group(e+mx,U.numberGroup(U.groupName(e,fx),"{2}","[+-]")),U.optionalNonCapturingGroup(":?",U.numberGroup(U.groupName(e,gx),"{2}",void 0)))}constructor(){super(fx,yu.format())}parse(e,t){let i=0;const s=ox.find(n=>n.name===e);if(s){if(typeof s.timeshift=="function")try{return s.timeshift(t??{})}catch(n){throw new zr(`The time zone ${e} depends on the date: ${n.message}`)}e=s.timeshift}if(e!=="Z"){const n=this.regexGroups(e),r=n[mx];r&&(i+=parseInt(r,10)*60);const a=n[gx];a&&(i+=parseInt(a,10))}return i}}const vx="year",bx="month",yx="day",wx="hour",Mx="minute",xx="second",Ex="millisecond",Sx="timeshift";class ih extends Sc{static format(e=""){return U.group(U.groupName(e,vx),Jp.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,bx),Qp.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,yx),jd.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,wx),Zd.format(e)),":?",U.group(U.groupName(e,Mx),ef.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,xx),tf.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,Ex),"\\d+"))),"\\s*",U.optionalGroup(U.groupName(e,Sx),yu.format(e)))))}constructor(){super("date",ih.format())}parse(e){const t=this.regexGroups(e),i=t[vx],s=t[bx],n=t[yx],r=t[wx],a=t[Mx],o=t[xx],c=t[Ex],h=t[Sx],d=i?new pu(Jp.read(i)):void 0,u=s?Qp.read(s):void 0;return{year:d,month:u?new fu(u,_d.create(u.value,d?.value)):void 0,day:n?new mu(jd.read(n)):void 0,hour:r?new gu(Zd.read(r)):void 0,minute:a?new vu(ef.read(a)):void 0,second:o?new bu(tf.read(o)):void 0,millisecond:c?Dl.parseFraction(c):void 0,timeshift:h?Ml.fromString(h,new yu,{year:d?.value,month:u?.value,day:n?jd.read(n).value:void 0,hour:r?Zd.read(r).value:void 0}):void 0}}}const Ax="years",Iv="months",z5="days",Tx="hours",Ix="minutes",_x="seconds";class kw extends Sc{static format(e=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Ax),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Iv),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,z5),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Tx),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Ix),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,_x),"+",void 0,"\\d"),"S")}constructor(){super("duration",kw.format())}parseGroups(e){return{years:e[Ax],months:e[Iv],days:e[Iv],hours:e[Tx],minutes:e[Ix],seconds:e[_x]}}}const _v="start",Dv="end";class Rw extends Sc{static format=U.group(_v,ih.format(_v))+"/"+U.group(Dv,ih.format(Dv));constructor(){super("interval",Rw.format)}parse(e){const t=this.regexGroups(e),i=t[_v],s=t[Dv];return{start:i?En.fromString(i,new ih):void 0,end:s?En.fromString(s,new ih):void 0}}}Be.register(En,()=>new ih);Be.register(mu,()=>new jd);Be.register(Ha,()=>new kw);Be.register(gu,()=>new Zd);Be.register(qp,()=>new Rw);Be.register(vu,()=>new ef);Be.register(fu,()=>new Qp);Be.register(bu,()=>new tf);Be.register(Ml,()=>new yu);Be.register(pu,()=>new Jp);class Zi extends Ac{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Zi.uncertainGroup+Zi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return U.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(U.groupName(Zi.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(Zi.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(Zi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return U.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let s=0,n;for(n=0;n<t.length;n++){const c=t[n];if(c==="X")break;s=s*10+parseInt(c,10)}if(n<t.length){let c=1;for(let u=0;u<t.length-n;u++)c*=10;const h=i*s*c,d=h+c-1;s={start:h,end:d}}else s*=i;const r=e[U.groupName(Zi.uncertainAndApproximateGroup,this.name)],a=e[U.groupName(Zi.approximateGroup,this.name)]||r,o=e[U.groupName(Zi.uncertainGroup,this.name)]||r;return{value:s,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const Dx="yearValue";class sf extends Zi{constructor(){super(Dx,sf.format())}static format(e=""){return"Y?"+Zi.numberFormat(U.groupName(e,Dx),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const kx="monthValue";class nf extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,kx),"{1,2}",void 0)}constructor(){super(kx,nf.format())}}const Rx="dayValue";class rf extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Rx),"{1,2}",void 0)}constructor(){super(Rx,rf.format())}}const Cx="hourValue";class af extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Cx),"{1,2}",void 0)}constructor(){super(Cx,af.format())}}const Ox="minuteValue";class of extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Ox),"{1,2}",void 0)}constructor(){super(Ox,of.format())}}const Lx="secondValue";class cf extends Zi{static format(e=""){return Zi.numberFormat(U.groupName(e,Lx),"{1,2}",void 0)}constructor(){super(Lx,cf.format())}}class lf extends yu{}class os extends Sc{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(e=os.format()){super("date",e)}static format(e=""){return U.group(U.groupName(e,os.yearGroup),sf.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,os.monthGroup),nf.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,os.dayGroup),rf.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,os.hourGroup),af.format(e)),":",U.group(U.groupName(e,os.minuteGroup),of.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,os.secondGroup),cf.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,os.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(e,os.timeshiftGroup),lf.format(e)))))}parseGroups(e){const t=e[os.millisecondGroup],i=t?Dl.parseFraction(t):void 0,s=e[os.secondGroup],n=s?cl.fromString(s,new cf):void 0,r=e[os.minuteGroup];let a;r&&(a=ol.fromString(r,new of),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[os.hourGroup];let c;o&&(c=al.fromString(o,new af),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[os.dayGroup];let d;h&&(d=rl.fromString(h,new rf),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[os.monthGroup];let p;u&&(p=nl.fromString(u,new nf),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[os.yearGroup];let m;f&&(m=sl.fromString(f,void 0,new sf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[os.timeshiftGroup],v=g?Th.fromString(g,new lf,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:n,millisecond:i,timeshift:v}}}const Px="years",Nx="months",Fx="days",Ux="hours",Bx="minutes",zx="seconds";class sh extends Zi{static format(e=""){return"P"+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Px),"+",void 0,"\\d"),"Y")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Nx),"+",void 0,"\\d"),"MM")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Fx),"+",void 0,"\\d"),"D")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Ux),"+",void 0,"\\d"),"H")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,Bx),"+",void 0,"\\d"),"M")+U.optionalNonCapturingGroup(U.numberGroup(U.groupName(e,zx),"+",void 0,"\\d"),"S")+this.formatSuffix(e)}constructor(){super("duration",sh.format())}parseGroups(e){return{years:e[Px],months:e[Nx],days:e[Fx],hours:e[Ux],minutes:e[Bx],seconds:e[zx],uncertain:!!e[Zi.uncertainGroup],approximate:!!e[Zi.approximateGroup]}}}const H5="dates",kv="start",Rv="end",Hx="durations",Cv="durationMin",Ov="durationMax";class Cw extends Sc{static format=U.group(H5,U.optionalGroup(kv,U.group("openStart","\\.\\.")+"|"+os.format(kv))+"/"+U.optionalGroup(Rv,U.group("openEnd","\\.\\.")+"|"+os.format(Rv)))+"|"+U.group(Hx,U.group(Cv,sh.format(Cv))+"/"+U.group(Ov,sh.format(Ov)));constructor(e="interval",t=Cw.format){super(e,t)}parseGroups(e){let t,i;if(e[Hx]){const n=e[Cv];t=Zs.fromString(n,new sh);const r=e[Ov];i=Zs.fromString(r,new sh)}else{const n=e[kv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=Fr.fromString(n,new os)}const r=e[Rv];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Fr.fromString(r,new os)}}return{start:t,end:i}}}Be.register(Fr,()=>new os);Be.register(rl,()=>new rf);Be.register(Zs,()=>new sh);Be.register(al,()=>new af);Be.register(jp,()=>new Cw);Be.register(ol,()=>new of);Be.register(nl,()=>new nf);Be.register(cl,()=>new cf);Be.register(Th,()=>new lf);Be.register(sl,()=>new sf);class oi extends Zi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=oi.uncertainGroup+oi.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(U.groupName(oi.uncertainGroup,e),"?")+this.qualifierFormat(U.groupName(oi.approximateGroup,e),"~")+this.qualifierFormat(U.groupName(oi.uncertainAndApproximateGroup,e),"%")+Zi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[U.groupName(oi.uncertainAndApproximateGroup,this.name)];return(e[U.groupName(oi.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[U.groupName(oi.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Pu="yearValue",Gx="exp",Vx="signif";class hf extends oi{constructor(){super(Pu,hf.format())}static format(e=""){return"Y?"+U.nonCapturingGroup(U.group(U.groupName(e,Gx),"[-]?\\d+E\\d+")+"|"+oi.numberFormat(U.groupName(e,Pu),"+","[-]?")+U.optionalGroup(U.groupName(e,Vx),"S\\d+"))}parseGroups(e){const t=e[Gx];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[Pu]=c.toString()}const i=e[Vx],s=e[Pu];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:o}=this.getValueAndSign(e);let c="";for(let h=0;h<a.length;h++)c+=h<r?a.charAt(h):"X";e[Pu]=(o<0?"-":"")+c}const n=super.parseGroups(e);return i&&(n.value.estimate=parseInt(s,10)),n}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const Wx="monthValue";class df extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Wx),"{1,2}",void 0)}constructor(){super(Wx,df.format())}}const $x="dayValue";class uf extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,$x),"{1,2}",void 0)}constructor(){super($x,uf.format())}}const Kx="hourValue";class pf extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Kx),"{1,2}",void 0)}constructor(){super(Kx,pf.format())}}const Xx="secondValue";class ff extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Xx),"{1,2}",void 0)}constructor(){super(Xx,ff.format())}}const Yx="minuteValue";class mf extends oi{static format(e=""){return oi.numberFormat(U.groupName(e,Yx),"{1,2}",void 0)}constructor(){super(Yx,mf.format())}}class G5 extends lf{}class fi extends Sc{static yearGroup=os.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",fi.format())}static format(e=""){return U.group(U.groupName(e,fi.yearGroup),hf.format(e))+U.optionalNonCapturingGroup("-",U.group(U.groupName(e,fi.monthGroup),df.format(e)),U.optionalNonCapturingGroup("-",U.group(U.groupName(e,fi.dayGroup),uf.format(e)),U.optionalNonCapturingGroup("[T ]",U.group(U.groupName(e,fi.hourGroup),pf.format(e)),":",U.group(U.groupName(e,fi.minuteGroup),mf.format(e)),U.optionalNonCapturingGroup(":",U.group(U.groupName(e,fi.secondGroup),ff.format(e)),U.optionalNonCapturingGroup("[.,]",U.group(U.groupName(e,fi.millisecondGroup),"\\d+"))),U.optionalGroup(U.groupName(e,fi.timeshiftGroup),G5.format(e)))))}parseGroups(e){const t=e[fi.millisecondGroup],i=t?Dl.parseFraction(t):void 0,s=e[fi.secondGroup];let n;s&&(n=hc.fromString(s,void 0,new ff),n.uncertain=n?.uncertain||!1,n.approximate=n?.approximate||!1);const r=e[fi.minuteGroup];let a;r&&(a=lc.fromString(r,new mf),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[fi.hourGroup];let c;o&&(c=cc.fromString(o,new pf),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[fi.dayGroup];let d;h&&(d=oc.fromString(h,new uf),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[fi.monthGroup];let p;u&&(p=ac.fromString(u,new df),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[fi.yearGroup];let m;f&&(m=rc.fromString(f,void 0,new hf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[fi.timeshiftGroup],v=g?TT.fromString(g,new lf,{year:m?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:m,month:p,day:d,hour:c,minute:a,second:n,millisecond:i,timeshift:v}}}const qx="durationValue";class Ow extends oi{static format(e=""){return"^"+oi.numberFormat(U.groupName(e,qx),"+",void 0)}constructor(){super(qx,Ow.format())}}class V5 extends Iw{millisecond=new Pi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new Pi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Pi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new Pi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new Pi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new Pi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new Pi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const Uh=new V5;class ht extends oi{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new Ow;static componentFormat(e,t,i,s,n=""){const r=U.group(U.groupName(e,ht.quantityGroup(t)),oi.numberFormat(U.groupName(e,i),"+",void 0,"\\d"));return U.group(U.groupName(e,t),r,s,n)}static quantityGroup(e){return e+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",ht.format())}static format(e=""){const t=U.groupName(e,ht.durationGroup);return this.qualifierFormat(U.groupName(oi.uncertainGroup,t),"?")+this.qualifierFormat(U.groupName(oi.approximateGroup,t),"~")+this.qualifierFormat(U.groupName(oi.uncertainAndApproximateGroup,t),"%")+"P"+U.optional(ht.componentFormat(e,ht.yearsGroup,fi.yearGroup,"Y"))+U.optionalNonCapturingGroup(ht.componentFormat(e,ht.monthsGroup,fi.monthGroup,"MM")+"|"+ht.componentFormat(e,ht.isoMonthsGroup,"isoMonth","M",ht.isoMonthsLookahead))+U.optional(ht.componentFormat(e,ht.daysGroup,fi.dayGroup,"D"))+"T?"+U.optional(ht.componentFormat(e,ht.hoursGroup,fi.hourGroup,"H"))+U.optional(ht.componentFormat(e,ht.minutesGroup,fi.minuteGroup,"M"))+U.optional(ht.componentFormat(e,ht.secondsGroup,fi.secondGroup,"S"))+U.optionalGroup(U.groupName(e,ht.suffixGroup),"[?~%]")}static parseComponent(e,t,i){const s=ht.componentParser.parse(e);return new t(s,i)}parseGroups(e){const t=e[ht.quantityGroup(ht.secondsGroup)];let i;t&&(i=ht.parseComponent(t,hc,Uh.second),i.uncertain=!!e[U.groupName(oi.uncertainGroup,ht.secondsGroup)]||!1,i.approximate=!!e[U.groupName(oi.approximateGroup,ht.secondsGroup)]||!1);const s=e[ht.quantityGroup(ht.minutesGroup)];let n;s&&(n=ht.parseComponent(s,lc,Uh.minute),n.uncertain=n.uncertain||i?.uncertain||!1,n.approximate=n.approximate||i?.approximate||!1);const r=e[ht.quantityGroup(ht.hoursGroup)];let a;r&&(a=ht.parseComponent(r,cc,Uh.hour),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[ht.quantityGroup(ht.daysGroup)];let c;o&&(c=ht.parseComponent(o,oc,Uh.day),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[ht.quantityGroup(ht.monthsGroup)]||e[ht.quantityGroup(ht.isoMonthsGroup)];let d;h&&(d=ht.parseComponent(h,ac,Uh.month),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[ht.quantityGroup(ht.yearsGroup)];let p;u&&(p=ht.parseComponent(u,rc,Uh.year),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ht.suffixGroup],m=!!e[U.groupName(oi.uncertainAndApproximateGroup,ht.durationGroup)]||f==="%",g=m||!!e[U.groupName(oi.uncertainGroup,ht.durationGroup)]||f==="?",v=m||!!e[U.groupName(oi.approximateGroup,ht.durationGroup)]||f==="~";return{years:p,months:d,days:c,hours:a,minutes:n,seconds:i,uncertain:g,approximate:v}}}const W5="dates",Lv="start",Pv="end",jx="durations",Nv="durationMin",Fv="durationMax";class ev extends Sc{static format=U.group(W5,U.optionalGroup(Lv,U.group("openStart","\\.\\.")+"|"+fi.format(Lv))+"/"+U.optionalGroup(Pv,U.group("openEnd","\\.\\.")+"|"+fi.format(Pv)))+"|"+U.group(jx,U.group(Nv,ht.format(Nv))+"/"+U.group(Fv,ht.format(Fv)));constructor(e="interval",t=ev.format){super(e,t)}parseGroups(e){let t,i;if(e[jx]){const n=e[Nv];t=qs.fromString(n,new ht);const r=e[Fv];i=qs.fromString(r,new ht)}else{const n=e[Lv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=br.fromString(n,new fi)}const r=e[Pv];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=br.fromString(r,new fi)}}return{start:t,end:i}}}class $5{parse(e){e=e.trim();const t=e.startsWith("["),s=e.substring(1,e.length-1).split(","),n=[];for(const r of s){let a;r.includes("..")?a=Zp.fromString(r.replace("..","/"),new ev):a=br.fromString(r,new fi),n.push(a)}return{values:n,exclusive:t}}}Be.register(br,()=>new fi);Be.register(oc,()=>new uf);Be.register(qs,()=>new ht);Be.register(cc,()=>new pf);Be.register(Zp,()=>new ev);Be.register(lc,()=>new mf);Be.register(ac,()=>new df);Be.register(hc,()=>new ff);Be.register(q0,()=>new $5);Be.register(rc,()=>new hf);class Bs{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[Bs.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>Bs.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(Bs.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(c=>c===i))!==null&&s!==void 0?s:Object.keys(a).find(c=>Bs.base(c)===Bs.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}Bs.any=new Bs([]);var Zx;(function(l){l.abductee="abductee",l.actor="actor",l.artist="artist",l.anthropologist="anthropologist",l.archeologist="archeologist",l.astronaut="astronaut",l.astronomer="astronomer",l.astrologist="astrologist",l.astrophysicist="astrophysicist",l.banker="banker",l.barman="barman",l.biologist="biologist",l.biochemist="biochemist",l.biophysicist="biophysicist",l.bishop="bishop",l.businessman="businessman",l.botanist="botanist",l.cameraman="cameraman",l.chemist="chemist",l.contactee="contactee",l.cryptozoologist="cryptozoologist",l.dentist="dentist",l.director="director",l.diplomat="diplomat",l.diver="diver",l.electronics="electronics",l.engineer="engineer",l.ethnologist="ethnologist",l.exobiologist="exobiologist",l.farmer="farmer",l.firefighter="firefighter",l.flightAttendant="flightAttendant",l.geologist="geologist",l.geophysicist="geophysicist",l.geographer="geographer",l.historian="historian",l.houseWife="houseWife",l.hypnotherapist="hypnotherapist",l.illusionist="illusionist",l.journalist="journalist",l.judge="judge",l.lawyer="lawyer",l.leader="leader",l.librarian="librarian",l.logger="logger",l.mathematician="mathematician",l.mechanic="mechanic",l.meteorologist="meteorologist",l.military="military",l.musician="musician",l.neurologist="neurologist",l.neuroscientist="neuroscientist",l.neuropsychiatrist="neuropsychiatrist",l.nurse="nurse",l.oceanographer="oceanographer",l.painter="painter",l.parapsychologist="parapsychologist",l.philosopher="philosopher",l.photographer="photographer",l.physician="physician",l.physicist="physicist",l.pilot="pilot",l.politician="politician",l.policeman="policeman",l.priest="priest",l.producer="producer",l.prospector="prospector",l.psychologist="psychologist",l.psychiatrist="psychiatrist",l.radioastronomer="radioastronomer",l.radioamateur="radioamateur",l.salesman="salesman",l.sailor="sailor",l.sociologist="sociologist",l.softwareEngineer="softwareEngineer",l.stuntman="stuntman",l.taxiDriver="taxiDriver",l.teacher="teacher",l.telegrapher="telegrapher",l.truckDriver="truckDriver",l.ufologist="ufologist",l.ufoWitness="ufoWitness",l.ufoWitness2="ufoWitness2",l.worker="worker",l.writer="writer"})(Zx||(Zx={}));var Jx;(function(l){l.neutral="neutral",l.male="male",l.female="female"})(Jx||(Jx={}));class K5 extends Error{constructor(e,t){super(e),this.cause=t}}class Lw extends K5{constructor(e=Lw.defaultMessage,t){super(e,t)}}Lw.defaultMessage="Assertion failed";var Qx;(function(l){l.country="country",l.region="region",l.department="department",l.city="city",l.company="company"})(Qx||(Qx={}));var eE;(function(l){l.at="at",l.au="au",l.ar="ar",l.be="be",l.br="br",l.ca="ca",l.ch="ch",l.cn="cn",l.cl="cl",l.co="co",l.cy="cy",l.de="de",l.dk="dk",l.do="do",l.dz="dz",l.gr="gr",l.ec="ec",l.eg="eg",l.es="es",l.fi="fi",l.fr="fr",l.ga="ga",l.ge="ge",l.hu="hu",l.in="in",l.ie="ie",l.ir="ir",l.il="il",l.it="it",l.jp="jp",l.kr="kr",l.ma="ma",l.mx="mx",l.my="my",l.mz="mz",l.nl="nl",l.no="no",l.nz="nz",l.pa="pa",l.pe="pe",l.ph="ph",l.pl="pl",l.pt="pt",l.ro="ro",l.ru="ru",l.sc="sc",l.tr="tr",l.ua="ua",l.uk="uk",l.us="us",l.sa="sa",l.se="se",l.su="su",l.tn="tn",l.tw="tw",l.ve="ve",l.za="za"})(eE||(eE={}));class X5{static of(e){if(!(!e||e.length===0))return e.some(t=>t.outcome==="fails"&&t.against!=="supposed")?"incompatible":e.some(t=>t.outcome!=="holds")?"unsettled":"compatible"}}/**
|
|
450
450
|
@preserve
|
|
451
451
|
|
|
452
452
|
Astronomy library for JavaScript (browser and Node.js).
|
|
@@ -4642,7 +4642,7 @@ button.open { display: inline-flex; align-items: center; gap: 6px; cursor: point
|
|
|
4642
4642
|
.option input { margin: 2px 0 0; }
|
|
4643
4643
|
${en.css(".menu")}
|
|
4644
4644
|
.menu:popover-open { position-area: bottom span-left; margin: .35em 0 0; }
|
|
4645
|
-
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(jl.TAG)||customElements.define(jl.TAG,jl)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=zs.preferencesFor(this),this.language=Wa([...this.preferences],Ga),this.messages=await X_.load(this.language),this.draw()}draw(){const e=this.messages,t=document.createElement("style");t.textContent=jl.CSS;const i=document.createElement("button");i.type="button",i.className="open",i.setAttribute("part","button"),i.title=e.hint,i.setAttribute("aria-label",e.hint),i.setAttribute("aria-haspopup","menu"),i.innerHTML=jl.ICON,this.getAttribute("variant")==="pill"&&i.append(Object.assign(document.createElement("span"),{textContent:e.button}));const s=document.createElement("div");s.className="menu",s.setAttribute("role","menu"),en.attach(i,s);const n=[["html",e.html,e.htmlHint],["print",e.print,e.printHint],["json",e.json,e.jsonHint],["csv",e.csv,e.csvHint]];s.append(...n.map(([o,c,h])=>{const d=document.createElement("button");return d.type="button",d.setAttribute("role","menuitem"),d.append(Object.assign(document.createElement("strong"),{textContent:c}),Object.assign(document.createElement("small"),{textContent:h})),d.addEventListener("click",()=>void this.export(o,s)),d}));const r=document.createElement("label");r.className="option",this.withPictures=Object.assign(document.createElement("input"),{type:"checkbox"});const a=document.createElement("span");a.append(Object.assign(document.createElement("strong"),{textContent:e.pictures}),Object.assign(document.createElement("small"),{textContent:e.picturesHint})),r.append(this.withPictures,a),s.append(r),this.status=Object.assign(document.createElement("p"),{className:"status",hidden:!0}),this.status.setAttribute("role","status"),s.append(this.status),i.addEventListener("click",()=>en.show(s,s.hidden)),this.shadowRoot.replaceChildren(t,i,s)}async export(e,t){const i=this.messages;if(this.source){this.status.textContent=i.working,this.status.hidden=!1;try{const[{CaseReportExport:s},n]=await Promise.all([H(()=>import("./CaseReportExport-D0GXupCT.js"),[],import.meta.url),this.source()]);await s.make(e,n,this.language,this.preferences,this.withPictures?.checked??!1,(r,a)=>{this.status.textContent=i.drawing.replace("{done}",String(r)).replace("{total}",String(a))}),this.status.hidden=!0,en.show(t,!1)}catch{this.status.textContent=i.failed}}}}const UN=ui.catalog({en:()=>H(()=>import("./ReadingCheckTexts_en-eq6teExJ.js"),[],import.meta.url).then(l=>l.readingCheckTexts_en),fr:()=>H(()=>import("./ReadingCheckTexts_fr-pcDleIvY.js"),[],import.meta.url).then(l=>l.readingCheckTexts_fr),es:()=>H(()=>import("./ReadingCheckTexts_es-CR_JJZMV.js"),[],import.meta.url).then(l=>l.readingCheckTexts_es),it:()=>H(()=>import("./ReadingCheckTexts_it-MFKeoXnq.js"),[],import.meta.url).then(l=>l.readingCheckTexts_it)});class fr{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Vi.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Vi.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new fr(a,new URL("case.json",n).href),c=o.tracks[0];return c.recording=e,c.base={url:s},c.event.id=o.proposedId(c),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Vi.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const c={type:"event",eventType:Vi.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],c],this.caseChanged=!0,c}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}static sealed(e){return e.sealed===!0}seal(e,t){t?e.event.sealed=!0:delete e.event.sealed,this.caseChanged=!0}clone(e,t){if(!e.recording)return;const i=e.kind==="reading"?this.accountOf(e):void 0;if(e.kind==="reading"&&!i)return;const s=t??e.event.title;return this.addObservation(structuredClone(e.recording),e.event.time,s,i?{account:i,by:e.event.by}:void 0)}keep(e,t,i=!1){!i&&fr.sealed(e.event)||(t=An.recording(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title))}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===Vi.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(c=>c.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Vi.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Vi.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!fr.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(c=>s(c)?t:c);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(c=>c!==void 0&&s(c)?t:c);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Vi.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(T=>T.event.url)),o=new Set(this.tracks.map(T=>T.recording?.id));let c=this.tracks.filter(T=>T.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${c}.json`)||o.has(`${n.id??r}-interpretation-${c}`);)c++;const h=`interpretation-${r}-${c}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:g,sources:v,tags:b,timeline:w,milestones:y,interpretation:M,...x}=structuredClone(n),S={version:4,id:`${n.id??r}-interpretation-${c}`,...x,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},E={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],E],this.caseChanged=!0;const A={event:E,url:new URL(E.url,this.url).href,kind:"reading",recording:S};return this.tracks.push(A),A}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let c=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(c)||r.has(h);m++)c=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.by}:{},...i!==void 0?{title:i}:{},url:u+c};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};if(fr.sealed(e.event))return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(s=>s!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading"||fr.sealed(e.event))return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
4645
|
+
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(jl.TAG)||customElements.define(jl.TAG,jl)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=zs.preferencesFor(this),this.language=Wa([...this.preferences],Ga),this.messages=await X_.load(this.language),this.draw()}draw(){const e=this.messages,t=document.createElement("style");t.textContent=jl.CSS;const i=document.createElement("button");i.type="button",i.className="open",i.setAttribute("part","button"),i.title=e.hint,i.setAttribute("aria-label",e.hint),i.setAttribute("aria-haspopup","menu"),i.innerHTML=jl.ICON,this.getAttribute("variant")==="pill"&&i.append(Object.assign(document.createElement("span"),{textContent:e.button}));const s=document.createElement("div");s.className="menu",s.setAttribute("role","menu"),en.attach(i,s);const n=[["html",e.html,e.htmlHint],["print",e.print,e.printHint],["json",e.json,e.jsonHint],["csv",e.csv,e.csvHint]];s.append(...n.map(([o,c,h])=>{const d=document.createElement("button");return d.type="button",d.setAttribute("role","menuitem"),d.append(Object.assign(document.createElement("strong"),{textContent:c}),Object.assign(document.createElement("small"),{textContent:h})),d.addEventListener("click",()=>void this.export(o,s)),d}));const r=document.createElement("label");r.className="option",this.withPictures=Object.assign(document.createElement("input"),{type:"checkbox"});const a=document.createElement("span");a.append(Object.assign(document.createElement("strong"),{textContent:e.pictures}),Object.assign(document.createElement("small"),{textContent:e.picturesHint})),r.append(this.withPictures,a),s.append(r),this.status=Object.assign(document.createElement("p"),{className:"status",hidden:!0}),this.status.setAttribute("role","status"),s.append(this.status),i.addEventListener("click",()=>en.show(s,s.hidden)),this.shadowRoot.replaceChildren(t,i,s)}async export(e,t){const i=this.messages;if(this.source){this.status.textContent=i.working,this.status.hidden=!1;try{const[{CaseReportExport:s},n]=await Promise.all([H(()=>import("./CaseReportExport-DisXbZ3b.js"),[],import.meta.url),this.source()]);await s.make(e,n,this.language,this.preferences,this.withPictures?.checked??!1,(r,a)=>{this.status.textContent=i.drawing.replace("{done}",String(r)).replace("{total}",String(a))}),this.status.hidden=!0,en.show(t,!1)}catch{this.status.textContent=i.failed}}}}const UN=ui.catalog({en:()=>H(()=>import("./ReadingCheckTexts_en-eq6teExJ.js"),[],import.meta.url).then(l=>l.readingCheckTexts_en),fr:()=>H(()=>import("./ReadingCheckTexts_fr-pcDleIvY.js"),[],import.meta.url).then(l=>l.readingCheckTexts_fr),es:()=>H(()=>import("./ReadingCheckTexts_es-CR_JJZMV.js"),[],import.meta.url).then(l=>l.readingCheckTexts_es),it:()=>H(()=>import("./ReadingCheckTexts_it-MFKeoXnq.js"),[],import.meta.url).then(l=>l.readingCheckTexts_it)});class fr{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Vi.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Vi.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new fr(a,new URL("case.json",n).href),c=o.tracks[0];return c.recording=e,c.base={url:s},c.event.id=o.proposedId(c),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Vi.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const c={type:"event",eventType:Vi.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],c],this.caseChanged=!0,c}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}static sealed(e){return e.sealed===!0}seal(e,t){t?e.event.sealed=!0:delete e.event.sealed,this.caseChanged=!0}clone(e,t){if(!e.recording)return;const i=e.kind==="reading"?this.accountOf(e):void 0;if(e.kind==="reading"&&!i)return;const s=t??e.event.title;return this.addObservation(structuredClone(e.recording),e.event.time,s,i?{account:i,by:e.event.by}:void 0)}keep(e,t,i=!1){!i&&fr.sealed(e.event)||(t=An.recording(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title))}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===Vi.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(c=>c.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Vi.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Vi.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!fr.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(c=>s(c)?t:c);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(c=>c!==void 0&&s(c)?t:c);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Vi.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(T=>T.event.url)),o=new Set(this.tracks.map(T=>T.recording?.id));let c=this.tracks.filter(T=>T.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${c}.json`)||o.has(`${n.id??r}-interpretation-${c}`);)c++;const h=`interpretation-${r}-${c}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:g,sources:v,tags:b,timeline:w,milestones:y,interpretation:M,...x}=structuredClone(n),S={version:4,id:`${n.id??r}-interpretation-${c}`,...x,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},E={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],E],this.caseChanged=!0;const A={event:E,url:new URL(E.url,this.url).href,kind:"reading",recording:S};return this.tracks.push(A),A}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let c=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(c)||r.has(h);m++)c=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.by}:{},...i!==void 0?{title:i}:{},url:u+c};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};if(fr.sealed(e.event))return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(s=>s!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading"||fr.sealed(e.event))return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
4646
4646
|
`})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",a=[...this.transcripts].filter(([o,c])=>e&&o.url!==void 0&&(t||this.transcriptChanged(c))).map(([o,c])=>({path:s(new URL(o.url,this.url).href),content:c.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
|
|
4647
4647
|
`},...n,...a]}}class Pf{constructor(e,t,i,s){this.button=e,this.onPick=i,this.idOf=s;const n=this.panel=e.ownerDocument.createElement("div");n.id=t,n.className="add-menu",n.setAttribute("popover",""),n.setAttribute("role","menu");const r=`--add-menu-${t}`;e.style.setProperty("anchor-name",r),n.style.setProperty("position-anchor",r),e.setAttribute("popovertarget",t),e.setAttribute("aria-haspopup","menu"),e.after(n)}static CSS=`
|
|
4648
4648
|
.add-menu { padding: .3em 0; border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); border-radius: 4px; background: Canvas; color: CanvasText;
|
|
@@ -7407,22 +7407,23 @@ ${Yd.fields(".app")}
|
|
|
7407
7407
|
/* What a click in the scene opened, pointed out for a moment. */
|
|
7408
7408
|
.flash { background: var(--warn-bg) !important; border-radius: 8px; box-shadow: 0 0 0 6px var(--warn-bg); transition: background .3s ease, box-shadow .3s ease; }
|
|
7409
7409
|
@media (prefers-reduced-motion: reduce) { .scene-card > :is(.render-line, .playback-row) { transition: none; } }
|
|
7410
|
-
/* Given the width (the app on a computer): the
|
|
7411
|
-
|
|
7410
|
+
/* Given the width (the app on a computer): the chips of the sections across the whole width, under them the render in a column of its
|
|
7411
|
+
own on the right and the section open on the left (dicté 2026-11-20 : « settings à gauche, rendu à droite »), the editor the height of the screen and the open section scrolling on its own. The chips have
|
|
7412
|
+
the whole width so that they all show on one line: in the right column alone they ran past its edge. The grip has nothing to share out between the two any more. The
|
|
7412
7413
|
width this editor is given, never the window's: held by a case, it is the case's. */
|
|
7413
|
-
@container (min-width:
|
|
7414
|
+
@container (min-width: 760px) {
|
|
7414
7415
|
.app {
|
|
7415
7416
|
/* The screen's height, or what a page that has something above it says is left (see UfoAtHomeElement). */
|
|
7416
7417
|
max-width: none; height: var(--rr0-editor-height, 100dvh); max-height: none;
|
|
7417
|
-
display: grid; grid-template-columns: minmax(
|
|
7418
|
+
display: grid; grid-template-columns: minmax(22rem, 9fr) minmax(0, 11fr);
|
|
7418
7419
|
grid-template-rows: auto auto auto auto minmax(0, 1fr);
|
|
7419
|
-
grid-template-areas: "head head" "notes notes" "
|
|
7420
|
+
grid-template-areas: "head head" "notes notes" "tabs tabs" "tracks scene" "panel scene";
|
|
7420
7421
|
}
|
|
7421
7422
|
.app > .editor-head { grid-area: head; }
|
|
7422
7423
|
.app > .save-refused { grid-area: notes; }
|
|
7423
|
-
.app > .scene-card { grid-area: scene; align-self: start; border-
|
|
7424
|
+
.app > .scene-card { grid-area: scene; align-self: start; border-left: 1px solid var(--line); }
|
|
7424
7425
|
/* As tall as the screen leaves it under the header, whatever height the grip gave it in one column. */
|
|
7425
|
-
.app > .scene-card { --rr0-scene-max-height: calc(var(--rr0-editor-height, 100dvh) -
|
|
7426
|
+
.app > .scene-card { --rr0-scene-max-height: calc(var(--rr0-editor-height, 100dvh) - 9.5rem); }
|
|
7426
7427
|
.app > .scene-resize { display: none; }
|
|
7427
7428
|
.app > #group-tabs { grid-area: tabs; }
|
|
7428
7429
|
.app > #timeline-tracks { grid-area: tracks; }
|
|
@@ -8951,9 +8952,9 @@ canvas[data-cursor="rotate"] {
|
|
|
8951
8952
|
`;class wh{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:s,lng:n,headingDeg:r}=i.pose;s===void 0||n===void 0||t.push({t:i.t,lat:s,lng:n,headingDeg:r})}if(t.length===0){const i=e.event.place?.[0];if(!i)return;t.push({t:0,lat:i.lat,lng:i.lng})}return new wh(t)}static TRAVEL_M=50;get travels(){return this.spanM>wh.TRAVEL_M}get moved(){return this.spanM>wh.STATIONARY_M}get spanM(){const e=this.box,t=(e.south+e.north)/2,i=(e.west+e.east)/2;return Math.max(Math.abs(lt(t,e.east,t,e.west).x),Math.abs(lt(e.north,i,e.south,i).z))}get center(){const e=this.box;return{lat:(e.south+e.north)/2,lng:(e.west+e.east)/2}}boundsAround(e,t){const{lat:i,lng:s}=this.center,n=Math.max(this.spanM*(1+t),e)/2;return{north:wr(0,-n,i,s).lat,south:wr(0,n,i,s).lat,east:wr(n,0,i,s).lng,west:wr(-n,0,i,s).lng}}get box(){const e=this.points.map(i=>i.lat),t=this.points.map(i=>i.lng);return{south:Math.min(...e),north:Math.max(...e),west:Math.min(...t),east:Math.max(...t)}}}class da{constructor(e,t){this.rotationPassed=e,this.scale=t}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(e){if(e.instrument.mounted)return;const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>da.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new da(Math.max(1-(e.instrument.stabilization??0),da.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,s=(d,u)=>Math.sin(2*Math.PI*d*t+u),[n,r,a,o,c,h]=da.HZ;return{eastM:i*da.SWAY_M*(.7*s(n,.3)+.3*s(o,1.9)),northM:i*da.SWAY_M*(.6*s(a,2.2)+.4*s(c,.8)),upM:i*da.BREATH_M*s(r,0),yawDeg:i*this.rotationPassed*da.DRIFT_YAW_DEG*(.6*s(h,1.1)+.4*s(o,2.7)),pitchDeg:i*this.rotationPassed*da.DRIFT_PITCH_DEG*(.5*s(r,1.6)+.5*s(a,.4)),rollDeg:i*this.rotationPassed*da.DRIFT_ROLL_DEG*s(n,2.9)}}}class Ti{constructor(e,t){this.stretches=e,this.rotationPassed=t}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(e){const t=wh.of(e);if(!t||t.points.length<2)return;const i=[];let s=0;for(let n=1;n<t.points.length;n++){const r=t.points[n-1],a=t.points[n],o=(a.t-r.t)/1e3;if(o<=0)continue;const c=lt(a.lat,a.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),p=u/o,f=Ti.stepHzFor(p);i.push({startMs:r.t,endMs:a.t,speedMPerS:p,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:f,stepsBefore:s,rampsIn:!0,rampsOut:!0}),s+=f*o}for(let n=0;n<i.length;n++){const r=i[n-1],a=i[n+1];i[n].rampsIn=r===void 0||r.stepHz===0,i[n].rampsOut=a===void 0||a.stepHz===0}if(i.some(n=>n.stepHz>0))return new Ti(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const s=Ti.of(e)?.offsetAt(t)??Ti.STILL;return i?s:Ti.add(s,da.of(e)?.offsetAt(t))}static stepHzFor(e){return e<Ti.SLOWEST_WALK_M_PER_S||e>Ti.FASTEST_WALK_M_PER_S?0:Ti.REFERENCE_STEP_HZ*Math.pow(e/Ti.REFERENCE_SPEED_M_PER_S,Ti.CADENCE_EXPONENT)}offsetAt(e){return Ti.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/Ti.REFERENCE_SPEED_M_PER_S,s=(a,o,c,h)=>{if(a<0||a>Ti.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/Ti.JOLT_DECAY_S)*Math.sin(2*Math.PI*Ti.JOLT_HZ*d),p=h*o*i*u;return{eastM:p*t.eastUnit,northM:p*t.northUnit,upM:-Math.abs(p)*.3,rollDeg:0,pitchDeg:-h*c*i*u*this.rotationPassed,yawDeg:0}},n=t.rampsOut?s(e-t.endMs,Ti.STOP_LURCH_M,Ti.STOP_PITCH_DEG,1):void 0;if(n)return n;const r=t.rampsIn?s(e-t.startMs,Ti.START_LURCH_M,Ti.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(o=>e>=o.startMs&&e<=o.endMs);if(!t||t.stepHz===0)return Ti.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,s=2*Math.PI*i,n=this.amplitudeAt(t,e),r=Ti.SWAY_M*n*Math.cos(s/2),a=n*this.rotationPassed*t.speedMPerS/Ti.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:Ti.RISE_M_PER_M_PER_S*t.speedMPerS*n*Math.cos(s),rollDeg:Ti.HEAD_ROLL_DEG*a*Math.cos(s/2),pitchDeg:-1.25*a*Math.cos(s),yawDeg:Ti.HEAD_YAW_DEG*a*Math.cos(s/2)}}amplitudeAt(e,t){const i=1e3/e.stepHz,s=Math.min(i,(e.endMs-e.startMs)/2);if(s<=0)return 1;const n=t-e.startMs,r=e.endMs-t,a=Math.min(e.rampsIn?n/s:1,e.rampsOut?r/s:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class x8{constructor(e,t){this.timeline=e,this.onFrame=t}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const i of this.timeline.sourceIds){const s=this.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}this.onFrame(e,t)}}class na{static sessionDeclared=!1;static isLive(e){return e!==void 0&&typeof AudioContext<"u"&&e instanceof AudioContext}static unlock(e){if(na.declarePlayback(),e.state!=="running")try{Promise.resolve(e.resume()).catch(()=>{});const t=e.createBufferSource();t.buffer=e.createBuffer(1,1,22050),t.connect(e.destination),t.start(0)}catch{}}static declarePlayback(){if(!(na.sessionDeclared||typeof navigator>"u")){na.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const d2=.05,u2=.08,p2=2,f2=3,E8=14,S8=.02;class m2{context;constructor(e){this.context=e}voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}na.isLive(this.context)&&na.unlock(this.context)}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const i=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,i):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),na.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const i=this.context;if(!e||!i)return;const s=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,s,d2);for(const{param:n,ratio:r}of e.pitch)n.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),s,d2)}buildSynthesizedVoice(e,t){const i=this.context;if(i)switch(e.kind){case"hum":return this.buildHum(i,t);case"whistle":return this.buildWhistle(i,t);case"rumble":return this.buildRumble(i,t);case"crackle":return this.buildCrackle(i,t);default:return}}buildHum(e,t){const i=e.createOscillator();i.type="sawtooth";const s=e.createOscillator();s.type="sawtooth";const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(n),s.connect(n),n.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:s.frequency,ratio:1.006},{param:n.frequency,ratio:6}]}}buildWhistle(e,t){const i=e.createOscillator();i.type="sine";const s=e.createOscillator();s.type="sine",s.frequency.value=5;const n=e.createGain(),r=e.createGain();return r.gain.value=0,s.connect(n).connect(i.frequency),i.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:n.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=.8;const n=e.createGain();return n.gain.value=0,i.connect(s).connect(n).connect(this.output(e)),i.start(),{key:t,nodes:[s,n],sources:[i],volumeParam:n.gain,gainScale:1.4,pitch:[{param:s.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="bandpass",s.Q.value=1.2;const n=e.createGain();n.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const a=e.createGain();return a.gain.value=0,r.connect(a).connect(n.gain),i.connect(s).connect(n).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[s,n,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:s.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const s=this.context;if(!s)return;let n;try{n=await this.getBuffer(e)}catch(o){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",o);return}if(i!==this.voiceToken||!this.context)return;const r=s.createBufferSource();r.buffer=n,r.loop=!0;const a=s.createGain();a.gain.value=0,r.connect(a).connect(this.output(s)),r.start(),this.voice={key:t,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*p2),e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*p2),e.sampleRate),i=t.getChannelData(0);let s=0,n=0;for(let r=0;r<i.length;r++)s=(s+.02*(Math.random()*2-1))/1.02,i[r]=s,n=Math.max(n,Math.abs(s));if(n>0)for(let r=0;r<i.length;r++)i[r]/=n;return t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*f2),e.sampleRate),i=t.getChannelData(0),s=Math.max(1,Math.floor(S8*e.sampleRate)),n=Math.round(f2*E8);for(let r=0;r<n;r++){const a=Math.floor(Math.random()*i.length),o=.4+Math.random()*.6;for(let c=0;c<s&&a+c<i.length;c++)i[a+c]=Math.max(i[a+c],o*(1-c/s))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const i=t.currentTime;e.volumeParam.cancelScheduledValues(i),e.volumeParam.setTargetAtTime(0,i,u2/3);const s=i+u2;for(const n of e.sources){n.onended=()=>{n.disconnect();for(const r of e.nodes)r.disconnect()};try{n.stop(s)}catch{n.disconnect();for(const r of e.nodes)r.disconnect()}}}}class Ff{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}","out-of-range":"{path}: {found} is outside {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(e,t=Ff.EN){return t[e.kind].replace("{path}",e.path).replace("{expected}",e.expected??"").replace("{found}",e.found??"")}static warn(e,t){if(e.length===0)return;const i=e.map(s=>` ${Ff.text(s)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
8952
8953
|
${i.join(`
|
|
8953
8954
|
`)}`)}}class ua{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,s){if(!ua.isObject(e)){s.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:ua.typeOf(e)});return}for(const[n,r]of Object.entries(e)){const a=i?`${i}.${n}`:n,o=t[n];o?this.field(r,o,a,s):s.push({kind:"unknown-key",path:a})}}field(e,t,i,s){if(ua.isStated(e)){this.field(e.value,t,i,s);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&s.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(n=>`"${n}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,s):ua.isObject(e)||s.push({kind:"wrong-type",path:i,expected:"object",found:ua.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((n,r)=>{const a=ua.isStated(n)?n.value:n;this.object(a,t.fields,`${i}.${r}`,s)}):s.push({kind:"wrong-type",path:i,expected:"array",found:ua.typeOf(e)});return;default:typeof e!==t.type?s.push({kind:"wrong-type",path:i,expected:t.type,found:ua.typeOf(e)}):typeof e=="number"&&(t.minimum!==void 0&&e<t.minimum||t.maximum!==void 0&&e>t.maximum)&&s.push({kind:"out-of-range",path:i,expected:`${t.minimum??"−∞"}–${t.maximum??"∞"}`,found:String(e)})}}static STATED_KEYS=new Set(["value","basis","rationale","how","range","source"]);static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return ua.isObject(e)&&"value"in e&&Object.keys(e).every(t=>ua.STATED_KEYS.has(t))}static typeOf(e){return Array.isArray(e)?"array":e===null?"null":typeof e}}class Xn{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(e,t){const i=Number.isFinite(t)?Math.max(0,t):0,s=Math.max(0,e-i*1e3),n=Math.max(0,e-s);return{fromMs:s,toMs:e,ms:n,seconds:n/1e3}}static instants(e,t,i,s,n){if(!(s>0))return 1;const r=n>0?Xn.travelDegOver(e,t,i,i+s*1e3)/n/Xn.PIXELS_PER_INSTANT:0,a=Xn.flashesOver(e,s)*Xn.INSTANTS_PER_FLASH,o=Math.ceil(Math.max(r,a));return o<2?1:Math.min(Xn.MAX_INSTANTS,o)}static travelDegOver(e,t,i,s){let n=0;for(const r of e){if(!r.track||r.track.length<2)continue;const a=Xn.directionAt(r,t,i),o=Xn.directionAt(r,t,s),c=Math.min(1,Math.max(-1,a.x*o.x+a.y*o.y+a.z*o.z));n=Math.max(n,Math.acos(c)*180/Math.PI)}return n}static flashesOver(e,t){let i=0;for(const s of e)for(const n of s.lights??[])n.pattern.kind==="flash"&&(i=Math.max(i,n.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const s=ia(e,i),n=s.eastM,r=s.altitudeM-t,a=s.northM,o=Math.hypot(n,r,a);return o===0?{x:0,y:1,z:0}:{x:n/o,y:r/o,z:a/o}}static bodyInstants(e,t,i,s,n){if(!(s>i)||!(n>0))return 1;let r=0;for(const o of e){const c=Xn.bodyAt(o,i),h=Xn.bodyAt(o,s);if(!c||!h)continue;const d={x:c.eastM,y:c.upM-t,z:c.northM},u={x:h.eastM,y:h.upM-t,z:h.northM},p=Math.hypot(d.x,d.y,d.z),f=Math.hypot(u.x,u.y,u.z);if(p===0||f===0)continue;const m=Math.min(1,Math.max(-1,(d.x*u.x+d.y*u.y+d.z*u.z)/p/f));let g=Math.acos(m)*180/Math.PI,v=0;for(const b of Object.keys(h.motions))v=Math.max(v,Math.abs(h.motions[b]-(c.motions[b]??h.motions[b])));v>0&&(g+=v*2*(h.halfWidthM/Math.max(f,.001))*180/Math.PI),r=Math.max(r,g)}const a=Math.ceil(r/n/Xn.PIXELS_PER_INSTANT);return a<2?1:Math.min(Xn.MAX_INSTANTS,a)}static bodyAt(e,t){const i=e.track;if(i.length===0||t<i[0].t||t>i[i.length-1].t)return;let s=0,n=i.length-1;for(;n-s>1;){const u=s+n>>1;i[u].t<=t?s=u:n=u}const r=i[s],a=i[n];if(r.eastM===void 0||r.northM===void 0||a.eastM===void 0||a.northM===void 0)return;const o=a.t>r.t?(t-r.t)/(a.t-r.t):0,c=(u,p)=>u+(p-u)*o,h={};for(const u of Object.keys(a.motions??{})){const p=r.motions?.[u],f=a.motions[u];h[u]=p===void 0?f:c(p,f)}const d=i.find(u=>u.sizeM)?.sizeM?.widthM??1;return{eastM:c(r.eastM,a.eastM),northM:c(r.northM,a.northM),upM:c(r.altitudeM??0,a.altitudeM??0),halfWidthM:d/2,motions:h}}}const vI=Math.PI/180,A8=180/Math.PI,T8=256,bI=19,I8=1.25;function yI(l,e){return 156543.03392*Math.cos(l*vI)/2**e}function wI(l,e){return yI(l,e)*T8}function _8(l,e){let t=0;for(;t<bI&&wI(l,t+1)>=e;)t++;return t}function SM(l,e){return wI(l,e)}function MI(l,e){const t=e*I8;let i=0;for(;i<bI&&yI(l,i)>t;)i++;return i}function H0(l){const e=l*vI;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function xI(l,e,t){const i=2**t;return{x:(l+180)/360*i,y:H0(e)*i}}function EI(l,e,t){const i=H0(l.north),s=H0(l.south);return{x:(e-l.west)/(l.east-l.west),y:(H0(t)-i)/(s-i)}}function D8(l,e,t){const{x:i,y:s}=xI(l,e,t);return{x:Math.floor(i),y:Math.floor(s),z:t}}function k8(l){const e=2**l.z,t=l.x/e*360-180,i=(l.x+1)/e*360-180,s=g2(l.y,e);return{south:g2(l.y+1,e),north:s,west:t,east:i}}function g2(l,e){const t=l/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*A8}function SI(l,e,t,i){const s=D8(l,e,t),n=Math.floor(i/2),r=[];for(let c=-n;c<=n;c++)for(let h=-n;h<=n;h++)r.push({x:s.x+h,y:s.y+c,z:t});const a=r.map(k8),o={south:Math.min(...a.map(c=>c.south)),north:Math.max(...a.map(c=>c.north)),west:Math.min(...a.map(c=>c.west)),east:Math.max(...a.map(c=>c.east))};return{tiles:r,bounds:o}}const R8="#2ec4ff";class Jl{constructor(e){this.ctx=e}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(e,t){let i,s=1/0;for(const n of this.targets){const r=Math.hypot(n.x-e,n.y-t);r>n.radius||r>s||(i=n,s=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(e){const{ctx:t}=this;t.save(),this.targets=[],t.clearRect(0,0,this.width,this.height),this.paintGround(e),this.paintNight(e.nightFraction),this.paintPath(e),this.paintTraces(e),e.position?(this.paintCone(e,e.position),this.paintDecor(e),this.paintMarkers(e),this.paintObserver(e,e.position)):(this.paintDecor(e),this.paintMarkers(e)),this.paintNorth(),this.paintFooter(e.bounds,e.attribution),t.restore()}toCanvas(e,t,i){const s=EI(e,i,t);return{x:s.x*this.width,y:s.y*this.height}}paintGround(e){const{ctx:t}=this;t.fillStyle="#1d2321",t.fillRect(0,0,this.width,this.height);const i=e.imagery;if(!i)return;const s=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),n=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,s.x,s.y,n.x-s.x,n.y-s.y)}paintNight(e=0){if(e<=0)return;const{ctx:t}=this;t.save(),t.fillStyle=`rgba(6, 12, 30, ${Math.min(e,1)*.78})`,t.fillRect(0,0,this.width,this.height),t.restore()}paintDecor(e){const{ctx:t}=this;for(const i of e.decor){const s=this.toCanvas(e.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:s.x,y:s.y,radius:7}),t.beginPath(),t.rect(s.x-3.5,s.y-3.5,7,7),t.fillStyle="rgba(120, 220, 255, 0.85)",t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.7)",t.stroke(),i.headingDeg===void 0)continue;const n=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(s.x+Math.cos(n)*10,s.y+Math.sin(n)*10),t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.6)",t.stroke(),t.lineWidth=1.5,t.strokeStyle="rgba(120, 220, 255, 0.9)",t.stroke()}}paintPath(e){if(!e.path.moved)return;const{ctx:t}=this,i=e.path.points.map(s=>this.toCanvas(e.bounds,s.lat,s.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const s of i.slice(1))t.lineTo(s.x,s.y);t.lineJoin="round",t.lineCap="round",t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=5,t.stroke(),t.strokeStyle="rgba(255, 255, 255, 0.9)",t.lineWidth=2,t.stroke()}paintTraces(e){const{ctx:t}=this;for(const i of e.traces??[]){const s=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(s.length===0)continue;const n=i.color??R8;if(i.kind==="point")t.beginPath(),t.moveTo(s[0].x,s[0].y-6),t.lineTo(s[0].x+6,s[0].y),t.lineTo(s[0].x,s[0].y+6),t.lineTo(s[0].x-6,s[0].y),t.closePath(),t.fillStyle=n,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(s[0].x,s[0].y);for(const r of s.slice(1))t.lineTo(r.x,r.y);i.kind==="polygon"&&t.closePath(),t.lineJoin="round",t.setLineDash([]),t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=4.5,t.stroke(),t.setLineDash([9,5]),t.strokeStyle=n,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=s[0];if(i.kind==="line"&&e.position){const a=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=s.reduce((o,c)=>Math.hypot(c.x-a.x,c.y-a.y)>Math.hypot(o.x-a.x,o.y-a.y)?c:o)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:s}=e;if(i===void 0||s===void 0)return;const{ctx:n}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),a=Math.hypot(this.width,this.height),o=(i-90)*Math.PI/180,c=s*Math.PI/180;n.save(),n.beginPath(),n.moveTo(r.x,r.y),n.arc(r.x,r.y,a,o-c,o+c),n.closePath();const h=n.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),n.fillStyle=h,n.fill(),n.restore()}paintMarkers(e){const{ctx:t}=this;t.textAlign="center",t.textBaseline="middle",t.font="bold 10px sans-serif";for(const i of[...e.markers].sort((s,n)=>Number(s.current)-Number(n.current))){const s=this.toCanvas(e.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:s.x,y:s.y,radius:Jl.MARKER_RADIUS_PX}),t.beginPath(),t.arc(s.x,s.y,Jl.MARKER_RADIUS_PX,0,Math.PI*2),t.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",t.fill(),t.lineWidth=2,t.strokeStyle="rgba(255, 255, 255, 0.9)",t.stroke(),t.fillStyle=i.current?"#1d2321":"#fff",t.fillText(i.label,s.x,s.y)}}paintObserver(e,t){const{ctx:i}=this,s=this.toCanvas(e.bounds,t.lat,t.lng);e.observerLabel&&this.targets.push({kind:"observer",label:e.observerLabel,lat:t.lat,lng:t.lng,x:s.x,y:s.y,radius:8});const n=e.markers.some(r=>{if(!r.current)return!1;const a=lt(r.lat,r.lng,t.lat,t.lng);return Math.hypot(a.x,a.z)<=Jl.ON_MARKER_M});i.beginPath(),i.arc(s.x,s.y,n?Jl.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),n||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=n?3:2.5,i.strokeStyle=n?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:e}=this,t=this.width-14,i=16;e.beginPath(),e.moveTo(t,i-9),e.lineTo(t-4.5,i+5),e.lineTo(t,i+2),e.lineTo(t+4.5,i+5),e.closePath(),e.fillStyle="rgba(255, 255, 255, 0.92)",e.strokeStyle="rgba(0, 0, 0, 0.6)",e.lineWidth=1,e.fill(),e.stroke(),e.font="bold 9px sans-serif",e.textAlign="center",e.textBaseline="top",e.strokeText("N",t,i+6),e.fillText("N",t,i+6)}paintFooter(e,t){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const s=t?this.wrap(t,this.width-20):[];let n=this.height-4;i.textAlign="right";for(const p of s.slice().reverse())this.paintOutlinedText(p,this.width-6,n),n-=11;const r=(e.south+e.north)/2,o=Math.abs(lt(r,e.east,r,e.west).x)/this.width,c=Jl.SCALE_STEPS_M.find(p=>p/o<=this.width/3);if(c===void 0)return;const h=c/o,d=8,u=n-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(d,u),i.lineTo(d+h,u),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(c>=1e3?`${c/1e3} km`:`${c} m`,d,u-3)}paintOutlinedText(e,t,i){const{ctx:s}=this;s.lineWidth=3,s.strokeStyle="rgba(0, 0, 0, 0.75)",s.strokeText(e,t,i),s.fillStyle="#fff",s.fillText(e,t,i)}wrap(e,t){const i=[];let s="";for(const n of e.split(" ")){const r=s?`${s} ${n}`:n;s&&this.ctx.measureText(r).width>t?(i.push(s),s=n):s=r}return s&&i.push(s),i}}class bi{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(e,t){return bi.including(e.boundsAround(bi.MIN_SPAN_M,bi.MARGIN),t)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(e,t,i){const s=Math.min(bi.MAX_ZOOM,Math.max(bi.MIN_ZOOM,this.zoom*i)),n=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=n-(e-.5)/s,this.centerY=r-(t-.5)/s,this.zoom=s}panBy(e,t){this.centerX-=e/this.zoom,this.centerY-=t/this.zoom}refit(e,t){if(!this.changed)return;const i=this.boundsWithin(e),s=bi.mercatorY01(t.north),n=bi.mercatorY01(t.south),r=bi.mercatorY01(i.north),a=bi.mercatorY01(i.south);this.zoom=(t.east-t.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-t.west)/(t.east-t.west),this.centerY=((r+a)/2-s)/(n-s)}keepInView(e,t,i){if(!this.changed)return!1;const s=this.boundsWithin(e),n=bi.mercatorY01(s.north),r=bi.mercatorY01(s.south),a=(t.lng-s.west)/(s.east-s.west),o=(bi.mercatorY01(t.lat)-n)/(r-n);return a>=i&&a<=1-i&&o>=i&&o<=1-i?!1:(this.panBy(.5-a,.5-o),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=bi.mercatorY01(e.north),s=bi.mercatorY01(e.south),n=e.east-e.west;return{west:e.west+(this.centerX-t)*n,east:e.west+(this.centerX+t)*n,north:bi.latitudeAt(i+(this.centerY-t)*(s-i)),south:bi.latitudeAt(i+(this.centerY+t)*(s-i))}}static including(e,t,i=3){const s=(e.north+e.south)/2,n=(e.east+e.west)/2,r=lt(s,e.east,s,n).x;let a=r;for(const o of t){const{x:c,z:h}=lt(o.lat,o.lng,s,n),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(a=Math.max(a,d*1.15))}return a<=r?e:{north:wr(0,-a,s,n).lat,south:wr(0,a,s,n).lat,east:wr(a,0,s,n).lng,west:wr(-a,0,s,n).lng}}static expand(e,t){const i=e.east-e.west,s=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-s*t,north:e.north+s*t}}static pointAt(e,t,i){const s=bi.mercatorY01(e.north),n=bi.mercatorY01(e.south);return{lat:bi.latitudeAt(s+i*(n-s)),lng:e.west+t*(e.east-e.west)}}static mercatorY01(e){const t=e*Math.PI/180;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}static latitudeAt(e){return Math.atan(Math.sinh(Math.PI*(1-2*e)))*180/Math.PI}}const la=256,C8=3,O8=129,L8=7,P8=32768;class AI{fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(e,t){const i=(e.south+e.north)/2,s=(e.west+e.east)/2,n=Math.abs(lt(i,e.east,i,e.west).x),r=Math.abs(lt(e.north,s,e.south,s).z),a=Math.max(n,r);let o=_8(i,a),c=C8;if(t.width>=O8){const m=v=>2*Math.ceil((a/SM(i,v)+1)/2)+1;let g=MI(i,a/(t.width-1)/2);for(;g>o&&m(g)>L8;)g--;g>o&&(o=g,c=m(g))}const{tiles:h}=SI(s,i,o,c),d=c*la,u=new Float32Array(d*d),p=h[0];await Promise.all(h.map(m=>this.decodeTileInto(m,p,u,d)));const f=new Float32Array(t.width*t.height);for(let m=0;m<t.height;m++){const g=e.north+(e.south-e.north)*(m/(t.height-1));for(let v=0;v<t.width;v++){const b=e.west+(e.east-e.west)*(v/(t.width-1));f[m*t.width+v]=this.sampleAt(g,b,o,p,u,d)}}return{heights:f,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,s){const n=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)),r=await this.fetchImpl(n);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${n}`);const a=await createImageBitmap(await r.blob()),o=document.createElement("canvas");o.width=la,o.height=la;const c=o.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(a,0,0);const{data:h}=c.getImageData(0,0,la,la),d=(e.x-t.x)*la,u=(e.y-t.y)*la;for(let p=0;p<la;p++)for(let f=0;f<la;f++){const m=(p*la+f)*4,g=h[m]*256+h[m+1]+h[m+2]/256-P8,v=d+f,b=u+p;i[b*s+v]=g}}sampleAt(e,t,i,s,n,r){const{x:a,y:o}=xI(t,e,i),c=(a-s.x)*la,h=(o-s.y)*la,d=Math.max(0,Math.min(r-1,Math.floor(c))),u=Math.max(0,Math.min(r-1,Math.floor(h))),p=Math.min(r-1,d+1),f=Math.min(r-1,u+1),m=c-d,g=h-u,v=n[u*r+d],b=n[u*r+p],w=n[f*r+d],y=n[f*r+p],M=v+(b-v)*m,x=w+(y-w)*m;return M+(x-M)*g}}class bv{constructor(e,t,i,s){this.width=e,this.height=t,this.samples=i,this.values=s}at(e,t,i=0){return this.values[(t*this.width+e)*this.samples+i]}static parse(e){const t=new DataView(e);if(e.byteLength<8||t.getUint16(0)!==18761||t.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=t.getUint32(4,!0),s=t.getUint16(i,!0),n=new Map;for(let v=0;v<s;v++){const b=i+2+v*12;n.set(t.getUint16(b,!0),{type:t.getUint16(b+2,!0),count:t.getUint32(b+4,!0),value:t.getUint32(b+8,!0)})}const r=(v,b)=>{const w=n.get(v);if(w===void 0){if(b===void 0)throw new Error(`TIFF without tag ${v}`);return b}return w.type===3?w.value&65535:w.value},a=v=>{const b=n.get(v);if(b===void 0)throw new Error(`TIFF without tag ${v}`);const w=b.type===3?2:4,y=[];if(b.count*w<=4){const M=new DataView(new ArrayBuffer(4));M.setUint32(0,b.value,!0);for(let x=0;x<b.count;x++)y.push(w===2?M.getUint16(x*2,!0):M.getUint32(0,!0))}else for(let M=0;M<b.count;M++)y.push(w===2?t.getUint16(b.value+M*2,!0):t.getUint32(b.value+M*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(n.has(322))throw new Error("Tiled TIFF");const o=r(256),c=r(257),h=r(277,1),d=a(258)[0],u=r(339,1)===3;if(!(u&&d===32||!u&&d===8))throw new Error(`Unsupported TIFF samples: ${d} bits`);const p=a(273),f=a(279),m=new Uint8Array(o*c*h*(d/8));let g=0;for(let v=0;v<p.length&&g<m.length;v++){const b=Math.min(f[v],m.length-g);m.set(new Uint8Array(e,p[v],b),g),g+=b}if(g<m.length)throw new Error("Truncated TIFF");return new bv(o,c,h,u?new Float32Array(m.buffer):m)}}class N8{constructor(e,t,i,s,n){this.heights=e,this.plants=t,this.buildings=i,this.size=s,this.metresPerPixel=n}structureAt(e,t){const i=Math.floor(e/this.metresPerPixel+this.size/2),s=Math.floor(this.size/2-t/this.metresPerPixel);if(i<0||s<0||i>=this.size||s>=this.size)return;const n=s*this.size+i;if(!(this.plants[n]||this.buildings[n]))return this.heights[n]}tallestStructureNear(e,t,i){let s;const n=Math.ceil(i/this.metresPerPixel);for(let r=-n;r<=n;r++)for(let a=-n;a<=n;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const o=this.structureAt(e+a*this.metresPerPixel,t+r*this.metresPerPixel);o!==void 0&&(s===void 0||o>s)&&(s=o)}return s}}class Re{static METRES_PER_DEGREE=111320;static MIN_BRIDGE_M=4;static DEFAULT_DECK_M=6;static FOOTBRIDGE_DECK_M=2.5;static DECK_MARGIN_M=2.4;static JOIN_M=1;static JOIN_DEG=25;static RAIL_MATCH_M=6;static ROAD_MATCH_M=12;static DECK_SEEN_M=1.5;static DECK_STEP_M=.5;static DECK_GAP_M=2;static DECK_REACH_M=20;static DECK_MEETS_M=.3;static DECK_BEARING_M=4;static DEFAULT_DECK_HEIGHT_M=4;static MIN_POLE_M=6;static MAX_POLE_M=70;static MAX_SPAN_M=800;static MAX_LINES=16;static BY_VOLTAGE=[{upToKv:25,poleM:11,dropM:1.2,spreadM:.8},{upToKv:70,poleM:20,dropM:3,spreadM:3},{upToKv:100,poleM:22,dropM:3.5,spreadM:3.5},{upToKv:170,poleM:27,dropM:4.5,spreadM:4.5},{upToKv:250,poleM:32,dropM:5.5,spreadM:5.5},{upToKv:1e3,poleM:42,dropM:7,spreadM:7.5}];static toMetres(e,t){const[i,s]=e;return{east:(i-t.lng)*Re.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180),north:(s-t.lat)*Re.METRES_PER_DEGREE}}static path(e,t){return e.geometry.type!=="LineString"?[]:e.geometry.coordinates.map(i=>Re.toMetres(i,t))}static bearing(e,t){return(Math.atan2(t.east-e.east,t.north-e.north)*180/Math.PI+360)%360}static distanceToSegment(e,t,i){const s=i.east-t.east,n=i.north-t.north,r=s*s+n*n,a=r===0?0:Math.max(0,Math.min(1,((e.east-t.east)*s+(e.north-t.north)*n)/r));return Math.hypot(e.east-(t.east+a*s),e.north-(t.north+a*n))}static bridges(e,t,i,s){const n=e.elevatedRoads.map(o=>({path:Re.path(o,t),properties:o.properties})),r=(e.elevatedRailways??[]).map(o=>Re.path(o,t)),a=[];for(const o of Re.joined(e.bridges.map(c=>Re.path(c,t)))){const c=o[0],h=o[o.length-1],d=Math.hypot(h.east-c.east,h.north-c.north);if(d<Re.MIN_BRIDGE_M)continue;const u={east:(c.east+h.east)/2,north:(c.north+h.north)/2};if(Math.hypot(u.east,u.north)>i+d/2||Re.carriesRailway(c,h,r))continue;const[p,f]=Re.deckReach(c,h,s);a.push({eastM:Re.tenth((p.east+f.east)/2),northM:Re.tenth((p.north+f.north)/2),lengthM:Re.tenth(Math.hypot(f.east-p.east,f.north-p.north)),widthM:Re.roadOf(u,n).width,heightM:Re.tenth(Re.deckHeight(c,h,s)),headingDeg:Re.tenth(Re.bearing(c,h)%180),...Re.roadOf(u,n).name?{name:Re.roadOf(u,n).name}:{}})}return a.sort((o,c)=>Math.hypot(o.eastM,o.northM)-Math.hypot(c.eastM,c.northM)),a}static carriesRailway(e,t,i){const s={east:(e.east+t.east)/2,north:(e.north+t.north)/2},n=Re.bearing(e,t)%180;for(const r of i)for(let a=0;a+1<r.length;a++){if(Re.distanceToSegment(s,r[a],r[a+1])>Re.RAIL_MATCH_M)continue;const o=Math.abs(Re.bearing(r[a],r[a+1])%180-n);if(Math.min(o,180-o)<=Re.JOIN_DEG)return!0}return!1}static joined(e){const t=e.filter(i=>i.length>=2);for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++){const n=Re.join(t[i],t[s]);n!==void 0&&(t[i]=n,t.splice(s,1),s=i)}return t}static join(e,t){for(const i of[e,[...e].reverse()])for(const s of[t,[...t].reverse()]){const n=i[i.length-1],r=s[0];if(Math.hypot(n.east-r.east,n.north-r.north)>Re.JOIN_M)continue;const a=Math.abs(Re.bearing(i[0],n)-Re.bearing(r,s[s.length-1]));if(Math.min(a,360-a)<=Re.JOIN_DEG)return[...i,...s.slice(1)]}}static roadOf(e,t){let i;for(const a of t)for(let o=0;o+1<a.path.length;o++){const c=Re.distanceToSegment(e,a.path[o],a.path[o+1]);(i===void 0||c<i.distance)&&(i={distance:c,properties:a.properties})}if(i===void 0||i.distance>Re.ROAD_MATCH_M)return{width:Re.DEFAULT_DECK_M};const s=[i.properties.nom_voie_ban_gauche,i.properties.nom_voie_ban_droite,i.properties.cpx_toponyme_route_nommee].find(a=>typeof a=="string"&&a.length>0),n=Number(i.properties.largeur_de_chaussee),r=Number.isFinite(n)&&n>0?Re.tenth(n+Re.DECK_MARGIN_M):i.properties.nature==="Sentier"?Re.FOOTBRIDGE_DECK_M:Re.DEFAULT_DECK_M;return s?{width:r,name:s}:{width:r}}static deckReach(e,t,i){const s=Math.hypot(t.east-e.east,t.north-e.north);if(i===void 0||s===0)return[e,t];const n={east:(e.east+t.east)/2,north:(e.north+t.north)/2},r={east:(t.east-e.east)/s,north:(t.north-e.north)/s},a=u=>(i.structureAt(n.east+r.east*u,n.north+r.north*u)??0)>=Re.DECK_SEEN_M,o=u=>i.structureAt(n.east+r.east*u,n.north+r.north*u)??0,c=u=>{let p;for(let m=0;m<=s/2+Re.DECK_REACH_M;m+=Re.DECK_STEP_M)if(a(u*m))p=m;else if(p!==void 0&&m-p>Re.DECK_GAP_M)break;if(p===void 0)return s/2;let f=p;for(;f-p<Re.DECK_REACH_M&&o(u*(f+Re.DECK_STEP_M))>=Re.DECK_MEETS_M;)f+=Re.DECK_STEP_M;return Math.max(s/2,f+Re.DECK_BEARING_M)},h=c(-1),d=c(1);return[{east:n.east-r.east*h,north:n.north-r.north*h},{east:n.east+r.east*d,north:n.north+r.north*d}]}static deckHeight(e,t,i){if(i===void 0)return Re.DEFAULT_DECK_HEIGHT_M;const s=[],n=20;for(let r=4;r<=n-4;r++){const a=i.structureAt(e.east+(t.east-e.east)*r/n,e.north+(t.north-e.north)*r/n);a!==void 0&&a>=1.5&&s.push(a)}return s.length===0?Re.DEFAULT_DECK_HEIGHT_M:(s.sort((r,a)=>r-a),s[Math.floor(s.length/2)])}static lines(e,t,i,s){const n=[];for(const r of e.lines){const a=String(r.properties.voltage??""),o=Re.kilovolts(a);if(o===void 0)continue;const c=Re.BY_VOLTAGE.find(d=>o<=d.upToKv)??Re.BY_VOLTAGE[Re.BY_VOLTAGE.length-1],h=Re.path(r,t);for(let d=0;d+1<h.length;d++){const u=h[d],p=h[d+1],f=Math.hypot(p.east-u.east,p.north-u.north);if(f<5||f>Re.MAX_SPAN_M||Re.distanceToSegment({east:0,north:0},u,p)>i)continue;const m=Re.poleHeight(u,p,s)??c.poleM;n.push({eastM:Re.tenth((u.east+p.east)/2),northM:Re.tenth((u.north+p.north)/2),lengthM:Re.tenth(f),headingDeg:Re.tenth(Re.bearing(u,p)),heightM:Re.tenth(Math.max(4,m-c.dropM)),poleHeightM:Re.tenth(m),acrossM:[-c.spreadM,0,c.spreadM],voltage:a})}}return n.sort((r,a)=>Math.hypot(r.eastM,r.northM)-Math.hypot(a.eastM,a.northM)),n.slice(0,Re.MAX_LINES)}static kilovolts(e){const t=/([\d.,]+)\s*kV/i.exec(e);if(t===null)return;const i=Number(t[1].replace(",","."));return Number.isFinite(i)&&i>0?i:void 0}static poleHeight(e,t,i){if(i===void 0)return;const s=[e,t].map(n=>i.tallestStructureNear(n.east,n.north,3)).filter(n=>n!==void 0&&n>=Re.MIN_POLE_M&&n<=Re.MAX_POLE_M);return s.length===0?void 0:s.reduce((n,r)=>n+r,0)/s.length}static tenth(e){return Math.round(e*10)/10}}class Xt{static covers(e,t){return e>=41.2&&e<=51.3&&t>=-5.4&&t<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Xt.WMS,this.wfs=e.wfsEndpoint??Xt.WFS}static radius(e){return Math.min(e,Xt.MAX_RADIUS_M)}static lidarRadius(e){return Math.min(e,Xt.MAX_LIDAR_RADIUS_M)}async lidar(e,t){const i=Xt.lidarRadius(t),s=Math.ceil(2*i/Xt.METRES_PER_PIXEL),[n,r]=await Promise.all([this.raster(e,i,s,Xt.HEIGHT_LAYER),this.raster(e,i,s,Xt.CLASS_LAYER)]);if(n.samples!==1||r.samples<3)throw new Ra("unreachable","The survey answered in a layout this does not read");const a=n.values;if(a.every(d=>d===Xt.NO_DATA))throw new Ra("no-coverage","No LiDAR HD survey here yet");const o=new Uint8Array(s*s),c=new Uint8Array(s*s);for(let d=0;d<s*s;d++){const u=r.values[d*r.samples],p=r.values[d*r.samples+1],f=r.values[d*r.samples+2];o[d]=p>u&&p>f?1:0,c[d]=u>120&&p<90&&f<90?1:0}const h=2*i/s;return{size:s,metresPerPixel:h,heights:a,vegetation:o,building:c,structures:new N8(a,o,c,s,h)}}async laserDate(e){return Xt.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",e))}async photoDate(e){return Xt.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",e))}static latest(e){return e.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(e,t,i,s){const r=[s.lng-1e-4,s.lat-1e-4,s.lng+1e-4,s.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(e,`BBOX(${t},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(e,t){const i=Xt.radius(t),s=Math.min(Xt.MAX_PHOTO_PIXELS,Math.ceil(2*i/Xt.METRES_PER_PIXEL)),n=await this.raster(e,i,s,Xt.PHOTO_LAYER);if(n.samples<3)throw new Ra("unreachable","The photograph came in a layout this does not read");return{size:s,metresPerPixel:2*i/s,samples:n.samples,values:n.values}}async vectors(e,t,i){const s=Xt.radius(t),n=s/Xt.METRES_PER_DEGREE,r=s/(Xt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),o=`BBOX(geometrie,${[e.lng-r,e.lat-n,e.lng+r,e.lat+n].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[c,h,d,u,p,f]=await Promise.all([this.features("construction_lineaire",`${o} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${o} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${o} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",o,"voltage,geometrie"),i?this.features("batiment",o,Xt.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",o,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(f,p,[e.lng-r,e.lat-n,e.lng+r,e.lat+n]):[],g=[...p,...m];return{bridges:c,elevatedRoads:h,elevatedRailways:d,lines:u,buildings:g,zones:f,mapDate:Xt.latest(g.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(e,t,i){const[s,n,r,a]=i,o=Xt.MAX_WHOLE_M/Xt.METRES_PER_DEGREE;let c;for(const d of e){if(d.properties.categorie!=="Religieux")continue;const[u,p,f,m]=Xt.extent(d);if(u>=s&&p>=n&&f<=r&&m<=a)continue;const g=[Math.max(u,s-o),Math.max(p,n-o),Math.min(f,r+o),Math.min(m,a+o)];c=c?[Math.min(c[0],g[0]),Math.min(c[1],g[1]),Math.max(c[2],g[2]),Math.max(c[3],g[3])]:g}if(!c)return[];const h=new Set(t.map(d=>d.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${c.map(u=>u.toFixed(6)).join(",")},'EPSG:4326')`,Xt.BUILDING_PROPERTIES,1e3)).filter(u=>!h.has(u.properties.cleabs))}catch{return[]}}static extent(e){let t=1/0,i=1/0,s=-1/0,n=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(t=Math.min(t,a[0]),s=Math.max(s,a[0]),i=Math.min(i,a[1]),n=Math.max(n,a[1])):Array.isArray(a)&&a.forEach(r)};return r(e.geometry.coordinates),[t,i,s,n]}async elevatedRoadLines(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(n=>n.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${t} AND position_par_rapport_au_sol>'0'`,"geometrie",300),s=[];for(const n of i){const{type:r,coordinates:a}=n.geometry,o=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const c of o)s.push(c.map(h=>({lat:h[1],lng:h[0]})))}return s}async waterSurfaces(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${t} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${t} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${t} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(e,t,i,s){const n=t/Xt.METRES_PER_DEGREE,r=t/(Xt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:s,STYLES:"",CRS:"EPSG:4326",BBOX:[e.lat-n,e.lng-r,e.lat+n,e.lng+r].map(c=>c.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let o;try{o=await this.fetchImpl(`${this.wms}?${a}`)}catch(c){throw new Ra("unreachable",c instanceof Error?c.message:String(c))}if(!o.ok)throw new Ra("unreachable",`The survey answered ${o.status}`);try{return bv.parse(await o.arrayBuffer())}catch(c){throw new Ra("unreachable",c instanceof Error?c.message:String(c))}}async features(e,t,i,s=200){const n=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:e.includes(":")?e:`BDTOPO_V3:${e}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(s),CQL_FILTER:t,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${n}`)}catch(o){throw new Ra("unreachable",o instanceof Error?o.message:String(o))}if(!r.ok)throw new Ra("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class Xc{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(e,t){if(e.length<2||t.length<2)return!1;const i=t[0],s=t.map(a=>lt(a.lat,a.lng,i.lat,i.lng)),n=e.map(a=>lt(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<n.length-1;a++){const o=n[a],c=n[a+1],h=Math.hypot(c.x-o.x,c.z-o.z);if(h<1e-6)continue;const d=Math.max(1,Math.ceil(h/Xc.SAMPLE_M)),u=Math.atan2(c.x-o.x,-(c.z-o.z));for(let p=0;p<=d;p++){const f=p/d,m=Xc.nearest(s,o.x+(c.x-o.x)*f,o.z+(c.z-o.z)*f);m.distanceM>Xc.NEAR_M||Xc.angleBetween(u,m.heading)<=Xc.ALIGNED_DEG&&(r+=h/d)}}return r>=Xc.LONG_ENOUGH_M}static nearest(e,t,i){let s={distanceM:1/0,heading:0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,c=a.z-r.z,h=o*o+c*c,d=h<1e-9?0:Math.max(0,Math.min(1,((t-r.x)*o+(i-r.z)*c)/h)),u=Math.hypot(t-(r.x+o*d),i-(r.z+c*d));u<s.distanceM&&(s={distanceM:u,heading:Math.atan2(o,-c)})}return s}static angleBetween(e,t){const i=Math.abs((e-t)*180/Math.PI%180);return Math.min(i,180-i)}}class Bt{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Bt.WMS,this.timeoutMs=e.timeoutMs??Bt.DEFAULT_TIMEOUT_MS,this.maxWindowM=e.maxWindowM??Bt.MAX_WINDOW_M,this.geoplatform=new Xt({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:e.wfsEndpoint})}async getElevationGrid(e,t,i){const s={lat:(e.south+e.north)/2,lng:(e.west+e.east)/2};if(!Xt.covers(s.lat,s.lng))throw new Error("The IGN's relief covers France only");const n=Math.abs(lt(s.lat,e.east,s.lat,e.west).x),r=Math.abs(lt(e.north,s.lng,e.south,s.lng).z);t=this.finer(t,n,r);const a={x:n/Math.max(1,t.width-1),y:r/Math.max(1,t.height-1)},o={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},c={south:e.south-o.y/Bt.METRES_PER_DEGREE,north:e.north+o.y/Bt.METRES_PER_DEGREE,west:e.west-o.x/(Bt.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180)),east:e.east+o.x/(Bt.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180))},h=m=>Math.min(Bt.MAX_PIXELS,Math.max(Bt.MIN_PIXELS,Math.ceil(m/Bt.METRES_PER_PIXEL))),d={width:h(n+2*o.x),height:h(r+2*o.y)},u={x:(n+2*o.x)/d.width,y:(r+2*o.y)/d.height};let p=new Error("No layer of the IGN's relief answered");const f=Math.max(u.x,u.y)>Bt.COARSE_METRES_PER_PIXEL;for(const m of f?[...Bt.LAYERS].reverse():Bt.LAYERS)try{const g=await this.heights(c,d,m);m===Bt.LAYERS[0]&&await this.layBridgeDecks(g,c,d,i?.route);const v=this.sample(g,t,e,c,u,a);if(v)return{heights:v,width:t.width,height:t.height,bounds:e};p=new Error(`${m} does not cover this place`)}catch(g){p=g}throw p}finer(e,t,i){if(e.width<Bt.MESH_FROM_VERTICES||e.height<Bt.MESH_FROM_VERTICES)return e;const s=(n,r)=>{const a=Math.ceil(n/Bt.FINE_SPACING_M),o=Math.max(r-1,Math.min(Bt.MAX_SEGMENTS,a));return o%2===0?o:o+1};return{width:s(t,e.width)+1,height:s(i,e.height)+1}}async raster(e,t,i){const s=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[e.south,e.west,e.north,e.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(t.width),HEIGHT:String(t.height),FORMAT:"image/geotiff"}),n=await this.fetchImpl(`${this.wms}?${s}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok)throw new Error(`The IGN's relief answered ${n.status}`);return bv.parse(await n.arrayBuffer())}async heights(e,t,i){const s=await this.raster(e,t,i);if(s.samples!==1||!(s.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return s}async layBridgeDecks(e,t,i,s){if(!(!s||s.length<2)&&!(!(e.values instanceof Float32Array)||!e.values.some(n=>n>Bt.NO_DATA_BELOW)))try{const n=(await this.geoplatform.elevatedRoadLines({west:t.west,south:t.south,east:t.east,north:t.north})).filter(a=>Xc.follows(s,a));if(n.length===0)return;const r=Float32Array.from(e.values);await this.layClassifiedDecks(e,t,i,n),this.layRouteDecks(e,r,t,n)}catch{}}async layClassifiedDecks(e,t,i,s){try{const n=await this.raster(t,i,Bt.CLASS_LAYER);if(n.samples<3||n.width!==e.width||n.height!==e.height)return;const r=(g,[v,b,w])=>n.values[g*n.samples]===v&&n.values[g*n.samples+1]===b&&n.values[g*n.samples+2]===w,a=e.width,o=e.height,c=new Uint8Array(a*o);let h=!1;for(let g=0;g<c.length;g++)r(g,Bt.DECK)&&(c[g]=1,h=!0);if(!h)return;const d=Bt.DECK_END_PIXELS,u=[];for(let g=0;g<c.length;g++){if(c[g]!==1)continue;const v=g%a,b=(g-v)/a;for(let w=-d;w<=d;w++)for(let y=-d;y<=d;y++){const M=v+y,x=b+w;if(M<0||x<0||M>=a||x>=o)continue;const S=x*a+M;c[S]===0&&r(S,Bt.NO_CLASS)&&u.push(S)}}for(const g of u)c[g]=1;const p=this.paint(s,t,a,o),f=this.touching(c,p,a,o);if(f.every(g=>g===0))return;const m=await this.heights(t,i,Bt.SURFACE_LAYER);if(m.width!==a||m.height!==o)return;for(let g=0;g<f.length;g++){if(f[g]===0)continue;const v=m.values[g];Number.isFinite(v)&&v>Bt.NO_DATA_BELOW&&v>e.values[g]&&(e.values[g]=v)}}catch{}}layRouteDecks(e,t,i,s){const{width:n,height:r}=e,a=(i.north+i.south)/2,o=(i.east-i.west)*Bt.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),c=(i.north-i.south)*Bt.METRES_PER_DEGREE,h=o/n,d=c/r,u=v=>({x:(v.lng-i.west)/(i.east-i.west)*o,y:(i.north-v.lat)/(i.north-i.south)*c}),p=(v,b)=>{const w=Math.floor(v/h),y=Math.floor(b/d);if(w<0||y<0||w>=n||y>=r)return;const M=t[y*n+w];return Number.isFinite(M)&&M>Bt.NO_DATA_BELOW?M:void 0},f=Bt.DECK_HALF_WIDTH_M,m=Bt.DECK_APPROACH_M,g=(v,b)=>{const w=Math.hypot(v.x-b.x,v.y-b.y)||1,y={x:(v.x-b.x)/w,y:(v.y-b.y)/w},M=[0,m/2,m].map(x=>p(v.x+y.x*x,v.y+y.y*x)).filter(x=>x!==void 0);return M.length>0?Math.max(...M):void 0};for(const v of Bt.chains(s.map(b=>b.map(u)))){const b=[0];for(let D=1;D<v.length;D++)b.push(b[D-1]+Math.hypot(v[D].x-v[D-1].x,v[D].y-v[D-1].y));const w=b[b.length-1];if(w<1||w>Bt.DECK_STRAIGHT_MAX_M)continue;const y=g(v[0],v[1]),M=g(v[v.length-1],v[v.length-2]);if(y===void 0||M===void 0)continue;const x=f+m,S=Math.max(0,Math.floor((Math.min(...v.map(D=>D.x))-x)/h)),E=Math.min(n-1,Math.ceil((Math.max(...v.map(D=>D.x))+x)/h)),A=Math.max(0,Math.floor((Math.min(...v.map(D=>D.y))-x)/d)),T=Math.min(r-1,Math.ceil((Math.max(...v.map(D=>D.y))+x)/d));for(let D=A;D<=T;D++)for(let k=S;k<=E;k++){const O=Bt.nearestAlong(v,b,{x:(k+.5)*h,y:(D+.5)*d});if(O.distance>f||O.s<-m||O.s>w+m)continue;const N=y+(M-y)*Math.min(1,Math.max(0,O.s/w)),C=D*n+k;t[C]>=N||(e.values[C]=N)}}}static chains(e){const t=e.filter(n=>n.length>=2).map(n=>[...n]),i=[],s=(n,r)=>Math.hypot(n.x-r.x,n.y-r.y)<=1;for(;t.length>0;){let n=t.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<t.length;a++){const o=t[a],c=n[0],h=n[n.length-1];if(s(h,o[0]))n=[...n,...o.slice(1)];else if(s(h,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else if(s(c,o[o.length-1]))n=[...o.slice(0,-1),...n];else if(s(c,o[0]))n=[...[...o].reverse().slice(0,-1),...n];else continue;t.splice(a,1),r=!0;break}}i.push(n)}return i}static nearestAlong(e,t,i){let s={s:0,distance:1/0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,c=a.y-r.y,h=o*o+c*c;if(h<1e-9)continue;let d=((i.x-r.x)*o+(i.y-r.y)*c)/h;n>0&&(d=Math.max(0,d)),n<e.length-2&&(d=Math.min(1,d));const u=Math.hypot(i.x-(r.x+o*d),i.y-(r.y+c*d));u<s.distance&&(s={s:t[n]+d*Math.sqrt(h),distance:u})}return s}paint(e,t,i,s){const n=new Uint8Array(i*s),r=o=>(o-t.west)/(t.east-t.west)*i,a=o=>(t.north-o)/(t.north-t.south)*s;for(const o of e)for(let c=0;c<o.length-1;c++){const h=r(o[c].lng),d=a(o[c].lat),u=r(o[c+1].lng),p=a(o[c+1].lat),f=Math.max(1,Math.ceil(Math.hypot(u-h,p-d)*2));for(let m=0;m<=f;m++){const g=Math.floor(h+(u-h)*m/f),v=Math.floor(d+(p-d)*m/f);for(let b=-1;b<=1;b++)for(let w=-1;w<=1;w++){const y=g+w,M=v+b;y>=0&&M>=0&&y<i&&M<s&&(n[M*i+y]=1)}}}return n}touching(e,t,i,s){const n=new Uint8Array(e.length),r=new Uint8Array(e.length);for(let a=0;a<e.length;a++){if(e[a]===0||r[a]===1)continue;const o=[],c=[a];r[a]=1;let h=!1;for(;c.length>0;){const d=c.pop();o.push(d),t[d]===1&&(h=!0);const u=d%i,p=(d-u)/i;for(let f=-1;f<=1;f++)for(let m=-1;m<=1;m++){const g=u+m,v=p+f;if(g<0||v<0||g>=i||v>=s)continue;const b=v*i+g;e[b]===1&&r[b]===0&&(r[b]=1,c.push(b))}}if(h)for(const d of o)n[d]=1}return n}sample(e,t,i,s,n,r){const{width:a,height:o}=t,c=new Float32Array(a*o),h=new Uint8Array(a*o),d=Math.min(r.x,this.maxWindowM)/n.x,u=Math.min(r.y,this.maxWindowM)/n.y;let p=0;for(let f=0;f<o;f++){const m=i.north+(i.south-i.north)*(o===1?.5:f/(o-1)),g=(s.north-m)/(s.north-s.south)*e.height-.5;for(let v=0;v<a;v++){const w=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-s.west)/(s.east-s.west)*e.width-.5,y=d>1||u>1?this.tent(e,w,g,Math.max(1,d),Math.max(1,u)):this.bilinear(e,w,g),M=f*a+v;y===void 0?p++:(c[M]=y,h[M]=1)}}if(!(p===a*o||p/(a*o)>Bt.MAX_HOLE_SHARE))return this.fill(c,h,a,o),c}tent(e,t,i,s,n){let r=0,a=0,o=0;const c=Math.max(0,Math.ceil(i-n)),h=Math.min(e.height-1,Math.floor(i+n)),d=Math.max(0,Math.ceil(t-s)),u=Math.min(e.width-1,Math.floor(t+s));for(let p=c;p<=h;p++){const f=1-Math.abs(p-i)/n;if(!(f<=0))for(let m=d;m<=u;m++){const g=f*(1-Math.abs(m-t)/s);if(g<=0)continue;o+=g;const v=e.at(m,p);!Number.isFinite(v)||v<Bt.NO_DATA_BELOW||(r+=g*v,a+=g)}}return o>0&&a>=o*.5?r/a:void 0}bilinear(e,t,i){const s=Math.max(0,Math.min(e.width-1,Math.floor(t))),n=Math.max(0,Math.min(e.height-1,Math.floor(i))),r=Math.min(e.width-1,s+1),a=Math.min(e.height-1,n+1),o=Math.max(0,Math.min(1,t-s)),c=Math.max(0,Math.min(1,i-n)),h=e.at(s,n),d=e.at(r,n),u=e.at(s,a),p=e.at(r,a);for(const g of[h,d,u,p])if(!Number.isFinite(g)||g<Bt.NO_DATA_BELOW)return;const f=h+(d-h)*o,m=u+(p-u)*o;return f+(m-f)*c}fill(e,t,i,s){let n=t.reduce((r,a)=>r+(a?0:1),0);for(;n>0;){const r=[];for(let a=0;a<s;a++)for(let o=0;o<i;o++){const c=a*i+o;if(t[c])continue;let h=0,d=0;for(let u=-1;u<=1;u++)for(let p=-1;p<=1;p++){const f=a+u,m=o+p;f<0||m<0||f>=s||m>=i||!t[f*i+m]||(h+=e[f*i+m],d++)}d>0&&r.push([c,h/d])}if(r.length===0)return;for(const[a,o]of r)e[a]=o,t[a]=1;n-=r.length}}}class F8{providers;constructor(...e){this.providers=e}async getElevationGrid(e,t,i){let s=new Error("No source of relief to ask");for(const n of this.providers)try{return await n.getElevationGrid(e,t,i)}catch(r){s=r}throw s}}const G0=256,U8=5;async function TI(l,e,t,i){const s=(l.south+l.north)/2,n=(l.west+l.east)/2,r=Math.abs(lt(s,l.east,s,l.west).x),a=Math.abs(lt(l.north,n,l.south,n).z),o=Math.max(r,a),{zoom:c,gridSize:h}=B8(s,o,Math.max(e.width,e.height)),{tiles:d,bounds:u}=SI(n,s,c,h),p=h*G0,f=document.createElement("canvas");f.width=p,f.height=p;const m=f.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const g=d[0];await Promise.all(d.map(async y=>{const M=t(y),x=await i(M);if(!x.ok)throw new Error(`Imagery tile fetch failed (${x.status}): ${M}`);const S=await createImageBitmap(await x.blob());m.drawImage(S,(y.x-g.x)*G0,(y.y-g.y)*G0)}));const v=Math.min(Math.max(e.width,e.height),p);if(v===p)return{source:f,width:p,height:p,bounds:u};const b=document.createElement("canvas");b.width=v,b.height=v;const w=b.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(f,0,0,p,p,0,0,v,v),{source:b,width:v,height:v,bounds:u}}function B8(l,e,t){let i=MI(l,e/Math.max(1,t)),s=v2(l,i,e);for(;s>U8&&i>0;)i--,s=v2(l,i,e);return{zoom:i,gridSize:s,mPerPixel:SM(l,i)/G0}}function v2(l,e,t){const i=Math.ceil(t/2/SM(l,e));return Math.max(3,2*i+1)}class II{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(e,t){return TI(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Pr{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(e,t=Pr.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(e);if(!i)return[...t];const[s,n,r,a]=i.slice(1).map(Number),o=(s+r)/2,c=(n+a)/2,h=Pr.FRANCE;return o>=h.south&&o<=h.north&&c>=h.west&&c<=h.east?[Pr.FRANCE_ENDPOINT,...t.filter(u=>u!==Pr.FRANCE_ENDPOINT)]:[...t]}fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(e){return this.queued(()=>this.ask(e))}queued(e){const t=Pr.queue.then(e,e);return Pr.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints??Pr.endpointsFor(e))for(let s=0;s<2;s++){try{const n=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(Pr.HANG_MS)});if(n.ok)return await n.json();if(t=new Error(`${new URL(i).host} refused (${n.status})`),n.status!==429&&n.status!==504)break}catch(n){t=new Error(`${new URL(i).host} unreachable (${String(n)})`);break}await new Promise(n=>setTimeout(n,Pr.RETRY_MS))}throw t??new Error("No Overpass instance answered")}}class Yc{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(e={}){this.client=new Pr(e)}async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Yc.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(e){const t=[];for(const i of e.elements??[]){const s=i.geometry,n=i.tags;!n||!s||s.length<2||t.push({id:`osm-${i.id??t.length}`,name:n.name,surface:Yc.surfaceOf(n),widthM:Yc.widthOf(n),...Yc.paintOf(n),points:s.map(r=>({lat:r.lat,lng:r.lon}))})}return t}static paintOf(e){const t=e.highway??"",i=e.junction==="roundabout"||e.junction==="circular",s=e.oneway,n=s==="yes"||s==="1"||s==="true"||s===void 0&&(t==="motorway"||i),r=s==="-1"||s==="reverse",a=Number.parseInt(e.lanes??"",10),o=Number.parseInt(e.maxspeed??"",10),c=i?"roundabout":t==="motorway"?"motorway":t.endsWith("_link")?"slip":(t==="trunk"||t==="primary")&&(n||r)?"dual":t?"road":void 0;return{...c?{kind:c}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...s!==void 0||t==="motorway"||i?{direction:r?"backward":n?"forward":"both"}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{}}}static widthOf(e){const t=Number.parseFloat(e.width??e.est_width??"");if(Number.isFinite(t)&&t>0)return t;const i=Number.parseInt(e.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:Yc.WIDTH_M[e.highway]??Yc.DEFAULT_WIDTH_M}static surfaceOf(e){const t=e.surface;return t==="dirt"||t==="earth"||t==="mud"?"dirt":t==="gravel"||t==="fine_gravel"||t==="compacted"||t==="ground"||t==="sand"||t==="unpaved"?"gravel":t?"paved":e.highway==="track"?"gravel":"paved"}}const Ob="https://ufoathome.org/roads/index.json";class Pd{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Pd.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRoads(e);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(e){let t;try{t=await this.load()}catch{return}const i=t.find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.ways)?(this.attributionRead=n.attribution,this.contemporaryRead=n.contemporary,n.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8954
|
-
`);let t=Pd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Pd.shared.set(e,t),t.then(i=>{i.length===0&&Pd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.
|
|
8955
|
-
`);let t=Nd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Nd.shared.set(e,t),t.then(i=>{i.length===0&&Nd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.194.0")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==Lb?[t,Lb]:[Lb]).map(i=>i+e)}}class Tr{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=Tr.key(e);let i=Tr.asked.get(t);return i===void 0&&(i=this.recalled(t,e),Tr.asked.set(t,i),i.catch(()=>Tr.asked.delete(t))),structuredClone(await i)}static forget(){Tr.asked.clear()}static key(e){return`v${Tr.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await Tr.openCache(),s=Tr.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<Tr.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&Tr.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-Tr.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Tr.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class tl{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Xt(e)}static covers(e){return Xt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>tl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=tl.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),c=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=tl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=tl.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>tl.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(c)?c:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class Cn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new Pr(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${Cn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return Cn.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=Cn.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(v=>lt(v.lat,v.lng,s.lat,s.lng)),o=new Map,c=new Map,h=new Map;let d=0;const u=n.filter(v=>v.service===!!r.service);for(const v of Cn.samples(a)){d++;const b=Cn.waysAt(u,v);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&c.set(w.voltageV,(c.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=v=>[...v.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(c)),g=[...h.entries()].filter(([,v])=>v*4>=d).sort((v,b)=>b[1]-v[1]||v[0].localeCompare(b[0])).map(([v])=>v);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=Cn.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=Cn.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=Cn.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>lt(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=Cn.SAMPLE_M/2;a<s;a+=Cn.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(Cn.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],c=n.path[a+1],h=c.x-o.x,d=c.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=Cn.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class Fd{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new Pr(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Fd.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Cn.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=Cn.voltageOf(r),c=Fd.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=Fd.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:c,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:Fd.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class G8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!tl.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class Ks{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=Ks.key(e);let i=Ks.asked.get(t)??Ks.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Ks.asked.set(t,i),s.catch(()=>Ks.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Ks.asked.clear(),Ks.failedAt=-1/0}static key(e){return`v${Ks.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Ks.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await Ks.openCache(),s=Ks.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:c}=await a.json();if(Array.isArray(c)){if(this.now()-o<Ks.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-Ks.failedAt<Ks.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(Ks.failedAt=this.now(),n)return n;throw a}return i&&Ks.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-Ks.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ks.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const Pb="https://ufoathome.org/railways/index.json";class Ud{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Ud.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8956
|
-
`);let t=Ud.shared.get(e);return t||(t=this.fetchFirstAvailable(),Ud.shared.set(e,t),t.then(i=>{i.length===0&&Ud.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.194.0")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==Pb?[t,Pb]:[Pb]).map(i=>i+e)}}function _I(){return{elevation:DI(),imagery:kI(),roads:RI(),water:CI(),railways:OI()}}function DI(){return new F8(new Bt,new AI)}function kI(){return new II}function RI(){return new Pd({fallback:new z8(new el,new Yc)})}function CI(){return new Nd({fallback:new Tr(new H8(new Uf,new Ql))})}function OI(){return new Ud({fallback:new Ks(new G8(new tl,new Fd))})}const V8=new Set,ru="show-observer-map",au="hide-milestones",ch="minified";class Zt extends HTMLElement{static get observedAttributes(){return["src",ru,au,ch]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new bi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=cv.create();issues=[];issueCheck=0;sightingAudio=new m2;liveSightingAudio;hearInto(e){e?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new m2(e)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Zt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,s=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");Zt.setIcon(this.moreButton,e?Je.UNFOLDED:Je.FOLDED);const t=e?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(e){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!e){this.fitControls();return}const t=document.createElement("button");t.type="button",t.id="video-button",t.innerHTML=Je.VIDEO,this.videoElement=t,this.labelVideoButton(),t.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(e,t)},{once:!0}),this.moreButton.after(t),this.fitControls()}async loadVideoButton(e,t){const{VideoButton:i}=await H(async()=>{const{VideoButton:n}=await import("./VideoButton-Kxg7pF1Y.js");return{VideoButton:n}},[],import.meta.url);if(this.videoElement!==t)return;const s=new i(e,t);this.videoButton=s,this.messages&&(s.messages=this.messages),this.stageElement.append(s.panel),s.open()}labelVideoButton(){const e=this.videoElement;!e||this.videoButton||(e.title=this.messages?.recordVideo??"",e.setAttribute("aria-label",e.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(e){e!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,e&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(e){const t=this.currentTime,i=e.caption&&this.sighting.milestones.length>0?Gm(this.sighting.milestones,t):void 0,s=i?this.said.read(i.label)??"":void 0,n=this.canvas.getBoundingClientRect(),r=e.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:s,note:this.said.read(i.note)}}:{},...e.time?{time:this.formatPosition(t)}:{},...r&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-n.left)/n.width,top:(r.top-n.top)/n.height,width:r.width/n.width,height:r.height/n.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.y),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<Zt.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=bi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=bi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Zt.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const s=bi.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${M8}</style>${w8}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new _u(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Jl(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),c=this.player.seekableDuration;if(o.width<=0||c<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===ru&&this.applyObserverMapDefault(),e===au&&this.setMilestonesShown(!this.hasAttribute(au)),e===ch){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(ch)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(LI)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await ba.recording(e)}get sightingData(){return Lf(this.currentSighting)}set sightingData(e){const t=An.recording(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=Jf(t),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;set titleShown(e){this.titleHidden=!e,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let s=[];try{const{default:n}=await H(async()=>{const{default:r}=await import("./sightingSchema-CgwoRMl-.js");return{default:r}},[],import.meta.url);s=new ua(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],Ff.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent($8,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=(this.messages?.recordingIssues??"").replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const s=document.createElement("li");return s.textContent=Ff.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(e){this.cited=[...e],this.refreshCitedMarks()}refreshCitedMarks(){const e=this.player.seekableDuration;this.citedMarks.replaceChildren(...(e>0?this.cited:[]).map(t=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=de.INTERVIEW,i.style.left=`${Math.min(Math.max(t.at*1e3/e,0),1)*100}%`;const s=t.quote??"";return i.title=s,i.setAttribute("aria-label",s),i.addEventListener("click",()=>this.player.seek(t.at*1e3)),i}))}sayTimeMoved(e){Math.abs(e-this.timeSaid)<Zt.TIME_SAID_EVERY_MS||(this.timeSaid=e,this.dispatchEvent(new CustomEvent(W8,{bubbles:!0,composed:!0,detail:{at:e/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of t)this.controlsRight.insertBefore(s,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;if(!this.referenceOpacityTouched&&e.length>0){const t=String(e[0].opacity);this.referenceOpacityInput.value!==t&&(this.referenceOpacityInput.value=t,this.severalReferences||this.dispatchReferenceView())}for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages?.referenceOpacity??"",c.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${s}`),c.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),n.append(r,c),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Zt.setIcon(this.referencesButton,i?Je.PICTURES_ON:Je.PICTURES_OFF);const s=t?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Zt.setIcon(this.tracesButton,this.tracesShownState?Je.TRACES_ON:Je.TRACES_OFF);const e=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?bh(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),this.refreshCitedMarks(),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const s=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(o,c),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:c,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=Zt.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){if(e.buttons!==0){this.seekPreview.hidden=!0;return}const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=Zt.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?Gm(a,n):void 0,c=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new _u(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const s=Zt.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?Gm(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=Xn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<Zt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Zt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Zt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Zt.EXPOSURE_STEP_PX),n=Math.min(Zt.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const c=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(c,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=Vt.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(e,t){this.sayTimeMoved(e),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:V8;this.canvasRenderer.setStarPoints(Vt.starPointsOf(this.sighting.instrument,et(this.sighting,e)?.fNumber));const s=(et(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,c]of o.shapes){const h=o.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,c]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?ai.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(Xw(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new x8(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*Zt.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Je.PLAY:Je.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){Zt.icons.get(e)!==t&&(Zt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Zt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),Zt.setIcon(this.playPauseButton,e?Je.PAUSE:Je.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(ru),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;Zt.setIcon(this.observerMapButton,e?Je.MAP_ON:Je.MAP_OFF);const t=e?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=wh.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(s=>s.points):[],i=bi.fitted(this.observerPath,t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?bi.expand(e,Zt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=bi.IMAGERY_PX*(t?1+2*Zt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,r=n?void 0:kI();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,s=this.observerMapView.changed?bi.expand(e,Zt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(e){e!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=Zt.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=et(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},Zt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?Gm(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?bh(this.currentSighting.milestones):[]){const a=et(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Qr.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Vt.aspectOf(i)):void 0,markers:s,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,bh(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",Zt.setIcon(this.milestonesButton,this.milestonesShown?Je.MILESTONES_ON:Je.MILESTONES_OFF);const e=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=et(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=ia(i,e),{lat:n,lng:r}=wr(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const s=et(this.currentSighting,this.currentTime),n=Qr.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return Ti.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=Zt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Zt.setIcon(this.miniMuteButton,this.mutedState?Je.MUTED:Je.VOLUME);const t=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){Zt.setIcon(this.muteButton,Je.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Zt.setIcon(this.muteButton,this.mutedState?Je.MUTED:Je.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Zt.setIcon(this.fullscreenButton,e?Je.EXIT_FULLSCREEN:Je.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Bs(zs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Wa(zs.preferencesFor(this),Ga);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await P_.load(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+t,this.timeEndLabel.title=(this.messages?.duration??"")+t,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.videoButton&&(this.videoButton.messages=e),this.labelVideoButton(),this.volumeInput.title=e.volume,this.volumeInput.setAttribute("aria-label",e.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=Dh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Zy(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return Nc(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?y2(b2(this.realStartMs+i)):Nc(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Nc(e):Nc(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Nc(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Nc(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Nc(this.currentSighting.timeline.duration):this.canShowClockTime?y2(b2(this.realStartMs+this.realDurationMs)):Nc(this.realDurationMs)}}function b2(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function y2(l){if(l.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return l.second?`${e(l.hour)}:${e(l.minute??0)}:${e(l.second)}`:`${e(l.hour)}:${e(l.minute??0)}`}function Nc(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Z1="rr0-ufo";function yv(){customElements.get(Z1)||customElements.define(Z1,Zt)}const W8="timechange",$8="recordingissues",LI="minifiedreset";class kp{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+kp.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-kp.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=kp.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Bd{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const g=n.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const v=lt(g.lat,g.lng,s.lat,s.lng);return{eastM:v.x,northM:-v.z,heading:g.headingDeg,aboveM:g.elevationM??0,altitudeM:g.altitudeM}},a=r(t-Bd.HALF_SPAN_MS),o=r(t+Bd.HALF_SPAN_MS),c=r(t);if(!a||!o||!c)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*Bd.HALF_SPAN_MS/1e3;if(h/d<Bd.MIN_SPEED_MS)return 0;const u=o.altitudeM!==void 0&&a.altitudeM!==void 0?o.altitudeM-a.altitudeM:i.heightAt(o.eastM,o.northM)+o.aboveM-i.heightAt(a.eastM,a.northM)-a.aboveM,p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const K8=.08,w2=.15,M2=2,X8=2e3;class x2{context;constructor(e){this.context=e}noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}na.isLive(this.context)&&na.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);na.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(s=>s.inside||s.distanceM<X8),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const c=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*M2*.5,M},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const g=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const b=e.createGain();g.connect(v).connect(b).connect(s);const w=[n,r,h,p,g];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,v,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const c=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,c,K8),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,g);const v=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,v*n)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,w2/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},w2*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*M2,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Bf{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Bf.BY_KIND[e??"generic"]??Bf.BY_KIND.generic}}class On{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(e){return On.ROAD_KINDS.includes(e)}static roadOf(e){return e&&On.isRoad(e.kind)?e.kind:void 0}static aircraftOf(e){return e&&!On.isRoad(e.kind)?e.kind:void 0}static transmission(e){const t=On.insulationDb(e),i=[3,4,5].map(s=>t[s]);return 10**(-(i.reduce((s,n)=>s+n,0)/i.length)/20)}static insulationDb(e){return e?e.windowsOpen===!0?On.WINDOWS_OPEN_DB:On.isRoad(e.kind)?On.ROAD_CLOSED_DB:On.CANOPIED.includes(e.kind)?On.CANOPY_DB:On.FUSELAGE_DB:On.OPEN_AIR}}class lh{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=lh.SAMPLE_MS,r=[];for(let c=i;c<=s+n/2;c+=n){const h=t(c-n/2),d=t(c+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*n/1e3);if(h<lh.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),g=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:g,gear:o})}return new lh(a,i)}at(e){const t=(e-this.startMs)/lh.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class Ig{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=h=>{const d=e.observerTrack.getInterpolatedPoseAt(h),u=d?.lat??s?.lat,p=d?.lng??s?.lng;if(u===void 0||p===void 0||!s)return;const f=lt(u,p,s.lat,s.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle,o=On.roadOf(a);if(a&&o){const h=Bf.of(o),d=this.drive(`observer:${o}`,Ig.trackKey(e),()=>lh.of(h,n,0,r));d&&i.push({id:"observer",profile:h,state:d.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const c=n(t);for(const h of e.decor){if(!h.engine||!c)continue;const d=Bf.of(h.engine.kind),u=g=>{const v=ia(h,g);return{eastM:v.eastM,northM:v.northM}},p=this.drive(`decor:${h.id}`,Ig.decorKey(h,r),()=>lh.of(d,u,0,r));if(!p)continue;const f=ia(h,t),m=Math.hypot(f.eastM-c.eastM,f.northM-c.northM,f.altitudeM);i.push({id:`decor:${h.id}`,profile:d,state:p.at(t),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:m})}return i}drive(e,t,i){const s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const Y8="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",q8=`
|
|
8955
|
+
`);let t=Pd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Pd.shared.set(e,t),t.then(i=>{i.length===0&&Pd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.195.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==Ob?[t,Ob]:[Ob]).map(i=>i+e)}}class el{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(e={}){this.platform=new Xt(e)}static covers(e){return Xt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,s)=>el.wayOf(i,s))}static wayOf(e,t){if(e.geometry.type!=="LineString")return[];const i=e.geometry.coordinates.map(([u,p])=>({lat:p,lng:u}));if(i.length<2)return[];const s=String(e.properties.nature??""),n=el.BY_NATURE[s]??el.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),o=Number(e.properties.vitesse_moyenne_vl),c=el.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=el.KINDS[s],d=[e.properties.cpx_toponyme_route_nommee,e.properties.nom_voie_ban_gauche,e.properties.nom_voie_ban_droite].find(u=>typeof u=="string"&&u.length>0);return[{id:String(e.properties.cleabs??`ign-${t}`),...d?{name:d}:{},surface:n.surface,widthM:Number.isFinite(r)&&r>0?r:n.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...c?{direction:c}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{},points:i}]}}class z8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(e){if(el.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}class Uf{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(e={}){this.platform=new Xt(e)}static covers(e){return Xt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getWater(e){return(await this.platform.waterSurfaces(e)).flatMap((i,s)=>Uf.surfacesOf(i,s))}static surfacesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="Polygon"?[s]:i==="MultiPolygon"?s:[],r=String(e.properties.cleabs??`ign-water-${t}`);return n.flatMap((a,o)=>{const c=a.map(h=>Uf.open(h.map(d=>({lat:d[1],lng:d[0]})))).filter(h=>h.length>=3);return c.length>0?[{id:n.length>1?`${r}-${o}`:r,rings:c}]:[]})}static open(e){const t=e[0],i=e[e.length-1];return e.length>1&&t.lat===i.lat&&t.lng===i.lng?e.slice(0,-1):e}}class Ql{attribution="Water © OpenStreetMap contributors";client;constructor(e={}){this.client=new Pr(e)}async getWater(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${t});way["waterway"="riverbank"](${t});)->.w;(relation["natural"="water"](${t});relation["waterway"="riverbank"](${t});)->.r;.w out geom;.r out body;way(r.r)(${t});out geom;`;return Ql.surfacesFrom(await this.client.query(i))}static surfacesFrom(e){const t=e.elements??[],i=new Map;for(const r of t)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const s=[],n=new Set;for(const r of t){if(r.type!=="relation")continue;const a=c=>(r.members??[]).filter(h=>h.type==="way"&&h.role===c&&h.ref!==void 0&&i.has(h.ref)).map(h=>(n.add(h.ref),i.get(h.ref))),o=Ql.rings(a("inner"));for(const[c,h]of Ql.rings(a("outer")).entries()){const d=o.filter(u=>Ql.contains(h,u[0]));s.push({id:`osm-r${r.id}-${c}`,rings:[h,...d]})}}for(const r of t)if(!(r.type!=="way"||!r.tags||r.id===void 0||n.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of Ql.rings([i.get(r.id)??[]]))s.push({id:`osm-w${r.id}`,rings:[a]});return s}static rings(e){const t=(n,r)=>n.lat===r.lat&&n.lng===r.lng,i=e.filter(n=>n.length>=2).map(n=>[...n]),s=[];for(;i.length>0;){let n=i.pop(),r=!0;for(;!t(n[0],n[n.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const o=i[a],c=n[n.length-1];if(t(c,o[0]))n=[...n,...o.slice(1)];else if(t(c,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}n.length>=4&&t(n[0],n[n.length-1])&&s.push(n.slice(0,-1))}return s}static contains(e,t){let i=!1;for(let s=0,n=e.length-1;s<e.length;n=s++){const r=e[s],a=e[n];r.lat>t.lat!=a.lat>t.lat&&t.lng<(a.lng-r.lng)*(t.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class H8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(e){if(Uf.covers(e))try{const t=await this.regional.getWater(e);if(t.length>0)return t}catch{}return this.worldwide.getWater(e)}}const Lb="https://ufoathome.org/water/index.json";class Nd{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Nd.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getWater(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.surfaces)?(this.attributionRead=n.attribution,n.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8956
|
+
`);let t=Nd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Nd.shared.set(e,t),t.then(i=>{i.length===0&&Nd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.195.0")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==Lb?[t,Lb]:[Lb]).map(i=>i+e)}}class Tr{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=Tr.key(e);let i=Tr.asked.get(t);return i===void 0&&(i=this.recalled(t,e),Tr.asked.set(t,i),i.catch(()=>Tr.asked.delete(t))),structuredClone(await i)}static forget(){Tr.asked.clear()}static key(e){return`v${Tr.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await Tr.openCache(),s=Tr.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<Tr.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&Tr.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-Tr.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Tr.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class tl{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Xt(e)}static covers(e){return Xt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>tl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=tl.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),c=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=tl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=tl.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>tl.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(c)?c:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class Cn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new Pr(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${Cn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return Cn.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=Cn.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(v=>lt(v.lat,v.lng,s.lat,s.lng)),o=new Map,c=new Map,h=new Map;let d=0;const u=n.filter(v=>v.service===!!r.service);for(const v of Cn.samples(a)){d++;const b=Cn.waysAt(u,v);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&c.set(w.voltageV,(c.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=v=>[...v.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(c)),g=[...h.entries()].filter(([,v])=>v*4>=d).sort((v,b)=>b[1]-v[1]||v[0].localeCompare(b[0])).map(([v])=>v);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=Cn.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=Cn.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=Cn.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>lt(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=Cn.SAMPLE_M/2;a<s;a+=Cn.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(Cn.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],c=n.path[a+1],h=c.x-o.x,d=c.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=Cn.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class Fd{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new Pr(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Fd.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Cn.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=Cn.voltageOf(r),c=Fd.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=Fd.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:c,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:Fd.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class G8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!tl.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class Ks{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=Ks.key(e);let i=Ks.asked.get(t)??Ks.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Ks.asked.set(t,i),s.catch(()=>Ks.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Ks.asked.clear(),Ks.failedAt=-1/0}static key(e){return`v${Ks.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Ks.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await Ks.openCache(),s=Ks.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:c}=await a.json();if(Array.isArray(c)){if(this.now()-o<Ks.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-Ks.failedAt<Ks.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(Ks.failedAt=this.now(),n)return n;throw a}return i&&Ks.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-Ks.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Ks.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const Pb="https://ufoathome.org/railways/index.json";class Ud{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Ud.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8957
|
+
`);let t=Ud.shared.get(e);return t||(t=this.fetchFirstAvailable(),Ud.shared.set(e,t),t.then(i=>{i.length===0&&Ud.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.195.0")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==Pb?[t,Pb]:[Pb]).map(i=>i+e)}}function _I(){return{elevation:DI(),imagery:kI(),roads:RI(),water:CI(),railways:OI()}}function DI(){return new F8(new Bt,new AI)}function kI(){return new II}function RI(){return new Pd({fallback:new z8(new el,new Yc)})}function CI(){return new Nd({fallback:new Tr(new H8(new Uf,new Ql))})}function OI(){return new Ud({fallback:new Ks(new G8(new tl,new Fd))})}const V8=new Set,ru="show-observer-map",au="hide-milestones",ch="minified";class Zt extends HTMLElement{static get observedAttributes(){return["src",ru,au,ch]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new bi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=cv.create();issues=[];issueCheck=0;sightingAudio=new m2;liveSightingAudio;hearInto(e){e?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new m2(e)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Zt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,s=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");Zt.setIcon(this.moreButton,e?Je.UNFOLDED:Je.FOLDED);const t=e?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(e){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!e){this.fitControls();return}const t=document.createElement("button");t.type="button",t.id="video-button",t.innerHTML=Je.VIDEO,this.videoElement=t,this.labelVideoButton(),t.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(e,t)},{once:!0}),this.moreButton.after(t),this.fitControls()}async loadVideoButton(e,t){const{VideoButton:i}=await H(async()=>{const{VideoButton:n}=await import("./VideoButton-Kxg7pF1Y.js");return{VideoButton:n}},[],import.meta.url);if(this.videoElement!==t)return;const s=new i(e,t);this.videoButton=s,this.messages&&(s.messages=this.messages),this.stageElement.append(s.panel),s.open()}labelVideoButton(){const e=this.videoElement;!e||this.videoButton||(e.title=this.messages?.recordVideo??"",e.setAttribute("aria-label",e.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(e){e!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,e&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(e){const t=this.currentTime,i=e.caption&&this.sighting.milestones.length>0?Gm(this.sighting.milestones,t):void 0,s=i?this.said.read(i.label)??"":void 0,n=this.canvas.getBoundingClientRect(),r=e.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:s,note:this.said.read(i.note)}}:{},...e.time?{time:this.formatPosition(t)}:{},...r&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-n.left)/n.width,top:(r.top-n.top)/n.height,width:r.width/n.width,height:r.height/n.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.y),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<Zt.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=bi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=bi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Zt.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const s=bi.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${M8}</style>${w8}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new _u(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Jl(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),c=this.player.seekableDuration;if(o.width<=0||c<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===ru&&this.applyObserverMapDefault(),e===au&&this.setMilestonesShown(!this.hasAttribute(au)),e===ch){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(ch)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(LI)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await ba.recording(e)}get sightingData(){return Lf(this.currentSighting)}set sightingData(e){const t=An.recording(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=Jf(t),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;set titleShown(e){this.titleHidden=!e,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let s=[];try{const{default:n}=await H(async()=>{const{default:r}=await import("./sightingSchema-CgwoRMl-.js");return{default:r}},[],import.meta.url);s=new ua(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],Ff.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent($8,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=(this.messages?.recordingIssues??"").replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const s=document.createElement("li");return s.textContent=Ff.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(e){this.cited=[...e],this.refreshCitedMarks()}refreshCitedMarks(){const e=this.player.seekableDuration;this.citedMarks.replaceChildren(...(e>0?this.cited:[]).map(t=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=de.INTERVIEW,i.style.left=`${Math.min(Math.max(t.at*1e3/e,0),1)*100}%`;const s=t.quote??"";return i.title=s,i.setAttribute("aria-label",s),i.addEventListener("click",()=>this.player.seek(t.at*1e3)),i}))}sayTimeMoved(e){Math.abs(e-this.timeSaid)<Zt.TIME_SAID_EVERY_MS||(this.timeSaid=e,this.dispatchEvent(new CustomEvent(W8,{bubbles:!0,composed:!0,detail:{at:e/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of t)this.controlsRight.insertBefore(s,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;if(!this.referenceOpacityTouched&&e.length>0){const t=String(e[0].opacity);this.referenceOpacityInput.value!==t&&(this.referenceOpacityInput.value=t,this.severalReferences||this.dispatchReferenceView())}for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages?.referenceOpacity??"",c.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${s}`),c.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),n.append(r,c),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Zt.setIcon(this.referencesButton,i?Je.PICTURES_ON:Je.PICTURES_OFF);const s=t?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Zt.setIcon(this.tracesButton,this.tracesShownState?Je.TRACES_ON:Je.TRACES_OFF);const e=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?bh(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),this.refreshCitedMarks(),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const s=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(o,c),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:c,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=Zt.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){if(e.buttons!==0){this.seekPreview.hidden=!0;return}const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=Zt.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?Gm(a,n):void 0,c=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new _u(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const s=Zt.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?Gm(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=Xn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<Zt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Zt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Zt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Zt.EXPOSURE_STEP_PX),n=Math.min(Zt.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const c=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(c,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=Vt.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(e,t){this.sayTimeMoved(e),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:V8;this.canvasRenderer.setStarPoints(Vt.starPointsOf(this.sighting.instrument,et(this.sighting,e)?.fNumber));const s=(et(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,c]of o.shapes){const h=o.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,c]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?ai.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(Xw(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new x8(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*Zt.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Je.PLAY:Je.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){Zt.icons.get(e)!==t&&(Zt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Zt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),Zt.setIcon(this.playPauseButton,e?Je.PAUSE:Je.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(ru),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;Zt.setIcon(this.observerMapButton,e?Je.MAP_ON:Je.MAP_OFF);const t=e?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=wh.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(s=>s.points):[],i=bi.fitted(this.observerPath,t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?bi.expand(e,Zt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=bi.IMAGERY_PX*(t?1+2*Zt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,r=n?void 0:kI();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,s=this.observerMapView.changed?bi.expand(e,Zt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(e){e!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=Zt.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=et(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},Zt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?Gm(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?bh(this.currentSighting.milestones):[]){const a=et(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Qr.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Vt.aspectOf(i)):void 0,markers:s,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,bh(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",Zt.setIcon(this.milestonesButton,this.milestonesShown?Je.MILESTONES_ON:Je.MILESTONES_OFF);const e=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=et(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=ia(i,e),{lat:n,lng:r}=wr(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const s=et(this.currentSighting,this.currentTime),n=Qr.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return Ti.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=Zt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Zt.setIcon(this.miniMuteButton,this.mutedState?Je.MUTED:Je.VOLUME);const t=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){Zt.setIcon(this.muteButton,Je.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Zt.setIcon(this.muteButton,this.mutedState?Je.MUTED:Je.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Zt.setIcon(this.fullscreenButton,e?Je.EXIT_FULLSCREEN:Je.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Bs(zs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Wa(zs.preferencesFor(this),Ga);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await P_.load(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+t,this.timeEndLabel.title=(this.messages?.duration??"")+t,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.videoButton&&(this.videoButton.messages=e),this.labelVideoButton(),this.volumeInput.title=e.volume,this.volumeInput.setAttribute("aria-label",e.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=Dh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Zy(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return Nc(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?y2(b2(this.realStartMs+i)):Nc(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Nc(e):Nc(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Nc(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Nc(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Nc(this.currentSighting.timeline.duration):this.canShowClockTime?y2(b2(this.realStartMs+this.realDurationMs)):Nc(this.realDurationMs)}}function b2(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function y2(l){if(l.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return l.second?`${e(l.hour)}:${e(l.minute??0)}:${e(l.second)}`:`${e(l.hour)}:${e(l.minute??0)}`}function Nc(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Z1="rr0-ufo";function yv(){customElements.get(Z1)||customElements.define(Z1,Zt)}const W8="timechange",$8="recordingissues",LI="minifiedreset";class kp{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+kp.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-kp.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=kp.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Bd{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const g=n.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const v=lt(g.lat,g.lng,s.lat,s.lng);return{eastM:v.x,northM:-v.z,heading:g.headingDeg,aboveM:g.elevationM??0,altitudeM:g.altitudeM}},a=r(t-Bd.HALF_SPAN_MS),o=r(t+Bd.HALF_SPAN_MS),c=r(t);if(!a||!o||!c)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*Bd.HALF_SPAN_MS/1e3;if(h/d<Bd.MIN_SPEED_MS)return 0;const u=o.altitudeM!==void 0&&a.altitudeM!==void 0?o.altitudeM-a.altitudeM:i.heightAt(o.eastM,o.northM)+o.aboveM-i.heightAt(a.eastM,a.northM)-a.aboveM,p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const K8=.08,w2=.15,M2=2,X8=2e3;class x2{context;constructor(e){this.context=e}noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}na.isLive(this.context)&&na.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);na.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(s=>s.inside||s.distanceM<X8),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const c=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*M2*.5,M},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const g=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const b=e.createGain();g.connect(v).connect(b).connect(s);const w=[n,r,h,p,g];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,v,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const c=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,c,K8),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,g);const v=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,v*n)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,w2/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},w2*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*M2,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Bf{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Bf.BY_KIND[e??"generic"]??Bf.BY_KIND.generic}}class On{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(e){return On.ROAD_KINDS.includes(e)}static roadOf(e){return e&&On.isRoad(e.kind)?e.kind:void 0}static aircraftOf(e){return e&&!On.isRoad(e.kind)?e.kind:void 0}static transmission(e){const t=On.insulationDb(e),i=[3,4,5].map(s=>t[s]);return 10**(-(i.reduce((s,n)=>s+n,0)/i.length)/20)}static insulationDb(e){return e?e.windowsOpen===!0?On.WINDOWS_OPEN_DB:On.isRoad(e.kind)?On.ROAD_CLOSED_DB:On.CANOPIED.includes(e.kind)?On.CANOPY_DB:On.FUSELAGE_DB:On.OPEN_AIR}}class lh{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=lh.SAMPLE_MS,r=[];for(let c=i;c<=s+n/2;c+=n){const h=t(c-n/2),d=t(c+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*n/1e3);if(h<lh.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),g=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:g,gear:o})}return new lh(a,i)}at(e){const t=(e-this.startMs)/lh.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class Ig{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=h=>{const d=e.observerTrack.getInterpolatedPoseAt(h),u=d?.lat??s?.lat,p=d?.lng??s?.lng;if(u===void 0||p===void 0||!s)return;const f=lt(u,p,s.lat,s.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle,o=On.roadOf(a);if(a&&o){const h=Bf.of(o),d=this.drive(`observer:${o}`,Ig.trackKey(e),()=>lh.of(h,n,0,r));d&&i.push({id:"observer",profile:h,state:d.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const c=n(t);for(const h of e.decor){if(!h.engine||!c)continue;const d=Bf.of(h.engine.kind),u=g=>{const v=ia(h,g);return{eastM:v.eastM,northM:v.northM}},p=this.drive(`decor:${h.id}`,Ig.decorKey(h,r),()=>lh.of(d,u,0,r));if(!p)continue;const f=ia(h,t),m=Math.hypot(f.eastM-c.eastM,f.northM-c.northM,f.altitudeM);i.push({id:`decor:${h.id}`,profile:d,state:p.at(t),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:m})}return i}drive(e,t,i){const s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const Y8="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",q8=`
|
|
8957
8958
|
<div class="stage" id="stage">
|
|
8958
8959
|
<div class="frame" id="frame">
|
|
8959
8960
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -11577,7 +11578,7 @@ ${c.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
11577
11578
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
11578
11579
|
}
|
|
11579
11580
|
`,transparent:!0,depthWrite:!1,side:ln,fog:!1,blending:kh,blendSrc:Rh,blendDst:xf})}static wallReflectance(e,t,i){const s=i(e,1,t);return 2*s/(1+s)}static DISCS={uDiscDirection:{value:[new I(0,1,0),new I(0,1,0)]},uDiscCosRadius:{value:[2,2]},uDiscRadiance:{value:[new I,new I]}};static DISC_INDEX={sun:0,moon:1};static setDisc(e,t){const i=Qn.DISC_INDEX[e],s=Qn.DISCS;if(!t){s.uDiscCosRadius.value[i]=2,s.uDiscRadiance.value[i].set(0,0,0);return}s.uDiscDirection.value[i].set(...t.direction).normalize(),s.uDiscCosRadius.value[i]=Math.cos(t.radiusRad),s.uDiscRadiance.value[i].set(...t.radiance)}setSurroundings(e){this.uniforms.uSurroundings.value=e}static reflectedResponse(e,t){return Ke.respond(t*Ke.relativeOfResponse(Math.max(e,1e-5)))}}class _r{static SIZE=64;static MOVE_M=.01;holder=new ns;cameras=[];faces=[];target=new di(_r.SIZE,_r.SIZE);white=new Mr({color:new ce(1,1,1),side:ln});scene=new ra;cabin;meshes=0;eye=new I;scratch=new I;constructor(){const e=[[new I(1,0,0),new I(0,1,0)],[new I(-1,0,0),new I(0,1,0)],[new I(0,1,0),new I(0,0,1)],[new I(0,-1,0),new I(0,0,-1)],[new I(0,0,1),new I(0,1,0)],[new I(0,0,-1),new I(0,1,0)]];for(const[t,i]of e){const s=new Pn(90,1,.02,20);s.up.copy(i),s.lookAt(t),this.holder.add(s),this.cameras.push(s),this.faces.push(new Uint8Array(_r.SIZE*_r.SIZE*4))}this.scene.background=new ce(0,0,0)}get any(){return this.cabin!==void 0}update(e,t,i){if(!t){this.forget();return}t.updateWorldMatrix(!0,!0);const s=this.scratch.copy(i);t.worldToLocal(s);let n=0;t.traverse(r=>{r.isMesh&&n++}),!(t===this.cabin&&n===this.meshes&&s.distanceTo(this.eye)<_r.MOVE_M)&&(this.cabin=t,this.meshes=n,this.eye.copy(s),this.draw(e,t))}hides(e){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let t=0;t<6;t++){const i=this.cameras[t],s=this.scratch.copy(e).transformDirection(i.matrixWorldInverse);if(s.z>=0)continue;const n=s.x/-s.z,r=s.y/-s.z;if(Math.abs(n)>1||Math.abs(r)>1)continue;const a=Math.min(_r.SIZE-1,Math.floor((n+1)/2*_r.SIZE)),o=Math.min(_r.SIZE-1,Math.floor((r+1)/2*_r.SIZE));return this.faces[t][(o*_r.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(e,t){t.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];t.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof Qn))return;const c=new ve(a.geometry,this.white);c.matrixAutoUpdate=!1,c.matrix.copy(a.matrixWorld),c.matrixWorld.copy(a.matrixWorld),i.push(c)});for(const r of i)this.scene.add(r);const s=e.getRenderTarget(),n=e.shadowMap.autoUpdate;e.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),e.setRenderTarget(this.target),e.clear(),e.render(this.scene,a),Pg.now(e,this.target,0,0,_r.SIZE,_r.SIZE,this.faces[r])}e.setRenderTarget(s),e.shadowMap.autoUpdate=n;for(const r of i)r.removeFromParent()}}const Kb="https://ufoathome.org/models/index.json";class Bp{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??v7()}async entries(e){const t=await this.load();return e?t.filter(i=>[i.kind].flat().includes(e)):t}async entry(e){return(await this.load()).find(t=>t.id===e)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
11580
|
-
`);let t=Bp.shared.get(e);return t||(t=this.fetchFirstAvailable(),Bp.shared.set(e,t),t.then(i=>{i.length===0&&Bp.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function v7(){const l=`?v=${encodeURIComponent("0.
|
|
11581
|
+
`);let t=Bp.shared.get(e);return t||(t=this.fetchFirstAvailable(),Bp.shared.set(e,t),t.then(i=>{i.length===0&&Bp.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function v7(){const l=`?v=${encodeURIComponent("0.195.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==Kb?[e,Kb]:[Kb]).map(t=>t+l)}const hw=Xe.point("decorModels").provide(Xe.BUILT_IN,[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new Bp}]);class zp{constructor(e,t=hw){this.preferredId=e,this.sources=t}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const e=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(e?[e,...this.sources.filter(i=>i!==e)]:[]).map(i=>{let s=this.built.get(i);return s||(s=i.create(),this.built.set(i,s)),s})}entries(e){const t=this.catalogues()[0];return t?t.entries(e):Promise.resolve([])}async entry(e){for(const t of this.catalogues()){const i=await t.entry(e).catch(()=>{});if(i)return i}}async moduleOf(e){const t=Xe.point("decorModels");for(const i of this.sources){const s=t.ownerOf(i.id);if(!(s===void 0||s===Xe.BUILT_IN)&&await this.catalogueOf(i).entry(e).catch(()=>{}))return s}}catalogueOf(e){return this.catalogues(),this.built.get(e)}}async function Xb(l){const{GLTFLoader:e}=await H(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-C6nlGTTi.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,s)=>{t.load(l,n=>i(Object.assign(n.scene,{animations:n.animations})),void 0,n=>s(new Error(`Could not load 3D model ${l}: ${n instanceof Error?n.message:String(n)}`)))})}class jr{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new ve(new ar(2,2),new Nt({uniforms:{uColor:{value:new ce(0,0,0)},uRadius:{value:1}},vertexShader:jr.VERTEX,fragmentShader:jr.FRAGMENT,transparent:!0,depthWrite:!1,blending:pn,toneMapped:!1})),this.mesh.name=e,this.mesh.frustumCulled=!1,this.mesh.renderOrder=t,this.mesh.visible=!1}shine(e,t,i){this.mesh.visible=!0,this.mesh.position.set(e.x,e.y,e.z),this.mesh.material.uniforms.uRadius.value=t,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(e,t,i,s){const n=Math.max(e,s*jr.MIN_ANGLE_RAD),r=jr.FILL*Math.PI*n*n;return{radiusM:n,luminanceCdM2:i*Math.min(jr.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(jr.MAX_SHARE*jr.FILL*Math.PI))}static VERTEX=`
|
|
11581
11582
|
uniform float uRadius;
|
|
11582
11583
|
varying vec2 vOffset;
|
|
11583
11584
|
void main() {
|
|
@@ -12299,7 +12300,7 @@ ${Gt.rules([],[".model-picker .model-picker-address p"])}
|
|
|
12299
12300
|
.model-picker .model-name { font-weight: 600; }
|
|
12300
12301
|
.model-picker .model-credit { font-size: .8em; color: #666; }
|
|
12301
12302
|
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await H(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-DSshyLu2.js");return{ModelThumbnails:i}},__vite__mapDeps([40,41]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const s=document.createElement("button");s.type="button",s.className="model-picker-button",e.after(s),e.hidden=!0;let n=0,r;const a=()=>{const c=++n,h=e.selectedOptions[0],d=e.value===""?i?.current():void 0,u=JSON.stringify([e.value,h?.textContent,d?.url,d?.title,this.messages().choose,[...e.options].map(m=>m.value).join()]);if(u===r){--n;return}r=u,s.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,s.title=this.messages().choose,s.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(m=>Xp.pictureOf(m)).then(m=>{if(!m||c!==n)return;const g=new Image;g.src=m,g.alt="",s.prepend(g)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:c=>{i.apply(c),a()}};s.addEventListener("click",()=>void this.open(e,t,o)),a()}chooseFrom(e,t,i,s){this.ensureStyle(),this.open(e,t,s,i)}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=Xp.STYLE,t.append(i)}open(e,t,i,s){const n=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const a=document.createElement("div");a.className="model-picker",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=n.title;const c=document.createElement("button");c.type="button",c.className="model-picker-close",c.setAttribute("aria-label",n.close),c.title=n.close,c.innerHTML=de.CLOSE;const h=document.createElement("header");h.append(o,c);const d=document.createElement("div");d.className="model-picker-body",a.append(h,d),r.append(a);const u=()=>{r.remove(),document.removeEventListener("keydown",p,!0),H(async()=>{const{ModelViewer:S}=await import("./ModelViewer-_yhAYvNy.js");return{ModelViewer:S}},__vite__mapDeps([42,41]),import.meta.url).then(({ModelViewer:S})=>S.end())},p=S=>{S.key==="Escape"&&(S.stopPropagation(),u())},f=i?.current(),m="\0address",g=S=>S===m&&f?Promise.resolve({url:f.url}):t(S),v=S=>{if(u(),s){S!==m&&s(S);return}S===m||S===e.value||(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const w=new Map,y=S=>{const E=document.createElement("button");E.type="button",E.className="model-card",E.dataset.value=S.value,E.setAttribute("aria-pressed",String(!s&&(S.value===m||S.value===e.value&&!f)));const A=document.createElement("div");A.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=S.textContent,E.append(A,T),S.title){const C=document.createElement("span");C.className="model-credit",C.textContent=S.title,E.append(C)}g(S.value).then(C=>Xp.pictureOf(C)).then(C=>{if(!C)return;const P=new Image;P.src=C,P.alt="",A.append(P)});let D,k=!1;const O=()=>{k&&!(D&&!D.active)||(k=!0,Promise.all([g(S.value),H(()=>import("./ModelViewer-_yhAYvNy.js"),__vite__mapDeps([42,41]),import.meta.url)]).then(([C,{ModelViewer:P}])=>{!C||!k||(D=P.show(A,C))}).catch(()=>{}))},N=()=>{k=!1,D?.stop(),D=void 0};return w.set(E,O),E.addEventListener("pointerenter",O),E.addEventListener("focus",O),E.addEventListener("pointerleave",()=>{document.activeElement!==E&&N()}),E.addEventListener("blur",N),E.addEventListener("click",C=>{if(D?.consumeDrag()){C.preventDefault();return}v(S.value)}),E},M=()=>(b=document.createElement("div"),b.className="model-picker-grid",d.append(b),b);if(f){const S=new Option(f.title||f.url,m);S.title=[f.author,f.license].filter(Boolean).join(" — "),M().append(y(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const E=document.createElement("h3");E.textContent=S.label,d.append(E);const A=M();for(const T of Array.from(S.children))A.append(y(T));b=void 0}else S instanceof HTMLOptionElement&&(b??M()).append(y(S));i&&this.addAddressForm(h,c,a,d,i,n,u),c.addEventListener("click",u),r.addEventListener("click",S=>{S.target===r&&u()}),document.addEventListener("keydown",p,!0),this.root.append(r);const x=a.querySelector('.model-card[aria-pressed="true"]');(x??c).focus(),x&&w.get(x)?.()}addAddressForm(e,t,i,s,n,r,a){const o=document.createElement("button");o.type="button",o.className="model-picker-add",o.textContent="+",o.title=r.address,o.setAttribute("aria-label",r.address),o.setAttribute("aria-expanded","false"),e.insertBefore(o,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(w,y,M="")=>{const x=document.createElement("label"),S=document.createElement("span");S.textContent=w;const E=document.createElement("input");return E.type=y,E.placeholder=M,x.append(S,E),c.append(x),E},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),m=h(r.addressSource,"url","https://…"),g=document.createElement("p");g.textContent=r.addressIncomplete;const v=document.createElement("button");v.type="submit",v.className="model-picker-use",v.textContent=r.addressUse,c.append(g,v),i.insertBefore(c,s);const b=()=>{v.disabled=d.value.trim()==="",g.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const w of[d,u,p,f,m])w.addEventListener("input",b);o.addEventListener("click",()=>{const w=c.hidden;if(c.hidden=!w,o.setAttribute("aria-expanded",String(w)),!w)return;const y=n.current();d.value=y?.url??"",u.value=y?.title??"",p.value=y?.author??"",f.value=y?.license??"",m.value=y?.source??"",b(),d.focus()}),c.addEventListener("submit",w=>{w.preventDefault(),d.value.trim()!==""&&(n.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:m.value.trim()}),a())}),b()}}class WM{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=WM.SPAN_DEG;try{const n=(await this.provider.getElevationGrid({south:e-i,north:e+i,west:t-i,east:t+i},{width:2,height:2})).heights[0];return Number.isFinite(n)?n:void 0}catch{return}}}class RB{formatters=new Map;available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const i=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),s=this.zoneOffsetHours(e,new Date(i));if(s!==void 0)return this.zoneOffsetHours(e,new Date(i-s*36e5))??s}zoneOffsetHours(e,t){let i=this.formatters.get(e);if(i===void 0){try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"})}catch{i=null}this.formatters.set(e,i)}if(i===null)return;const s=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(s);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[3])/60):0}zonesAt(e,t){const i=t?.year!==void 0?t:{year:new Date().getFullYear(),month:1,day:1,hour:12};return this.available().filter(s=>this.offsetHoursAt(s,i)===e)}}class gr{static STEP_MS=100;static plan(e){const t=gr.routeOf(e),i=Qe.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const a=new Set,o=(u,p,f,m)=>{if(Math.abs(u.radiusM-m)>=m*.1)return!1;const{x:g,z:v}=lt(p,f,u.lat,u.lng);return Math.hypot(g,v)<Qe.rebuildDistanceFor(m)};for(let u=0;;u=Math.min(s,u+gr.STEP_MS)){const p=et(e,u);if(p?.lat!==void 0&&p.lng!==void 0){const f=Qe.groundRadiusFor(p.elevationM??0),m=Qe.patchRadiusFor(f,p.elevationM??0),g=Math.max(m,i);(!r||!o(r,p.lat,p.lng,g))&&(r=n.find(v=>o(v,p.lat,p.lng,g)),r||n.push(r={lat:p.lat,lng:p.lng,radiusM:g})),g<f&&a.add(r)}if(u>=s)break}const c=e.weatherTrack.allKeyframes.map(u=>u.weather.visibilityKm).filter(u=>u!==void 0),h=Qe.farRingRadiusFor(c.length>0?Math.max(...c):void 0);for(const u of a)n.push({lat:u.lat,lng:u.lng,radiusM:h,far:!0});if(h>Qe.FAR_RING_RADIUS_M)for(const u of[...n])!u.far&&!a.has(u)&&u.radiusM<h&&n.push({lat:u.lat,lng:u.lng,radiusM:h,far:!0});const d=Nf.map(u=>sa.of(u)).filter(u=>u.reachM&&sa.eventsOf(e.skyEvents,u).length>0);if(d.length>0){const u=p=>Math.max(...d.map(f=>f.reachM(sa.eventsOf(e.skyEvents,f),p)));for(const p of[...n])p.far||a.has(p)||n.some(f=>f.far&&f.lat===p.lat&&f.lng===p.lng)||Qe.needsFarRing(p.radiusM,0,u(p))&&n.push({lat:p.lat,lng:p.lng,radiusM:h,far:!0})}return n}static routeOf(e){const t=e.observerTrack.allKeyframes.flatMap(i=>i.pose.lat!==void 0&&i.pose.lng!==void 0?[{lat:i.pose.lat,lng:i.pose.lng}]:[]);return t.length>=2?t:void 0}static async freeze(e,t,i,s,n){const r=new Date().toISOString().slice(0,10),a=o=>n?.(o,i.length);switch(e){case"relief":{const o=gr.routeOf(t),c=[];for(const[u,p]of i.entries()){try{const f=await s.elevation.getElevationGrid(xr.boundsOf(p),{width:rw,height:rw},{route:o});c.push({...p,grid:f})}catch(f){console.warn("Relief not snapshots for a patch:",f)}a(u+1)}if(c.length===0)return;const h=s.elevationCredit;return{bytes:await Hf.encode({takenOn:r,attribution:h,patches:c}),attribution:h,takenOn:r,answered:c.length,patches:i.length}}case"imagery":{const o=new zA,c=qi(Eh,s.imagery),h=c.create(o.fetch);let d=0;for(const[f,m]of i.entries()){try{await h.getImageryTexture(xr.boundsOf(m),{width:Pp,height:Pp}),d++}catch(g){console.warn("Imagery not snapshots for a patch:",g)}a(f+1)}if(o.tiles.size===0)return;const u=h.attribution;return{bytes:await Hg.encode({takenOn:r,source:c.id,attribution:u,patches:[...i],tiles:o.tiles}),attribution:u,takenOn:r,answered:d,patches:i.length}}case"roads":return gr.vector(s.roads,i,r,a,(o,c)=>o.getRoads(c),o=>o.contemporary);case"water":return gr.vector(s.water,i,r,a,(o,c)=>o.getWater(c));case"railways":return gr.vector(s.railways,i,r,a,(o,c)=>o.getRailways(c),o=>o.contemporary)}}static mapGround(e){const t=wh.of(e);return t&&bi.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=gr.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new zA,r=qi(Eh,t),a=r.create(n.fetch),o=bi.IMAGERY_PX;try{await a.getImageryTexture(i,{width:o,height:o})}catch(d){console.warn("Map imagery not snapshots:",d);return}const c=a.attribution;return{bytes:await Hg.encode({takenOn:s,source:r.id,attribution:c,patches:[],map:{bounds:i,pixels:o},tiles:n.tiles}),attribution:c,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const a=[];for(const[h,d]of t.entries()){if(d.radiusM<=Qe.ROADS_MAX_RADIUS_M)try{a.push({...d,items:await n(e,xr.boundsOf(d))})}catch(u){console.warn("Not snapshots for a patch:",u)}s(h+1)}if(a.length===0)return;const o={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:a};return{bytes:new TextEncoder().encode(JSON.stringify(o)),attribution:e.attribution,takenOn:i,answered:a.length,patches:t.length}}}class ms{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.replace(this.shown,i.detail)),this.root.querySelector("#snapshot-refresh").addEventListener("click",()=>void this.refresh(this.shown)),this.root.querySelector("#annex-export").addEventListener("click",()=>void this.exportAnnex(this.shown))}messages;busy=!1;shown="relief";editor;editorFor;editTimer;get sourceInput(){return this.root.querySelector("#annex-source")}get editorHost(){return this.root.querySelector("#annex-editor")}get note(){return this.root.querySelector("#snapshot-note")}localize(e){this.messages=e,this.root.title=e.snapshotHint;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-annex-source",e.annexSource),t("snapshot-refresh",e.snapshotRefresh),t("annex-export",e.export),this.sourceInput.messages=e,this.render()}itemLabel(e){return this.groupName(e)}where(e){const t=this.annex(e);return this.isLive(e)?this.messages.snapshotLiveState:!t||t.refresh?this.messages.snapshotPending:ms.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&ms.isInline(t.src)}annex(e){const t=this.host.sighting().snapshots?.[e];return t?.src!==void 0?t:void 0}isLive(e){return us.isLive(this.host.sighting().snapshots,e)}setLive(e,t){if(this.isLive(e)===t)return;const i={...this.host.sighting().snapshots??{}};if(i.live){delete i.live;for(const n of us.NAMES)i[n]={...i[n]??{},live:!0}}const s={...i[e]??{}};t?s.live=!0:delete s.live,i[e]=Object.keys(s).length>0?s:void 0,this.setSnapshots(i)}show(e){this.shown=e,this.render()}render(){if(!this.messages)return;const e=this.shown,t=this.isLive(e),i=this.annex(e),s=this.root.querySelector("#snapshot-state");s.textContent=t?this.messages.snapshotLiveState:i&&!i.refresh?[this.messages.snapshotTakenOn.replaceAll("{date}",i.takenOn??"?"),i.attribution].filter(Boolean).join(" · "):this.messages.snapshotPending;const n=this.root.querySelector("#snapshot-refresh");n.disabled=this.busy||t;const r=i!==void 0&&!i.refresh&&!t,a=r&&ms.isInline(i.src);this.sourceInput.url=r?a?this.host.masterUrl():this.address(i.src):"",r||(this.sourceInput.mode="file"),this.sourceInput.disabled=this.busy||t,this.root.querySelector("#annex-export").disabled=i===void 0||this.busy,this.renderEditor(r&&!a?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!ms.isZip(t)?await this.textOf(e).catch(()=>{}):void 0;if(t!==this.shown||(this.editorHost.hidden=i===void 0,i===void 0))return;const s=`${t}|${e.src}`;if(this.editor&&this.editorFor===s)return;if(this.editorFor=s,this.editor){this.editor.replaceText(i,!1);return}const{SightingFileEditor:n}=await H(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-0VZmtiOX.js");return{SightingFileEditor:r}},__vite__mapDeps([43,20,44]),import.meta.url);if(t!==this.shown||!this.editorHost.isConnected){this.editorFor=void 0;return}this.editor??=new n(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const s={...this.host.sighting().snapshots??{}};let n;try{n=await this.bytesAt(t.url)}catch{n=void 0}if(n!==void 0)try{s[e]={src:t.url,...await ms.describe(e,n)}}catch{Gt.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){Gt.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}Lt.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}Gt.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await H(async()=>{const{InputFileElement:s}=await Promise.resolve().then(()=>u_);return{InputFileElement:s}},void 0,import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const s={...this.host.sighting().snapshots??{}},n=this.annex(e);let r;try{r=await ms.describe(e,t)}catch{Gt.show(this.note,this.messages.annexUnreadable,"warning");return}const a=n!==void 0&&ms.isInline(n.src),o=a?ms.dataUrl(e,t):n?.src??us.annexName(this.host.base(),e);a||Lt.hold(this.address(o),t),s[e]={...s[e]?.live?{live:!0}:{},src:o,...r},Gt.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${o}`),this.setSnapshots(s)}async setStorage(e,t){const i={...this.host.sighting().snapshots??{}},s=this.annex(e);if(!s||ms.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=ms.dataUrl(e,n):(r=us.annexName(this.host.base(),e),Lt.hold(this.address(r),n)),i[e]={...s,src:r},this.editorFor=`${e}|${r}`,this.setSnapshots(i)}async exportAnnex(e){const t=this.annex(e);if(!t)return;const i=await this.bytesOf(t),s=ms.isInline(t.src)?us.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:ms.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(ms.isZip(e)){const{unzipSync:s}=await H(async()=>{const{unzipSync:n}=await import("./browser-CltifEM0.js");return{unzipSync:n}},[],import.meta.url);i=JSON.parse(new TextDecoder().decode(s(t)["index.json"]))}else i=JSON.parse(new TextDecoder().decode(t));if(typeof i!="object"||i===null)throw new Error("Not an annex");return{takenOn:typeof i.takenOn=="string"?i.takenOn:void 0,attribution:typeof i.attribution=="string"?i.attribution:void 0}}async bytesAt(e){return Lt.bytes(this.address(e))}static isInline(e){return e.startsWith("data:")}static isZip(e){return e==="relief"||e==="imagery"||e==="map"}static dataUrl(e,t){let i="";for(let s=0;s<t.length;s+=32768)i+=String.fromCharCode(...t.subarray(s,s+32768));return`data:${ms.isZip(e)?"application/zip":"application/json"};base64,${btoa(i)}`}async refresh(e){if(this.busy)return;const t={...this.host.sighting().snapshots??{}};if(e==="upperAir"){const i=t.upperAir;i&&(t.upperAir={...i,refresh:!0}),this.setSnapshots(t);return}this.busy=!0,this.render();try{const i=t[e]?.src,s=(i&&!ms.isInline(i)?ms.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,gr.plan(this.host.sighting()),this.host.sources(),s))?Gt.show(this.note,void 0):Gt.show(this.note,this.messages.snapshotFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setSnapshots(t)}hasWork(){const e=this.host.sighting();return us.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||gr.plan(e).length>0:!0}async prepare(e){const t=this.host.sighting(),i={...t.snapshots??{}},s=new Map;this.busy=!0,this.render();try{const n=d=>us.isLive(i,d),r=d=>i[d]?.src!==void 0?i[d]:void 0;for(const d of us.NAMES)!i.live&&i[d]?.live&&(i[d]={live:!0});const a=gr.plan(t);let o;for(const d of us.TERRAIN){if(n(d))continue;const u=r(d);if(a.length>0&&(!u||u.refresh||!await this.fits(d,u,a))&&await this.take(d,i,a,o??=this.host.sources(),e)){await this.keep(r(d),s);continue}u?.refresh&&(i[d]={...u,refresh:void 0}),r(d)&&await this.keep(r(d),s)}if(!n("map")){const d=r("map");gr.mapGround(t)!==void 0&&(!d||d.refresh||!await this.fitsMap(d))&&await this.takeMap(i,o??=this.host.sources(),e)?await this.keep(r("map"),s):d&&(d.refresh&&(i.map={...d,refresh:void 0}),await this.keep(r("map"),s))}const c=this.host.upperAirHeard(),h=r("upperAir");if(!n("upperAir")&&c&&(!h||h.refresh)){const d=new Date().toISOString().slice(0,10),u={version:1,takenOn:d,attribution:c.answer.source.name,answers:[c]},p=new TextEncoder().encode(JSON.stringify(u)),f=this.place("upperAir",h?.src,e,p);i.upperAir={src:f,takenOn:d,attribution:c.answer.source.name},ms.isInline(f)||s.set(f,p)}else h&&!n("upperAir")&&(h.refresh&&(i.upperAir={...h,refresh:void 0}),await this.keep(r("upperAir"),s))}finally{this.busy=!1}return this.setSnapshots(i),s}async take(e,t,i,s,n){const r=this.groupName(e),a=await gr.freeze(e,this.host.sighting(),i,s,(o,c)=>Gt.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(o)).replaceAll("{of}",String(c))));return Gt.show(this.note,void 0),a?(t[e]={src:this.place(e,t[e]?.src,n,a.bytes),takenOn:a.takenOn,attribution:a.attribution},!0):!1}async takeMap(e,t,i){Gt.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await gr.freezeMap(this.host.sighting(),t.imagery);return Gt.show(this.note,void 0),s?(e.map={src:this.place("map",e.map?.src,i,s.bytes),takenOn:s.takenOn,attribution:s.attribution},!0):!1}async fitsMap(e){const t=gr.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await Lt.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&xr.sameBounds(i.map.bounds,t)}catch{return!1}}async fits(e,t,i){try{const s=this.address(t.src),n=t.src.endsWith(".zip")?JSON.parse(new TextDecoder().decode((await Lt.zip(s))["index.json"])).patches:(await Lt.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(a=>a.radiusM<=Qe.ROADS_MAX_RADIUS_M);return xr.samePatches(n.map(({lat:a,lng:o,radiusM:c})=>({lat:a,lng:o,radiusM:c})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&ms.isInline(t))return ms.dataUrl(e,s);const n=t??us.annexName(i,e);return Lt.hold(this.address(n),s),n}async keep(e,t){if(!ms.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{Gt.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return Lt.bytes(this.address(e.src))}address(e){return Lt.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of us.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=us.isEmpty(e)?void 0:e,this.render(),this.host.changed()}destroy(){clearTimeout(this.editTimer),this.editor?.destroy(),this.editor=void 0,this.editorFor=void 0}static baseOf(e){return e?.match(/^(.*)\.[a-z-]+\.(zip|json)$/)?.[1]}static size(e){return e<1e6?`${Math.max(1,Math.round(e/1e3))} kB`:`${(e/1e6).toFixed(1)} MB`}groupName(e){return{relief:this.messages.snapshotRelief,imagery:this.messages.snapshotImagery,roads:this.messages.snapshotRoads,water:this.messages.snapshotWater,railways:this.messages.snapshotRailways,upperAir:this.messages.snapshotUpperAir,map:this.messages.snapshotMap}[e]}}class qg{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,Gt.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().snapshots?.[e]?.src}itemLabel(e){const t=this.messages;return t?{weather:t.fileItemWeather,place:t.fileItemPlace,lightPollution:t.fileItemLightPollution,decor:t.fileItemDecor}[e]:""}where(e){return this.srcOf(e)??this.messages?.annexStorageInline??""}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[Jt.KEYS[e][0]]}render(){if(!this.messages)return;const e=this.srcOf(this.shown);this.sourceInput.url=e?this.resolve(e):this.host.masterUrl(),this.root.querySelector("#section-annex-state").textContent=this.state(this.shown)}state(e){const t=this.host.sighting();switch(e){case"weather":return t.weatherSource?.name??this.messages.weatherStatedByObserver;case"place":return t.event.place?.[0]?.name??"";case"lightPollution":return new Bs(zs.preferencesFor(this.root)).read(t.provenance.at("lightPollution")?.rationale)??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().snapshots??{}};if(t===(i[e]?.src===void 0))return;const{src:s,...n}=i[e]??{};i[e]=t?n:{...n,src:Jt.annexName(this.host.base(),e)},this.write(e,i)}annex(e){const t=this.srcOf(e);return t===void 0?void 0:{src:t,bytes:this.bytesOf(e)}}bytesOf(e){const t=Lf(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:An.CURRENT.sighting,takenOn:i,attribution:s,...Jt.taken(e,t)};return new TextEncoder().encode(JSON.stringify(n))}resolve(e){return new URL(e,this.host.documentUrl()??location.href).href}exportAnnex(e){const t=this.srcOf(e)??Jt.annexName(this.host.base(),e);this.host.download(new Blob([this.bytesOf(e)],{type:"application/json"}),decodeURIComponent(t.split("/").pop()??t))}async take(e,t){if(t.url&&this.resolve(t.url)===this.resolve(this.host.masterUrl())){this.setStorage(e,!0);return}if(t.url)try{await fetch(this.resolve(t.url),{method:"HEAD"}).then(o=>{if(!o.ok)throw new Error(String(o.status))})}catch{const o={...this.host.sighting().snapshots??{}};o[e]={...o[e]??{},src:t.url},Gt.show(this.note,void 0),this.write(e,o);return}let i;try{const{InputFileElement:o}=await H(async()=>{const{InputFileElement:h}=await Promise.resolve().then(()=>u_);return{InputFileElement:h}},void 0,import.meta.url),c=await o.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=An.recording(JSON.parse(new TextDecoder().decode(c))),typeof i!="object"||i===null||Jt.KEYS[e].every(h=>i[h]===void 0))throw new Error("Not this section")}catch{Gt.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...Lf(s)};if(e==="decor")Jt.put(e,n,"timeline"in i?Jt.taken(e,i):i);else for(const o of Jt.KEYS[e])n[o]=i[o];const r=Jf(n);qg.copy(e,r,s);const a={...s.snapshots??{}};t.url?a[e]={...a[e]??{},src:t.url}:a[e]=a[e]??{},Gt.show(this.note,void 0),this.write(e,a)}write(e,t){this.host.sighting().snapshots=us.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const s of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(s.t,s.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const s of Jt.KEYS[e]){i.provenance.clear(s);for(const n of t.provenance.paths())(n===s||n.startsWith(`${s}.`))&&i.provenance.set(n,t.provenance.at(n))}}}class CB{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const i=new URL(this.endpoint);i.searchParams.set("latitude",String(e)),i.searchParams.set("longitude",String(t)),i.searchParams.set("timezone","auto"),i.searchParams.set("forecast_days","1");try{const s=await fetch(i.toString());if(!s.ok)return;const n=await s.json();return n.timezone&&n.timezone!=="GMT"?n.timezone:void 0}catch{return}}}const OB=Xe.point("timeZone").provide(Xe.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new CB}]),LB=["appearance","movement","incongruity","detection","close","beings","traces"];class _y{static OCCUPATIONS={student:!0,worker:!0,farmer:!0,homemaker:!0,merchant:!0,business:!0,employee:!0,artist:!0,technician:!0,police:!0,pilot:!0,military:!0};static RELATIONS=["friends","family","professional","none"];static ACTIVITIES=["leisure","travelling","cultural","working"]}class Es{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=Es.select("observerOccupationKind");graduate=Es.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=Es.select("observersRelation");activity=Es.select("observerActivity");factors=new Map(LB.map(e=>[e,Es.select(`strangeness-${e}`)]));labels=new Map;unit=document.createTextNode(" min");strangenessTitle=document.createElement("span");strangenessIntro=Object.assign(document.createElement("p"),{className:"section-intro"});wording;constructor(e,t,i,s){Qs.register(),e.append(this.label(this.occupationKind,h=>[h.occupationKind,h.occupationKindHint]),this.label(this.graduate,h=>[h.graduate]));const n=this.label(this.enquiryMinutes,h=>[h.enquiryMinutes,h.enquiryMinutesHint]);n.append(this.unit);const r=t.querySelector("#accountSource")?.closest("label");r?r.after(n):t.append(n),t.append(this.label(this.relation,h=>[h.relation]),this.label(this.activity,h=>[h.activity]));const a=Object.assign(document.createElement("h3"),{className:"section-title"});a.append(this.strangenessTitle),i.append(a,this.strangenessIntro,...[...this.factors].map(([h,d])=>this.label(d,u=>[u.factors[h],u.factorHints[h]])));const o=[["yes","yes"],["no","no"]],c=h=>h.map(d=>[d,d]);Es.choices(this.occupationKind,"",c(Object.keys(_y.OCCUPATIONS))),Es.choices(this.graduate,"",o),Es.choices(this.relation,"",c(_y.RELATIONS)),Es.choices(this.activity,"",c(_y.ACTIVITIES));for(const h of this.factors.values())Es.choices(h,"",o);for(const h of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])h.addEventListener("change",s)}set messages(e){this.wording=e;for(const t of this.labels.values())t();this.unit.textContent=` ${e.minutes}`,this.strangenessTitle.textContent=e.strangenessSection,this.strangenessIntro.textContent=e.strangenessIntro,Es.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),Es.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),Es.choices(this.relation,e.unknown,Object.entries(e.relations)),Es.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)Es.choices(i,Es.READ_FROM_RECORDING.includes(t)?e.fromRecording:e.unknown,[["yes",e.yes],["no",e.no]])}show(e){this.occupationKind.value=e?.observerOccupationKind??"",this.graduate.value=Es.yesNo(e?.observerGraduate),this.enquiryMinutes.value=e?.enquiryMinutes?.toString()??"",this.relation.value=e?.observersRelation??"",this.activity.value=e?.activity??"";for(const[t,i]of this.factors)i.value=Es.yesNo(e?.strangeness?.[t])}values(){const e=this.enquiryMinutes.value.trim()===""?void 0:Number(this.enquiryMinutes.value),t={};for(const[i,s]of this.factors){const n=Es.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:Es.boolean(this.graduate.value),enquiryMinutes:e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0,observersRelation:this.relation.value||void 0,activity:this.activity.value||void 0,strangeness:Object.keys(t).length>0?t:void 0}}label(e,t){const i=document.createElement("label"),s=document.createElement("span");return i.append(s," ",e),this.labels.set(s,()=>{if(!this.wording)return;const[n,r]=t(this.wording);Qs.say(s,n,r)}),i}static select(e){return Object.assign(document.createElement("select"),{id:e})}static choices(e,t,i){const s=e.value;e.replaceChildren(new Option(t,""),...i.map(([n,r])=>new Option(r,n))),e.value=s}static yesNo(e){return e===void 0?"":e?"yes":"no"}static boolean(e){return e===""?void 0:e==="yes"}}const _0=new Set;yv();l_();qd.register();const Ed={width:48,height:28},PB=2500,D0=40,k0=10,NB=30,FB=10,uT=600,pT=900,Sd=2e-4,UB=900,BB=-1.46,zB=3,Dy=.2,HB=.5,GB=3,VB=.01,WB=1.6,ky=2e3,$B=250,fT=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),KB=1,XB=5,YB=10,Bc=4,mp="ufo-1",qB={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function jB(l){return l.kind==="oval"?"oval":"polygon"}const ZB=-6,JB=21;class ge extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=OB[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new RB;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;exportKmlButton;exportGeoJsonButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;saidInterviews;candidatesView;sectionFolds;snapshotsPanel;sectionFilePanel;eventsPanel;aroundPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;aircraftStatus=Object.assign(document.createElement("span"),{className:"source-status"});aircraftFlights;aircraftFlightsShownAt=0;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=TB();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lensGlassSelect;isoInput;filmStockSelect;meteringSelect;lensDropsInput;lensCondensationInput;lensDirtInput;lensShelteredInput;skySourcesInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;evaluationFields;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;skyParts=new Map;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileAsk;identityAsk;fileSyncTimer;fileApplyTimer;historySnapshot;historyTimer;historyAnswering=!1;undoButton;redoButton;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new fp(SB());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;static FIELDS_OF_PATH={time:["obs-time","obs-time-native"],"place.locations.0.lat":["lat"],"place.locations.0.lng":["lng"]};markBeyondKnown(e){for(const{field:t,title:i}of this.markedBeyondKnown)t.removeAttribute("aria-invalid"),i===null?t.removeAttribute("title"):t.setAttribute("title",i);this.markedBeyondKnown=[];for(const{path:t,why:i}of e)for(const s of ge.FIELDS_OF_PATH[t]??[]){const n=this.shadow.getElementById(s);n&&(this.markedBeyondKnown.push({field:n,title:n.getAttribute("title")}),n.setAttribute("aria-invalid","true"),n.setAttribute("title",i))}}setReadingBounds(e){const t=this.shadow.querySelector('rr0-date-input[name="obs-time"]'),i=e.time?Ur.boundsOf(e.time):void 0;t?.setBounds(i?{...i,...e.hour?{adjust:e.hour}:{}}:void 0);for(const[s,n]of[["lat",e.lat],["lng",e.lng]]){const r=this.shadow.getElementById(s);if(r&&(this.numberBounds.set(r,n),r.min=n?String(n[0]):"",r.max=n?String(n[1]):"",!this.boundedFields.has(r))){this.boundedFields.add(r);const a=()=>{const o=this.numberBounds.get(r),c=Number(r.value);if(!o||r.value===""||!Number.isFinite(c))return;const h=Math.min(Math.max(c,o[0]),o[1]);h!==c&&(r.value=String(h))};r.addEventListener("change",a,{capture:!0})}}}numberBounds=new WeakMap;boundedFields=new WeakSet;markedBeyondKnown=[];accountShapeIds;labelNarrativeSource;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;weatherProviderSelect;weatherFileLink;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;observerList;observerShown="principal";static CLICK_SLOP_PX=5;static OBSERVER_PRINCIPAL="principal";surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=new zp;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=ui.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...qB};currentSourceId=mp;selectedSourceIds=new Set([mp]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSourceInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceVideoFromInput;referenceVideoToInput;referenceVideoRateInput;referenceRemoveKeyButton;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;referenceFailure;addReferenceButton;referenceAddMenu;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;findGhostsButton;searchingGhosts=!1;ghostsStatus;ghostFinding;ghostsShown=!0;ghostsShownButton;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;traceImportInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;addTraceButton;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$;pictureRegistration;pictureRegistrationLoading;referenceFields;labelReferenceGroup;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),(e.ctrlKey||e.metaKey)&&!e.altKey&&["z","y"].includes(e.key.toLowerCase())){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;e.preventDefault(),e.key.toLowerCase()==="y"||e.shiftKey?this.redo():this.undo();return}if(fT.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;fT.has(e.key)?this.selectedMembers().length===0&&t===this?this.walkOrTurn(e):this.moveOrResizeSelectedShapes(e):this.canvasMode()==="decor"?this.deleteDecor():this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0,t=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedBodyId:void 0;this.endDrag(),t!==void 0&&this.showBody(t),e!==void 0&&(this.selectDecor(e),this.revealDecorPanel(),this.flash(this.shadow.querySelector("#decor-item label, #decor-item .field")))};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${y8}</style>${b8}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const c of this.shadow.querySelectorAll(wg))c.build();for(const c of this.shadow.querySelectorAll(Xg))c.build();for(const c of this.shadow.querySelectorAll(Vf))c.build();for(const c of this.shadow.querySelectorAll(xg))c.build();this.sceneElement=document.createElement(Gf),this.sceneElement.addEventListener("observermapchange",c=>{this.ufoElement.sighting.observerMap=c.detail.open,this.dispatchEvent(new CustomEvent("sightingchange"))}),this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.titleShown=!1,this.sceneElement.ownCredits=!1,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",c=>{const{lat:h,lng:d}=c.detail;this.latInput.value=String(Number(h.toFixed(6))),this.lngInput.value=String(Number(d.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.shapeRotationInput=this.shadow.getElementById("shapeRotation"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.timeZoneWarning=this.shadow.getElementById("time-zone-warning"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextDuplicateButton=this.shadow.getElementById("context-duplicate"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new kp(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const c of[this.timeStartLabel,this.timeEndLabel])c.addEventListener("click",()=>this.switchTimeDisplay()),c.addEventListener("keydown",h=>{h.key!=="Enter"&&h.key!==" "||(h.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(Xg),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.exportKmlButton=this.shadow.getElementById("export-kml"),this.exportGeoJsonButton=this.shadow.getElementById("export-geojson"),this.saveButton=this.shadow.getElementById("save"),this.shareButton=this.shadow.getElementById("share"),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.sectionFolds=new fs(this.shadow);const t=this;this.witnessErrorView=new dI({get sighting(){return t.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:c=>{const h=this.ufoElement.sighting,{conditions:d,...u}=h.account??{},p={...u,...c?{conditions:c}:{}};h.account=Object.values(p).some(f=>f!==void 0)?p:void 0},recordingJson:()=>this.sightingData,valueSources:()=>this.valueSources(),lawsChanged:()=>{this.sceneElement.confrontationTolerance=ri.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new Qf(this.shadow.getElementById("timeline-tracks"),c=>this.goToMark(c),this.messages),this.tracksToggle=this.shadow.getElementById("toggle-tracks"),this.tracksToggle.addEventListener("click",()=>this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")!=="true")),this.resizeScene(this.shadow.getElementById("scene-resize")),this.shadow.querySelector(".scene-card").addEventListener("pointerdown",c=>{c.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new pI(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",c=>{const h=c.target.id;ge.SCENE_LINKED.includes(h)&&this.setActiveSceneField(h)}),this.shadow.addEventListener("focusout",c=>{const h=c.relatedTarget;(!h||!ge.SCENE_LINKED.includes(h.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.filmStockSelect=this.shadow.getElementById("filmStock"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),this.skySourcesInput=this.shadow.getElementById("sky-sources"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.evaluationFields=new Es(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${xg}[name="observer"]`),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverBirth=this.shadow.getElementById("label-observer-birth"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.wholeKeyframesInput=this.shadow.getElementById("whole-keyframes");try{this.wholeKeyframesInput.checked=localStorage.getItem(ge.WHOLE_KEYFRAMES_STORAGE)==="true"}catch{}this.wholeKeyframesInput.addEventListener("change",()=>this.setKeyframesWritten()),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.snapshotsPanel=new ms(this.shadow.getElementById("snapshot-data"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,sources:()=>this.snapshotSources(),upperAirHeard:()=>this.sceneElement.upperAirHeard,changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleFileSync(),this.refreshFileItems()},base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(c,h)=>this.download(c,h)}),this.sectionFilePanel=new qg(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(c,h)=>this.download(c,h),changed:c=>{if(this.touch(),this.ufoElement.refresh(),c==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),c==="place"&&this.syncPlaceNameField(),c==="lightPollution"){const h=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=h===void 0?"":String(h),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const i={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:c=>this.goToMark(c),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const c=this.ufoElement.sighting.timeline;return c.sourceIds.includes(this.currentSourceId)?c.topOf(this.currentSourceId):void 0},shapesLabel:c=>this.shapesLabel(c),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:c=>this.naming.point(c),lookedAt:()=>{const c=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return c?.headingDeg===void 0||c.pitchDeg===void 0?void 0:{azimuthDeg:c.headingDeg,altitudeDeg:c.pitchDeg}},bodyLabel:c=>{const h=this.ufoElement.sighting.interpretation?.bodies.find(d=>d.id===c);return this.said.read(h?.title)??c},valueSources:()=>this.valueSources()};this.eventsPanel=new To(this.shadow.getElementById("events-section"),i,void 0),this.phenomenonEventsPanel=new To(this.shadow.getElementById("phenomenon-events-section"),i,void 0,"phenomenon"),this.bodiesEventsPanel=new To(this.shadow.getElementById("bodies-events-section"),i,void 0,"bodies"),this.aroundPanel=new i8(this.shadow.getElementById("around-section"),{sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.scheduleFileSync()},valueSources:()=>this.valueSources()}),this.samplingRateInput.addEventListener("change",()=>{const c=Number(this.samplingRateInput.value);i.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(c)&&c>0?c:void 0,ft.refresh(this.ufoElement.sighting),i.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.snapshotsPanel.localize(this.messages),this.sectionFilePanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",c=>{c.preventDefault(),this.keepReadingWeather()}),this.shadow.getElementById("file-ask-stop").addEventListener("click",()=>this.stopReadingWeather()),this.shadow.getElementById("file-ask-keep").addEventListener("click",()=>this.keepReadingWeather()),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelRareIce=this.shadow.getElementById("label-rare-ice"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.aircraftFlights=new YU(this.shadow.getElementById("aircraft-flights"),c=>this.aimAtFlight(c),c=>this.naming.point(c)),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.weatherProviderSelect=this.shadow.getElementById("weatherSource"),this.weatherFileLink=this.shadow.getElementById("weather-file-link"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorList=new Ln({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:c=>`option-decor-${c}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:c=>this.selectDecor(c),onAdd:c=>this.addDecor(c),onRemove:()=>this.deleteDecor()}),this.decorList.setKinds([{value:"building",label:"Building"},{value:"tree",label:"Tree"},{value:"shrub",label:"Shrub"},{value:"bridge",label:"Bridge"},{value:"wire",label:"Overhead line"},{value:"crop",label:"Crop row"},{value:"terrace",label:"Terrace (restanque)"},{value:"mound",label:"Stone heap"},{value:"wall",label:"Dry-stone wall"},{value:"streetlight",label:"Streetlight"},{value:"trafficlight",label:"Traffic light"},{value:"peak",label:"Peak"},{value:"crossing",label:"Pedestrian crossing"},{value:"roadsign",label:"Road sign"},{value:"vehicle",label:"Vehicle"},{value:"aircraft",label:"Aircraft"},{value:"entity",label:"Being"},{value:"observer",label:"Other observer",hidden:!0}]),this.decorList.setLabels({list:"Environment",remove:"Delete decor",add:"Add",empty:"No decor",actions:{"look-at-decor":"Look at it"}}),this.observerList=new Ln({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:c=>this.selectObserver(c),onAdd:()=>this.addDecor("observer"),onRemove:()=>this.deleteDecor()}),this.observerList.setLabels({list:"Observer",remove:"Delete observer",add:"Add observer",actions:{"look-at-observer":"Look at it"}}),this.sceneryStatus=this.shadow.getElementById("scenery-status"),this.sceneryWarning=this.shadow.getElementById("scenery-warning"),this.scenerySource=this.shadow.getElementById("scenery-source"),this.labelScenerySource=this.shadow.getElementById("label-scenery-source"),this.sceneryRadius=this.shadow.getElementById("scenery-radius"),this.labelSceneryRadius=this.shadow.getElementById("label-scenery-radius"),this.sceneryRadius.value=this.readSceneryRadius(),this.surroundings=new kn(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:c=>this.setPlantedDecor(c),kindName:c=>this.decorList.kindLabel(c),cite:c=>this.citeSource(c),busy:(c,h)=>this.sceneElement.setBusy(c,h),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(c=>({lat:c.pose.lat,lng:c.pose.lng})).filter(c=>typeof c.lat=="number"&&typeof c.lng=="number")},this.messages,async(c,h)=>this.surroundingsProvider?this.surroundingsProvider.covers(c,h)?this.surroundingsProvider:void 0:(await H(async()=>{const{SurroundingsSources:d}=await import("./surroundingsSources-z7680fTA.js");return{SurroundingsSources:d}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,c,h),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const c=this.scenerySource.value===ge.FILE_SOURCE;if(this.setDecorFromFile(c),c){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===ge.NO_SCENERY){this.surroundings.withdraw();return}const h=this.plantingCentre();h&&this.surroundings.survey(h.lat,h.lng)}),this.sceneryRadius.addEventListener("input",()=>{const c=Number(this.sceneryRadius.value);if(!Number.isFinite(c)||c<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const h=this.plantingCentre();this.surroundings.radiusChanged(c,h?.lat,h?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSourceInput=this.shadow.getElementById("reference-source"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceVideoFromInput=this.shadow.getElementById("referenceVideoFrom"),this.referenceVideoToInput=this.shadow.getElementById("referenceVideoTo"),this.referenceVideoRateInput=this.shadow.getElementById("referenceVideoRate"),this.referenceRemoveKeyButton=this.shadow.getElementById("reference-remove-key"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new Pf(this.addReferenceButton,"reference-add-kind",c=>this.addReferenceOfKind(c),c=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[c]??`reference-add-${c}`),this.setReferenceAddKinds("From an address","From a file","Street-level pictures nearby"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.findGhostsButton=this.shadow.getElementById("reference-find-ghosts"),this.ghostsStatus=this.shadow.getElementById("reference-ghosts-status"),this.findGhostsButton.addEventListener("click",()=>void this.findGhosts()),this.ghostsShownButton=this.shadow.getElementById("reference-ghosts-shown"),this.ghostsShownButton.addEventListener("click",()=>{this.ghostsShown=!this.ghostsShown,this.syncGhostsShown(),this.ufoElement.refresh()}),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.traceImportInput=this.shadow.getElementById("trace-import"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.addTraceButton=this.shadow.getElementById("add-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceVideoFromInput,this.referenceVideoToInput,this.referenceVideoRateInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.modelPicker=new Xp(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.decorParametersHost=this.shadow.getElementById("decor-parameters"),this.decorParameterForm=new Ua(this.decorParametersHost,"en","decorParam.");const s={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new Ua(this.decorBaseHost,"en","decorBase.",s,(c,h)=>this.enhanceDecorModelChoice(c,h)),this.decorStateForm=new Ua(this.decorStateHost,"en","decorState.",s),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",c=>{this.focus({preventScroll:!0}),this.onPointerDown(c)}),this.ufoElement.canvasElement.addEventListener("pointermove",c=>this.onPointerMove(c));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",c=>{n={x:c.clientX,y:c.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",c=>{const h=n;n=void 0,!(!h?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(c.clientX-h.x,c.clientY-h.y)>ge.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",c=>this.onContextMenu(c)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()});const r=this.shadow.getElementById("editor-mute"),a=this.shadow.getElementById("editor-volume");r.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.toggleMuted()}),a.addEventListener("input",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.volume=Number(a.value)}),this.ufoElement.addEventListener("mutedchange",()=>this.syncSoundControls()),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.exportKmlButton.addEventListener("click",()=>void this.exportFigures("kml")),this.exportGeoJsonButton.addEventListener("click",()=>void this.exportFigures("geojson")),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",c=>{const h=c.detail;h.file?this.importFromFile(h.file):this.importFromUrl(h.url)}),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()});for(const c of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])c.addEventListener(c instanceof HTMLSelectElement||c.type==="checkbox"?"change":"input",()=>this.updateLens());this.skySourcesInput.addEventListener("change",()=>{this.ufoElement.sighting.skySources=this.skySourcesInput.checked?void 0:!1,this.ufoElement.refresh(),this.refreshSkyCandidates(),this.showAircraftStatus()}),this.lightPollutionInput.addEventListener("input",()=>{const c=this.ufoElement.sighting;c.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),c.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),c.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.renderNarrativeSettings(),this.durationElement.addEventListener("durationchange",c=>{const{seconds:h,text:d}=c.detail;this.ufoElement.sighting.event.durationText=d,this.ufoElement.durationSeconds=h,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((h??0)*1e3),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const c of this.referenceFields)c.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",c=>void this.setReferenceSource(c.detail)),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.addTraceButton.addEventListener("click",()=>{const c=this.shadow.getElementById("trace-import-row");c.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",c=>void this.addTraces(c.detail)),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",c=>this.onReferenceWheel(c),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",c=>this.onBodyWheel(c),{passive:!1}),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const c of[this.milestoneLabelInput,this.milestoneNoteInput])c.addEventListener("input",()=>this.updateMilestone());this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.shadow.getElementById("add-own-aircraft").addEventListener("click",()=>this.addOwnAircraft()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(HM,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(zM,()=>{const c=this.currentReference();c&&this.syncReferenceStatus(c)}),this.sceneElement.addEventListener(BM,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(UM,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncVideoRegistrationFields(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown),this.shapeAddMenu=new Pf(this.addShapeButton,"add-shape-kind",c=>{const h=ec.byId(c);if(h){this.addModel(h);return}this.currentAppearance={...this.currentAppearance,presetId:c},this.addShape()},c=>`add-shape-${c}`),this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const c of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])c.addEventListener("input",()=>this.updateObserver());for(const c of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])c.addEventListener("input",()=>this.updateObserver());this.isoInput.addEventListener("input",()=>this.updateExposureSettings()),this.filmStockSelect.addEventListener("change",()=>this.updateExposureSettings()),this.meteringSelect.addEventListener("change",()=>this.updateExposureSettings()),this.observerPosition.addEventListener("positionchange",c=>{if(this.observerSaid=c.detail.said,!this.observerPosition.relative)return;const h=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(h,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",c=>this.writeObserverBasis(c.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("input",()=>this.refreshHeadingPoint()),this.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const c=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const h=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(d=>[d.t,Li.fovOf(this.ufoElement.sighting,d.t)]));this.retuneFieldOfView(c),this.retuneExposure(c),Li.reproject(this.ufoElement.sighting,c,h),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.accountCompareInput.addEventListener("change",()=>this.syncBodiesShown()),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const o=c=>this.shadow.querySelector(`${wg}[name="${c}"]`);this.startDate=o("obs-time"),this.endDate=o("obs-end-time"),this.birthDate=o("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=za.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const c of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(c,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",c=>{const{time:h}=c.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=h}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",c=>{this.birth=c.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",c=>{const{time:h}=c.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=h})});for(const c of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])c.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(ge.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const c of this.weatherFields){if(c===this.iceCrystalAlignmentInput||c===this.rareIceCrystalsInput){c.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}c.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const c of this.soundFields)c.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.weatherProviderSelect.addEventListener("change",()=>this.onWeatherProviderChosen()),this.weatherFileLink.addEventListener("click",()=>this.openFileItem("weather")),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(c=>this.shadow.getElementById(c.getAttribute("aria-controls")));for(const c of this.groupTabs)c.addEventListener("click",()=>this.toggleGroup(c,!this.isGroupOpen(c)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const c of this.subgroupTabs)c.addEventListener("click",()=>this.openSubgroup(c));this.buildSkyParts(),rn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",c=>this.onParamSummaryClick(c)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(c=>c.id==="group-shape")],!0),this.sectionChosen=!1,this.opensMostLacking=!0,this.attachWitnessErrors(),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=qN(this.shadow.getElementById("cloud-editor"),this.sceneElement,(c=!0)=>{c&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(c,h)=>{this.headingInput.value=String(this.rounded(c)),this.pitchInput.value=String(this.rounded(h)),this.updateObserver()},Wa(zs.preferencesFor(this),Ga),this.framePlace()),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&(this.ready=this.loadLocaleMessages())}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),zs.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=this.loadLocaleMessages()),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving),Xe.changes.addEventListener("change",this.onModulesChanged),H(async()=>{const{ModuleSession:t}=await import("./ModuleSession-jKFl1FMo.js");return{ModuleSession:t}},[],import.meta.url).then(({ModuleSession:t})=>t.shared.start(),()=>{});const e=this.getAttribute("src");e&&this.importFromUrl(e)}relisters=[];onModulesChanged=e=>{for(const i of this.relisters)i();const t=e.detail;t==="weather"&&(this.followWeatherRecord(),this.fillWeatherProvider()),t==="surroundings"&&this.surveyIds&&this.fillScenerySources(),t==="decorModels"&&this.sceneElement.setDecorModelProvider(this.decorModelProvider),(t==="skyEvents"||t==="interpretations")&&this.buildSkyParts(),t==="perception"&&(this.perceptionSettings.providers=za.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),Xe.changes.removeEventListener("change",this.onModulesChanged),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),clearTimeout(this.moduleNamingTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){const t=An.recording(e);this.sourceUrl=void 0,this.endDrag(),this.ufoElement.sightingData=t,this.sceneElement.requireModules(t.modules),this.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncModulesPanel(),this.syncBodiesShown(),this.isGroupIdOpen("group-shape")&&this.showPhenomenonPartWithContent(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render(),this.aroundPanel.render(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??mp,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.offsetIsAuthors=!1,this.placeZone=void 0,this.timeZoneLookedUpAt=void 0,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.scheduleTimeZoneLookup(!1);const i=this.plantingCentre();this.surroundings.placeLoaded(i?.lat,i?.lng),this.syncSceneryPicker(),this.syncWeatherOwnership(),this.snapshotsPanel.render(),this.refreshFileItems(),!this.applyingFileText&&!this.patchingDraft&&this.resetHistory(),this.markClean(),this.sectionChosen||(this.opensMostLacking=!0)}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&this.fileText()!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=this.fileText(),this.touched=!1,this.savedFileText=this.baseline,this.fileEditor?.markSaved(),this.refreshEditorHead())}set embedded(e){this.shadow.getElementById("editor-head").hidden=e,this.shadow.querySelector(".app").classList.toggle("embedded",e),e||this.shadow.querySelector("#editor-head .head-actions").prepend(this.historyControls)}get historyControls(){return this.undoButton.parentElement}refreshEditorHead(){this.saveButton&&(this.refreshEditorTitle(),this.saveButton.disabled=!this.dirty,this.shareButton.disabled=this.sourceUrl===void 0,this.shareButton.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"")}sourceUrl;get address(){return this.sourceUrl}shareButton;shareDialog;shareMessages;shareSubject={module:"rr0-sighting-editor",link:()=>`${Ah.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let s="";i?.year!==void 0&&(s=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const n=[t,s].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==n&&(r.textContent=n)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.scheduleModuleNaming(),this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons(),this.refreshEditorHead())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons(),this.refreshEditorHead())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=this.shadow.getElementById("save-refused"),t=Kt.issues(this.ufoElement.sighting);if(Gt.show(e,t.length===0?void 0:this.messages.saveRefused.replace("{reasons}",t.map(s=>this.actorIssue(s)).join(" ; ")),"error"),t.length>0)return;const i=hs.inspect(this.sightingData,this.loadedJson());if(i.length===0){this.downloadJson();return}this.askAboutIdentity(i)}actorIssue(e){const t=this.messages;if(e.kind==="duplicate-id")return t.duplicateId.replace("{id}",e.id).replace("{kinds}",e.path.split(", ").map(n=>t.actorKinds[n]??n).join(", "));const i=Number(e.path.split(".")[1]),s=this.ufoElement.sighting.events?.[i];return t.unknownWho.replace("{n}",String(i+1)).replace("{kind}",(s&&t.events.kinds[s.eventType])??s?.eventType??"").replace("{id}",e.id)}loadedJson(){try{return this.baseline?JSON.parse(this.baseline):void 0}catch{return}}askAboutIdentity(e){const t={lastName:this.messages.identityLastName,firstNames:this.messages.identityFirstNames,nameInId:this.messages.identityNameInId,nameInText:this.messages.identityNameInText,address:this.messages.identityAddress,email:this.messages.identityEmail,phone:this.messages.identityPhone};this.shadow.getElementById("identity-ask-text").textContent=this.messages.identityAsk,this.shadow.getElementById("identity-ask-found").replaceChildren(...e.map(n=>{const r=document.createElement("li");return r.textContent=t[n.kind].replaceAll("{value}",n.found),r}));const s=e.some(n=>["lastName","firstNames","nameInId","nameInText"].includes(n.kind));this.shadow.getElementById("identity-ask-initials").hidden=!s,typeof this.identityAsk.showModal=="function"?this.identityAsk.showModal():this.identityAsk.setAttribute("open","")}closeIdentityAsk(){typeof this.identityAsk.close=="function"?this.identityAsk.close():this.identityAsk.removeAttribute("open")}writeNamesAsInitials(){const e=hs.namesOf(this.sightingData);this.observerLastNameInput.value=hs.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>hs.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=hs.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=hs.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=hs.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}async downloadJson(){const e=this.fileBase();let t=new Map;if(this.snapshotsPanel.hasWork()){this.exportButton.disabled=!0;try{t=await this.snapshotsPanel.prepare(e)}finally{this.exportButton.disabled=!1}}const i=this.sightingData;for(const r of Jt.NAMES){const a=this.sectionFilePanel.annex(r);a&&(/^[a-z][a-z0-9+.-]*:/i.test(a.src)||t.set(a.src,a.bytes),Jt.strip(r,i))}const s=`${e}.json`,n=this.writtenText(i);if(t.size===0)this.download(new Blob([n],{type:"application/json"}),s);else{const{zipSync:r,strToU8:a}=await H(async()=>{const{zipSync:h,strToU8:d}=await import("./browser-CltifEM0.js");return{zipSync:h,strToU8:d}},[],import.meta.url),o={[s]:a(n)};for(const[h,d]of t)o[h]=d;const c=r(o,{level:0});this.download(new Blob([c],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.snapshotExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",ms.size(c.length)))}this.markClean()}fileBase(){const e=this.sceneElement.documentUrl?.split(/[?#]/)[0].split("/").pop();return e?.endsWith(".json")&&e.length>5?decodeURIComponent(e.slice(0,-5)):`${this.sightingData.observer?.id??"sighting"}-sighting`}refreshFileItems(){const e=this.fileItemSelect;if(!e||!this.worded)return;this.syncFilePickers();const t=e.value||"recording";e.replaceChildren(new Option(this.messages.fileItemRecording,"recording"),...Jt.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...us.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,ge.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=us.NAMES.includes(e),i=Jt.NAMES.includes(e)?e:void 0,s=e===ge.MODULES_ITEM;this.shadow.getElementById("file-recording").hidden=t||i!==void 0||s,this.shadow.getElementById("snapshot-data").hidden=!t,this.shadow.getElementById("file-section").hidden=i===void 0,this.shadow.getElementById("file-modules").hidden=!s,s&&this.loadModulesPanel();for(const r of["file-recording","snapshot-data","file-section","file-modules"]){const a=this.shadow.getElementById(r);a.hidden||Ln.glue(a)}t&&this.snapshotsPanel.show(e),i&&this.sectionFilePanel.show(i);const n=t&&this.snapshotsPanel.isInlineGroup(e)?["snapshots",e,"src"]:i&&this.sectionFilePanel.isInline(i)?qg.pathOf(i):void 0;this.fileEditorHost.hidden=(t||i!==void 0||s)&&n===void 0,n&&this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(r=>{this.syncFileEditor(!1),r.reveal(n)},()=>{})}moduleNamingTimer;scheduleModuleNaming(){clearTimeout(this.moduleNamingTimer),this.moduleNamingTimer=setTimeout(()=>void this.nameModulesOfModels(),400)}async nameModulesOfModels(){const e=this.decorModelProvider;if(!(e instanceof zp)||Xe.installed().length===0)return;const t=this.ufoElement.sighting,i=new Set([...t.decor.map(r=>r.model?.id),...(t.interpretation?.bodies??[]).map(r=>r.model?.id)].filter(r=>typeof r=="string")),s=this.sceneElement.documentUrl;let n=t.modules;for(const r of i){const a=await e.moduleOf(r),o=a===void 0?void 0:Xe.installed().find(c=>c.id===a)?.url;!o||dT.names(n,o,s)||(n=[...n??[],dT.of(o,s)])}n===t.modules||this.ufoElement.sighting!==t||(t.modules=n,this.syncModulesPanel(),this.syncFileEditor(!1))}static MODULES_ITEM="modules";modulesPanel;modulesPanelLoading;loadModulesPanel(){return this.modulesPanelLoading??=H(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-VPRCdjmv.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([45,46]),import.meta.url).then(({register:e,ModulesPanelElement:t})=>{e();const i=this.shadow.getElementById("modules-panel");this.modulesPanel=i,i.addEventListener("recordingmoduleschange",()=>{const s=i.recordingModules;this.ufoElement.sighting.modules=s.length>0?s:void 0,this.syncFileEditor(!1)}),i.checkContext=()=>({weatherQuery:this.weatherInference.queryOf(this.ufoElement.sighting),interpretation:this.ufoElement.sighting.interpretation}),i.setLanguage(this.language),this.syncModulesPanel()}),this.modulesPanelLoading}syncModulesPanel(){this.modulesPanel&&(this.modulesPanel.base=this.sceneElement.documentUrl,this.modulesPanel.recordingModules=this.ufoElement.sighting.modules)}sectionFromFile(e){return Jt.fromFile(this.ufoElement.sighting.snapshots,e)}masterUrl(){return this.sceneElement.documentUrl??new URL(`${this.fileBase()}.json`,location.href).href}weatherFileItemLabel(){return this.sectionFilePanel?.itemLabel("weather")??""}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}snapshotSources(){const e=qi(M0,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:qi(Eh,this.chosenSourceId.get("imagery")).id,roads:RI(),water:CI(),railways:OI()}}async importFromFile(e){this.holdLoad(()=>void this.loadFile(e))||await this.loadFile(e)}async loadFile(e){this.showLoadError(void 0);try{const t=new Uint8Array(await new Promise((n,r)=>{const a=new FileReader;a.onload=()=>n(a.result),a.onerror=()=>r(a.error),a.readAsArrayBuffer(e)}));Lt.release();const i=await this.recordingText(t),s=JSON.parse(i);if(Vi.isCase(s)){if(Vi.check(s),this.offerCase(s,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=s,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){this.showLoadError(t)}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await H(async()=>{const{unzipSync:d,strFromU8:u}=await import("./browser-CltifEM0.js");return{unzipSync:d,strFromU8:u}},[],import.meta.url),s=t(e),n=/\.(relief|imagery|map)\.zip$|\.(roads|water|railways|upper-air|weather|place|light-pollution|decor)\.json$/,r=Object.keys(s).find(d=>d.endsWith(".json")&&!n.test(d));if(!r)throw new Error("No recording in this archive");const a=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[d,u]of Object.entries(s))d!==r&&d.startsWith(a)&&Lt.hold(Lt.address(d.slice(a.length),void 0),u);const o=i(s[r]),c=JSON.parse(o);let h=!1;for(const d of Jt.NAMES){const u=c.snapshots?.[d]?.src,p=u!==void 0?s[a+u]:void 0;if(!p)continue;const f=An.recording(JSON.parse(i(p)));Jt.put(d,c,f),h=!0}return h?JSON.stringify(c):o}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importInput.url){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}holdForNewScene(e){this.sceneElement.holdForNewScene(e)}async loadUrl(e){this.showLoadError(void 0),this.holdForNewScene();try{const t=await ba.recording(e);if(Vi.isCase(t)){Vi.check(t);const s=new URL(e,location.href).href;if(this.offerCase(t,s)){this.importInput.url=s;return}throw new Error("A case has no recording to edit here")}const i=t;Lt.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=vs.local(e)?void 0:new URL(e,location.href).href,this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){this.showLoadError(t)}}loadError;showLoadError(e){this.loadError=e===void 0?void 0:{error:e},this.sayLoadError()}sayLoadError(){Gt.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof Yp)return e.said(this.messages.formatVersionError);if(!(e instanceof Kl))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";static SCENERY_STORAGE="rr0-sighting-editor.surroundings";static SCENERY_RADIUS_STORAGE="rr0-sighting-editor.surroundings-radius";static NO_SCENERY="none";narrativeProvider=Km[0].create();get narrativeSourceId(){return qi(Km,this.chosenSourceId.get("narrative")).id}narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const i=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:ge.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof $r&&i.kind==="cancelled";this.narrativeStatus.textContent=s?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!s)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:s,...n}=i,r=i.timeZone?n:i,a=lo.stated(r);if(a.length>0){const o=this.ufoElement.sighting.provenance,c=bg(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=lo.apply(c,Tg.loadable(r),a)}finally{this.patchingDraft=!1}this.ufoElement.sighting.provenance=o,this.recordNarrativeProvenance(e,a),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=a.length>0?this.messages.narrativeApplied.replace("{count}",String(a.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,s=new Set(t);for(const n of e.claims)!s.has(n.path)&&!t.some(r=>n.path.startsWith(`${r}.`))||i.provenance.set(n.path,{basis:n.basis,rationale:n.rationale,of:ge.valueAt(bg(this.ufoElement.sighting),n.path)})}static valueAt(e,t){let i=e;for(const s of t.split(".")){if(typeof i!="object"||i===null)return;i=i[s]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(s=>s.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[QB[t]]));for(const s of i){const n=document.createElement("div");n.className=`claim ${t}`;const r=document.createElement("code");r.textContent=s.path;const a=document.createElement(t==="stated"?"q":"span");a.textContent=s.rationale,n.append(r,a),this.narrativeReport.append(n)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const i of e.gaps){const s=document.createElement("li");s.textContent=i,t.append(s)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=qi(Km,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(s=>s.required&&(this.narrativeSettingInputs.get(s.id)?.value.trim()??"")===""),i=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t!==void 0||i,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsSetting.replace("{setting}",this.said.read(t.label)??t.id).replace("{source}",e):i?this.messages.narrativeNeedsAsk:"";for(const s of this.narrativeProvider.settings){const n=this.narrativeSettingInputs.get(s.id);if(!n||!s.suspect)continue;const r=n.value.trim(),a=r===""?void 0:s.suspect(r);n.classList.toggle("invalid",a!==void 0),n.title=a?this.said.read(a)??"":this.said.read(s.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const s=document.createElement("label"),n=document.createElement("span");n.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const o of i.choices??[]){const c=document.createElement("option");c.value=o.value,c.textContent=this.said.read(o.label)??o.value,r.appendChild(c)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"",r.placeholder&&(r.style.minWidth=`min(${r.placeholder.length+3}ch, 100%)`);r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const a=e[i.id]??this.storedNarrativeSetting(i.id);return a!==void 0&&(r.value=a),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),s.append(n,document.createTextNode(" "),r),s});this.narrativeSettingsBox.replaceChildren(...t),this.forgetStoredCredentials(),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const s=i.value.trim();s!==""&&(e[t]=s)}return e}narrativeErrorFor(e){if(!(e instanceof $r))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}static pageCredentials=new Map;static forgetCredentials(){ge.pageCredentials.clear(),fc.forget()}rememberNarrativeSettings(){for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";if(e.remembered==="credential")i!==""?ge.pageCredentials.set(t,i):ge.pageCredentials.delete(t);else if(e.remembered==="preference")try{i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}catch{}}}forgetStoredCredentials(){try{for(const e of this.narrativeProvider.settings)e.remembered==="credential"&&localStorage.removeItem(this.narrativeStorageKey(e.id));localStorage.removeItem(ge.NARRATIVE_KEY_STORAGE),localStorage.removeItem(ge.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){const t=this.narrativeStorageKey(e),i=this.narrativeProvider.settings.find(s=>s.id===e);if(i?.remembered==="credential")return ge.pageCredentials.get(t);if(i?.remembered==="preference")try{return localStorage.getItem(t)??void 0}catch{return}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const i=(e%360+360)%360;return String(i)!==t.value&&(t.value=String(i)),i}refreshSourceRows(){this.relisters.length=0,this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),ge.creditLink(qi(Iy,this.chosenSourceId.get("place")))),this.weatherSourceRow.replaceChildren(),this.fillWeatherProvider(),this.sourcePickers(this.shadow.getElementById("weather-source-rows"),"weather-source-kind","weather",[["weather",this.messages.fileItemWeather,this.shadow.getElementById("weather-picker")],["upper-air",this.messages.snapshotUpperAir,this.sourcePicker("upper-air",kB,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),ge.creditLink(qi(S0,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",Km,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.sourcePickers(this.terrainSourceRows,"source-kind","location",[["place",this.messages.fileItemPlace,this.sourcePicker("place",Iy,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",S0,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",M0,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",Eh,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[ge.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[ge.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[ge.LIVE_RAILWAYS],()=>{},this.groupChoice(["railways"]))]]),this.shadow.getElementById("label-aircraft-source").textContent=this.messages.sourceAircraft,this.shadow.getElementById("aircraft-own-hint").textContent=this.messages.aircraftOwnHint,this.shadow.getElementById("add-own-aircraft").textContent=this.messages.addOwnAircraft,this.shadow.getElementById("aircraft-source-row").replaceChildren(this.aircraftPicker()),this.sourcePickers(this.shadow.getElementById("decor-source-rows"),"decor-source-kind","decor",[["scenery",this.messages.fileItemDecor,this.shadow.getElementById("scenery-picker")],["decor-model",this.messages.decorModel,this.sourcePicker("decor-model",hw,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,s){const n=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;const a=()=>{r.replaceChildren(...t.map(g=>{const v=document.createElement("option");return v.value=g.id,v.textContent=g.name,v.title=g.credit,v})),s&&r.appendChild(new Option(this.messages.sourceFile,ge.FILE_SOURCE))};a();const o=()=>{const g=this.chosenSourceId.get(e);return g!==void 0&&t.some(v=>v.id===g)?g:t[0].id};r.value=s?.fromFile()?ge.FILE_SOURCE:o();const c=document.createElement("a");c.className="source-credit",c.target="_blank",c.rel="noopener noreferrer";const h=document.createElement("button");h.type="button",h.className="link source-file-link",h.addEventListener("click",()=>this.openFileItem(s.item));const d=document.createElement("label");d.className="source-key";const u=document.createElement("input");u.type="password",u.id=`${e}SourceKey`,u.autocomplete="off",u.spellcheck=!1,u.title=this.messages.sourceKeyHint;const p=document.createElement("a");p.className="source-credit",p.target="_blank",p.rel="noopener noreferrer",p.textContent=this.messages.sourceKeyGet,d.append(document.createTextNode(`${this.messages.sourceKey} `),u,document.createTextNode(" "),p),u.addEventListener("change",()=>{const g=qi(t,r.value);fc.set(g.id,u.value),i(g,!0)});const f=()=>{const g=r.value===ge.FILE_SOURCE,v=qi(t,g?o():r.value);d.hidden=g||!v.keyUrl,p.href=v.keyUrl??"",u.value=fc.of(v.id)??"",r.title=g?s.where():v.credit,c.hidden=g,c.href=v.creditUrl,c.textContent=v.credit,h.hidden=!g,g&&(h.textContent=s.label(),h.title=s.where())};f(),r.addEventListener("change",()=>{const g=r.value===ge.FILE_SOURCE;g||this.chosenSourceId.set(e,r.value),s?.setFromFile(g),f(),g||i(qi(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?ge.FILE_SOURCE:o(),f()});const m=()=>{const g=r.value,v=this.chosenSourceId.has(e)&&!t.some(b=>b.id===this.chosenSourceId.get(e));v&&this.chosenSourceId.delete(e),a(),r.value=g===ge.FILE_SOURCE&&s?g:o(),f(),v&&r.value!==ge.FILE_SOURCE&&i(qi(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),c,h,d),n}aircraftPicker(){const e=this.sourcePicker("aircraft",Sw,(t,i)=>this.applyAircraftSource(i));return e.append(this.aircraftStatus),this.showAircraftStatus(),e}get aircraftTabOpen(){return this.isGroupIdOpen("group-weather")&&this.shadow.getElementById("weather-aircraft")?.hidden===!1}showAircraftFlights(){if(this.aircraftTabOpen){if(this.ufoElement.playbackState==="playing"){const e=performance.now();if(e-this.aircraftFlightsShownAt<1e3)return;this.aircraftFlightsShownAt=e}this.aircraftFlights.show(this.sceneElement.aircraftFlights,this.messages)}}aimAtFlight(e){if(e.key===this.aircraftFlights.selectedKey){this.aircraftFlights.select(void 0,this.messages),this.sceneElement.markFlight(void 0);return}if(!e.sky&&e.firstMs===void 0)return;const t=e.sky?this.ufoElement.currentTime:e.firstMs;e.sky||this.goToMark(t),this.sceneElement.lookAtFlight(e.key,t),this.aircraftFlights.select(e.key,this.messages),this.sceneElement.markFlight(e.key),this.showAircraftFlights()}showAircraftStatus(){this.showAircraftFlights();const{status:e,problem:t,partial:i,creditsSpent:s,total:n}=this.sceneElement.aircraftState,r=[];e==="loading"&&r.push(this.messages.aircraftLoading),e==="outside"&&r.push(this.messages.aircraftOutside),e==="byHand"&&r.push(this.messages.aircraftByHand),e==="unavailable"&&!t&&r.push(this.messages.aircraftProblems.network),e==="ready"&&n===0&&r.push(this.messages.aircraftNone),i&&r.push(this.messages.aircraftPartial.replace("{traced}",String(i.traced)).replace("{seen}",`${i.seen}${i.moreSeen?"+":""}`).replace("{km}",String(i.withinKm))),s&&r.push(this.messages.aircraftCredits.replace("{credits}",String(s))),t?Gt.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):Gt.show(this.aircraftStatus,r.length>0?r.join(" "):void 0,"info")}groupChoice(e){return{item:e[0],fromFile:()=>!this.snapshotsPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.snapshotsPanel.setLive(i,!t)},label:()=>this.snapshotsPanel.itemLabel(e[0]),where:()=>this.snapshotsPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const s={...this.ufoElement.sighting.snapshots??{}};i?s[e]=s[e]??{}:delete s[e],this.ufoElement.sighting.snapshots=us.isEmpty(s)?void 0:s,this.touch(),this.scheduleFileSync(),this.refreshFileItems(),i||t()},label:()=>this.sectionFilePanel.itemLabel(e),where:()=>this.sectionFilePanel.where(e)}}static FILE_SOURCE="file";filePickers=new Map;syncFilePickers(){for(const e of this.filePickers.values())e()}openFileItem(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-file");t&&this.toggleGroup(t,!0),this.fileItemSelect.value=e,this.showFileItem(e)}static LIVE_ROADS={id:"ign-osm",name:"IGN BD TOPO / OpenStreetMap",credit:"© IGN, BD TOPO (Licence Ouverte 2.0) in France; © OpenStreetMap contributors (ODbL) elsewhere",creditUrl:"https://www.openstreetmap.org/copyright",create:()=>{}};static LIVE_WATER=ge.LIVE_ROADS;static LIVE_RAILWAYS=ge.LIVE_ROADS;sourcePickers(e,t,i,s){const n=document.createElement("label"),r=document.createElement("span");r.id=`label-${t}`,r.textContent=this.messages.sourceKind;const a=document.createElement("select");a.id=t;const o=s.map(([h,d,u])=>{a.append(new Option(d,h));const p=document.createElement("span");return p.className="source-picker",p.dataset.kind=h,p.append(u),p});a.value=this.sourceKindShown.get(i)??s[0][0];const c=()=>{this.sourceKindShown.set(i,a.value);for(const h of o)h.hidden=h.dataset.kind!==a.value};a.addEventListener("change",c),c(),n.append(r,document.createTextNode(" "),a),e.replaceChildren(n,...o)}sourceKindShown=new Map;static creditLink(e){const t=document.createElement("a");return t.className="source-credit",t.target="_blank",t.rel="noopener noreferrer",t.href=e.creditUrl,t.textContent=e.credit,t}refreshSourceCredits(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),ge.creditLink(qi(Iy,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),ge.creditLink(qi(S0,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:qi(M0,this.chosenSourceId.get("elevation")).create(),imagery:qi(Eh,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(qi(Sw,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new zp(qi(hw,this.chosenSourceId.get("decor-model")).id),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.decorModelEntries=void 0,this.refreshDecorModelOptions(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId)),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e===""||this.sectionFromFile("place"))return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates||this.sectionFromFile("place"))return;const e=this.plantingCentre();if(!e)return;const{lat:t,lng:i}=e;Math.abs(t-this.namedCoordinates.lat)<Sd&&Math.abs(i-this.namedCoordinates.lng)<Sd||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),pT))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(e=!0){const t=this.numberOrUndefined(this.latInput.value),i=this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const s=this.timeZoneLookedUpAt;s&&Math.abs(t-s.lat)<Sd&&Math.abs(i-s.lng)<Sd||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),pT))}async lookUpTimeZone(e,t,i){const s={lat:e,lng:t};this.timeZoneLookedUpAt=s;const n=await this.timeZoneProvider.zoneAt(e,t);if(this.timeZoneLookedUpAt===s){if(this.placeZone=n??void 0,!n||!i||this.timeZoneIsStated()||!this.timeZones.available().includes(n)){this.timeZoneSelect.value=this.zoneShown(),this.updateUtcOffsetValidity();return}this.autoFilledTimeZone=n,this.timeZoneSelect.value=n,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange"))}}async reversePlace(e,t){const i=++this.placeSearchToken;let s;try{s=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}if(i!==this.placeSearchToken)return;this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=s?.name??"",this.placeNameInput.title=s?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=s?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!s;const n=this.ufoElement.sighting.event.place?.[0]??{lat:e,lng:t};this.ufoElement.sighting.event.place=[{lat:n.lat,lng:n.lng,name:this.stringOrUndefined(this.placeNameInput.value.trim())}]}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),s=this.numberOrUndefined(this.pitchInput.value)??0,n=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=this.ufoElement.sighting.event,o=this.ufoElement.sighting.observerTrack,c=this.ufoElement.currentTime,h=o.getInterpolatedPoseAt(c),d=h?.altitudeM!==void 0?r:void 0,u=d!==void 0?h.elevationM:Math.max(0,r-(this.groundElevationM??0)),p=this.ufoElement.sighting.instrument,f=this.numberOrUndefined(this.focalLengthInput.value),m=(p.frame&&f!==void 0?Vt.fieldOfViewDegAt(p,f):f)??this.currentFovDeg(),g=this.numberOrUndefined(this.fNumberInput.value),v=this.filterSelect.value,b=is.byId(o.getLatestPoseAt(c-1)?.filter),w=v===is.NONE.id||v===""?b===is.NONE?void 0:is.NONE.id:v,y=this.statedExposureSeconds(p);this.ufoElement.sighting.exposureSeconds=y===p.exposureSeconds?void 0:y;const M=this.numberOrUndefined(this.focusDistanceInput.value),x=Math.abs(m-Vt.fieldOfViewDeg(p))>.01||g!==p.fNumber||M!==void 0||w!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&u===0&&!x?o.removeKeyframeAt(c):o.addKeyframe(c,{lat:e,lng:t,elevationM:u,...d!==void 0?{altitudeM:d}:{},headingDeg:i,pitchDeg:s,rollDeg:n===0?void 0:n,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:m,fNumber:g,focusDistanceM:M,filter:w});const E=this.stringOrUndefined(this.placeNameInput.value.trim()),A=o.getInterpolatedPoseAt(0);a.place=e!==void 0&&t!==void 0?[{lat:A?.lat??e,lng:A?.lng??t,name:E}]:void 0;const T=this.plantingCentre();this.surroundings.placeChanged(T?.lat,T?.lng),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!E0.isFirm(t))return;const s=E0.at(t,i);s!==void 0&&(this.observerAgeInput.value=String(s),this.updateObserverMetadata())}syncBirthFromAge(){const e=this.ufoElement.sighting.event.time,t=this.numberOrUndefined(this.observerAgeInput.value);if(!e||t===void 0)return;const i=this.birth;if(i&&E0.at(i,e)===t)return;const s=E0.birthFor(t,e);s&&(this.birthDate.setPrecise(!1),this.birth=s,this.birthDate.time=s,this.updateObserverMetadata())}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.refreshSceneryWarning(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&Dh({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.sighting.event.durationText=void 0,this.ufoElement.durationSeconds=void 0)}refreshTimeZoneOptions(){let e=this.timeZoneSelect.options[0];if(!e){e=document.createElement("option"),e.value="";const t=this.timeZoneSelect.parentNode,i=this.timeZoneSelect.nextSibling;this.timeZoneSelect.remove(),this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(s=>{const n=document.createElement("option");return n.value=s,n.textContent=s,n})),t?.insertBefore(this.timeZoneSelect,i)}e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.value=this.zoneShown()}zoneShown(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone:e.utcOffsetHours===void 0?"":this.zoneKnownToRead(e.utcOffsetHours)??""}updateTimeZone(){const e=this.ufoElement.sighting.event,t=this.stringOrUndefined(this.timeZoneSelect.value);if(e.timeZone=t,this.offsetIsAuthors=!1,t===void 0){e.utcOffsetHours=void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup();return}this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event;if(this.offsetIsAuthors&&e.utcOffsetHours!==void 0){const t=this.preferredZoneFor(e.utcOffsetHours);e.timeZone=t,this.timeZoneSelect.value=t??""}else{const t=e.timeZone?this.timeZones.offsetHoursAt(e.timeZone,this.timeZoneReference()):void 0;t!==void 0&&(e.utcOffsetHours=t)}this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}timeZoneReference(){const e=this.ufoElement.sighting.event.time;return e?.year!==void 0?e:{year:new Date().getFullYear(),month:1,day:1,hour:12}}preferredZoneFor(e){return this.zoneKnownToRead(e)??this.timeZones.zonesAt(e,this.timeZoneReference())[0]}zoneKnownToRead(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference()),i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const s=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return s&&t.includes(s)?s:void 0}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.observerTitleInput.value.trim()===""?void 0:this.said.write(e.observer?.title,this.observerTitleInput.value.trim(),this.writingLanguage),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0},s=Kt.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,Kt.renamed(e,s,Kt.observerId(e)),e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerBirth:this.birth,observerPerception:za.compact(this.perceptionSettings.values),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes",...this.evaluationFields.values(),conditions:e.account?.conditions};e.account=Object.values(i).some(s=>s!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...s]=e.sources??[],{url:n,...r}=i??{},a=t===""?r:{...r,url:t},o=Object.keys(a).length>0?[a,...s]:s;e.sources=o.length>0?o:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState()):this.ufoElement.sighting.weatherSource!==void 0&&(this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={..._s(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={..._s(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(s=>s.id===this.currentReferenceId),t=e!==void 0;Ln.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const s of[this.referenceSelect,...this.referenceFields])s.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.syncVideoFields(e),this.showRegistration(this.registrationShown(e)),this.syncReferenceStatus(e)}syncVideoFields(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.referenceVideoFromInput.value=e.video?.fromS===void 0?"":String(e.video.fromS),this.referenceVideoToInput.value=e.video?.toS===void 0?"":String(e.video.toS),this.referenceVideoRateInput.value=e.video?.rate===void 0?"":String(e.video.rate),this.syncReferenceKeyButton(e)}syncReferenceKeyButton(e){this.referenceRemoveKeyButton.hidden=e.kind!=="video"||ds.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=ds.registrationAt(e,this.ufoElement.currentTime);return{headingDeg:this.rounded(t),pitchDeg:this.rounded(i),rollDeg:s===void 0?void 0:this.rounded(s),fovDeg:this.rounded(n)}}showRegistration({headingDeg:e,pitchDeg:t,rollDeg:i,fovDeg:s}){this.referenceHeadingInput.value=String(e),this.referencePitchInput.value=String(t),this.referenceRollInput.value=String(i??0),this.referenceFovInput.value=String(s)}syncVideoRegistrationFields(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);e?.kind==="video"&&(this.syncReferenceKeyButton(e),e.registrationTrack?.length&&this.showRegistration(this.registrationShown(e)))}removeReferenceKey(){const e=this.ufoElement.sighting.references.find(i=>i.id===this.currentReferenceId);if(!e)return;const t=ds.withoutKey(e,this.ufoElement.currentTime);this.ufoElement.sighting.references=this.ufoElement.sighting.references.map(i=>i===e?t:i),this.syncReferenceFields(),this.ufoElement.refresh()}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(Gt.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>lB?this.messages.referenceEmbedded.replace("{kb}",String(i)):"";return}this.referenceStatus.textContent=""}pictureFailureText(e){switch(e.kind){case"notShared":return this.messages.referenceNotShared;case"status":return this.messages.referenceNotFound.replace("{status}",String(e.status));case"notPicture":return this.messages.referenceNotPicture;case"notVideo":return this.messages.referenceNotVideo;default:return this.messages.referenceUnreachable}}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(n=>{if(n.id!==this.currentReferenceId)return n;const r=n.src,a={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||A0))},o=this.registrationShown(n),c=a.headingDeg!==o.headingDeg||a.pitchDeg!==o.pitchDeg||a.rollDeg!==o.rollDeg||a.fovDeg!==o.fovDeg,h=this.referenceKindSelect.value;return h==="video"?{...c?ds.withKey(n,this.ufoElement.currentTime,a):n,kind:h,src:r,title:this.said.write(n.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),video:this.videoClipOfFields(),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),from:void 0}:{...n,kind:h,video:void 0,registrationTrack:void 0,src:r,title:this.said.write(n.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:a,from:c?this.observerPositionNow()??n.from:n.from}});const s=e.references.find(n=>n.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(s),this.syncVideoFieldsKeepingInput(s),this.syncReferenceStatus(s),this.ufoElement.refresh()}videoClipOfFields(){const e={fromS:this.numberOrUndefined(this.referenceVideoFromInput.value),toS:this.numberOrUndefined(this.referenceVideoToInput.value),rate:this.numberOrUndefined(this.referenceVideoRateInput.value)};return e.fromS===void 0&&e.toS===void 0&&e.rate===void 0?void 0:e}syncVideoFieldsKeepingInput(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.syncReferenceKeyButton(e)}useObserverPoseForReference(){const e=et(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(ds.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=et(this.ufoElement.sighting,this.ufoElement.currentTime);return e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0}addReference(e,t,i={}){const s=this.ufoElement.sighting,n=et(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:cB,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:A0},from:this.observerPositionNow(),...i};s.references=[...s.references,a],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSourceInput.mode="url",this.referenceSourceInput.focus()}addReferenceFromFile(){this.addReference(""),this.referenceSourceInput.mode="file",this.referenceSourceInput.openPicker()}async setReferenceSource(e){const t=this.currentReferenceId;if(t===void 0)return;let i;if(e.file){const r=e.file;i=await new Promise((a,o)=>{const c=new FileReader;c.onload=()=>a(c.result),c.onerror=()=>o(c.error),c.readAsDataURL(r)})}else i=e.url;const s=this.ufoElement.sighting,n=ds.kindOfSource(e.file?{type:e.file.type}:{url:e.url});s.references=s.references.map(r=>r.id!==t?r:{...r,src:i,kind:n==="video"||n==="photo"&&r.kind==="video"?n:r.kind,from:n==="video"?void 0:r.from,title:r.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=H(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-DBBH_E6I.js");return{PictureRegistration:e}},[],import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);return e?.registrationTrack?.length?{...e,registration:ds.registrationAt(e,this.ufoElement.currentTime)}:e}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const s=this.pictureAspect(t.id);if(!(s!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,s)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const s=8;for(const n of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(n.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=s)return{landmarkId:n.id,end:"picture"};const a=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=s)return{landmarkId:n.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const s=i.x-t.startPointer.x,n=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(s,n)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+s*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-n*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const s=this.currentReference(),n=s?this.pictureAspect(s.id):void 0;if(!s||n===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(a=>{if(a.id!==e)return a;if(t==="scene")return{...a,scene:this.pictureRegistration.aimOf(r)};const o=this.pictureRegistration.picturePointOf(r,s.registration,n);return o?{...a,picture:o}:a})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||A0,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.pictureAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const a=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const s=this.currentLandmarks(),n=this.nextLandmarkId(s);this.writeLandmarks([...s,{id:n,picture:this.pendingLandmark,scene:this.pictureRegistration.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=n,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.pictureAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),s=this.pictureRegistration.solve(i,t,e.registration.fovDeg);s?(this.referenceFit={n:i.length,residualDeg:s.residualDeg},this.referenceHeadingInput.value=String(this.rounded(s.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(s.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(s.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(s.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return this.pictureRegistration.worldDirectionOf(e.picture,t.registration,i).angleTo(this.pictureRegistration.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.pictureAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[n,r]of t.entries()){const a=document.createElement("option");a.value=r.id;const o=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,n)+o,this.referenceLandmarksSelect.appendChild(a)}this.currentLandmarkId!==void 0&&!t.some(n=>n.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const s=t.find(n=>n.id===this.currentLandmarkId);Ln.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=s===void 0,this.referenceLandmarkLabelInput.disabled=s===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(s?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(a=>a.id===e?{...a,label:this.said.write(a.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:a));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),s=i.findIndex(a=>a.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const a=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+a}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.pictureAspect(t.id);if(i===void 0)return;const{registration:s}=t,n=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(a=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a,s,i))),r=this.currentLandmarks().map((a,o)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(a.scene)),label:this.landmarkLabel(a,o),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(this.pendingLandmark,s,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(n.every(a=>a!==void 0)?n:void 0,r.filter(a=>a.picture!==void 0),this.landmarkHint()),this.paintGhostFinding(e,t,i)};paintGhostFinding(e,t,i){const s=this.ghostFinding;if(!s||!this.ghostsShown||s.referenceId!==t.id||s.src!==t.src)return;const{search:n}=s,r=t.registration,a=d=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:d.x/n.width,v:d.y/n.height},r,i)),o=[];for(const d of n.pairs){const u=a(d.ghost),p=a(d.light),f=a({x:d.ghost.x+d.ghost.radius,y:d.ghost.y});!u||!p||o.push({ghost:u,light:p,ghostRadius:f?Math.hypot(f.x-u.x,f.y-u.y):0})}const c=n.centre?a(n.centre):void 0,h=n.cropped?a({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(o,c,h)}adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:s}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(ds.rollOfPicture(s)??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===n);if(r<0)return;const a=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),o=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[c,h]of o)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:a,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceAddMenu.setDisabled("street",e?void 0:this.messages.referenceStreetNoPlace)}setReferenceAddKinds(e,t,i){const s=this.numberOrUndefined(this.latInput?.value??"")!==void 0&&this.numberOrUndefined(this.lngInput?.value??"")!==void 0;this.referenceAddMenu.setKinds([{value:"address",label:e},{value:"file",label:t},{value:"street",label:i,...s?{}:{disabledReason:this.messages?.referenceStreetNoPlace??""}}])}addReferenceOfKind(e){switch(e){case"file":this.addReferenceFromFile();break;case"street":this.searchStreetPictures();break;default:this.addReferenceFromAddress()}}async searchStreetPictures(){const e=et(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),i=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const s=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.addReferenceButton.disabled=!0;try{this.streetPictures$??=new(await H(async()=>{const{PanoramaxPictures:r}=await import("./PanoramaxPictures-CELY3Ecc.js");return{PanoramaxPictures:r}},[],import.meta.url)).PanoramaxPictures,this.streetPictures=await this.streetPictures$.nearby(t,i,s)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.addReferenceButton.disabled=!1;return}this.addReferenceButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,a]of this.streetPictures.entries()){const o=document.createElement("option");o.value=String(r),o.textContent=this.streetPictureLabel(a,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(o)}const n=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!n,this.referenceStreetAddButton.hidden=!n,this.referenceStatus.textContent=n?"":this.messages.referenceStreetNone.replace("{m}",String(s))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:A0}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;Ln.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t;this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(s=>s.id!==this.currentTraceId?s:{...s,title:this.said.write(s.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(s.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(s=>s.value===this.currentTraceId),i=e.traces.find(s=>s.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{TraceImport:h}=await H(async()=>{const{TraceImport:d}=await import("./TraceImport-uGVIjCrc.js");return{TraceImport:d}},[],import.meta.url);i=await h.fromBytes(await VM.bytesOf(e))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(i.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const s=this.ufoElement.sighting,n=new Set(s.traces.map(h=>h.id));let r=1;const a=this.said.write(void 0,i.documentName??t,this.writingLanguage),o=i.traces.map(h=>{for(;n.has(`trace-${r}`);)r++;const d=`trace-${r}`;return n.add(d),{...h,id:d,title:h.title===void 0?void 0:this.said.write(void 0,h.title,this.writingLanguage),source:a}});s.traces=[...s.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const c=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",t)+c,this.ufoElement.refresh()}async exportFigures(e){const t=this.fileBase(),{GEO_EXPORT_TEXTS:i}=await H(async()=>{const{GEO_EXPORT_TEXTS:a}=await import("./GeoExportTexts-DrGdI2OF.js");return{GEO_EXPORT_TEXTS:a}},[],import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:a}=await H(async()=>{const{KmlExport:c}=await import("./KmlExport-Bh4eTycx.js");return{KmlExport:c}},__vite__mapDeps([47,48]),import.meta.url),o=a.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([o],{type:"application/vnd.google-earth.kml+xml"}),`${t}.kml`);return}const{GeoJsonExport:n}=await H(async()=>{const{GeoJsonExport:a}=await import("./GeoJsonExport-BZ-0v8fM.js");return{GeoJsonExport:a}},__vite__mapDeps([49,48]),import.meta.url),r=n.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([r],{type:"application/geo+json"}),`${t}.geojson`)}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of Tk){const t=document.createElement("option");t.value=e,t.textContent=this.soundKindLabel(e,this.messages),this.soundKindOptions.set(e,t),this.soundKindSelect.appendChild(t)}}soundKindLabel(e,t){switch(e){case"hum":return t.soundHum;case"whistle":return t.soundWhistle;case"rumble":return t.soundRumble;case"crackle":return t.soundCrackle;default:return t.soundNone}}applySoundAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;const e=this.readSound();this.ufoElement.sighting.soundTrack.addKeyframe(this.ufoElement.currentTime,e),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e),this.ufoElement.refresh(),this.previewSound(e)}previewSound(e){clearTimeout(this.soundPreviewTimer),this.ufoElement.previewSound(e),this.soundPreviewTimer=setTimeout(()=>this.ufoElement.stopSoundPreview(),PB)}readSound(){return{kind:this.soundKindSelect.value,volume:Number(this.soundVolumeInput.value),pitchHz:Number(this.soundPitchInput.value),src:this.soundSrcInput.value.trim()||void 0}}syncSoundFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=Xw(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.soundKindSelect&&(this.soundKindSelect.value=e.kind),t!==this.soundVolumeInput&&(this.soundVolumeInput.value=String(e.volume)),t!==this.soundPitchInput&&(this.soundPitchInput.value=String(e.pitchHz)),t!==this.soundSrcInput&&(this.soundSrcInput.value=e.src??""),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e)}updateSoundPitchReadout(e){this.soundPitchValue.textContent=`${Math.round(e)} Hz`}updateSoundFieldsDisabledState(e){const t=e.kind==="none"&&!e.src;this.soundVolumeInput.disabled=t,this.soundSrcInput.disabled=t,this.soundPitchInput.disabled=t||e.src!==void 0}set weatherProvider(e){this.weatherInference=new fp(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===ge.FILE_SOURCE;if(!e){const t=qi(io,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new fp(t.create()),this.scheduleWeatherLookup(!0),this.syncWeatherProvider())}if(this.setWeatherFromFile(e),this.weatherInferredInput.checked!==!e){this.weatherInferredInput.checked=!e,this.keepWeatherSource=e;try{this.weatherInferredInput.dispatchEvent(new Event("change"))}finally{this.keepWeatherSource=!1}}}keepWeatherSource=!1;setWeatherFromFile(e){const t=this.ufoElement.sighting;if(Jt.fromFile(t.snapshots,"weather")===e)return;const i={...t.snapshots??{}};e?i.weather={...i.weather??{},live:void 0}:delete i.weather,i.weather&&i.weather.live===void 0&&delete i.weather.live,t.snapshots=us.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=io.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==qi(io,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new fp(e.create())}else!e&&t!==void 0&&!io.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new fp(qi(io,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...io.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,ge.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!I0(t)?t:void 0;if(this.weatherProviderSelect.querySelector("option[data-stated]")?.remove(),i){const r=new Option(i.name??i.id,i.id);r.dataset.stated="",this.weatherProviderSelect.add(r,this.weatherProviderSelect.options.length-1)}this.weatherProviderSelect.value=e?ge.FILE_SOURCE:i?i.id:qi(io,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=qi(io,this.chosenSourceId.get("weather")),n=this.shadow.getElementById("weather-credit");n.hidden=e||i!==void 0,n.href=s.creditUrl,n.textContent=s.credit,this.weatherFileLink.hidden=!e,e&&(this.weatherFileLink.textContent=this.weatherFileItemLabel(),this.weatherFileLink.title=this.sectionFilePanel?.where("weather")??"")}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.setWeatherFromFile(!this.weatherFromRecords),this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.keepWeatherSource||(this.ufoElement.sighting.weatherSource=void 0),this.syncWeatherSourceState())}scheduleWeatherLookup(e=!1){if(!this.weatherFromRecords||this.pendingWeatherEdit!==void 0)return;const t=this.ufoElement.sighting.weatherSource;!e&&t!==void 0&&!I0(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),uT))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){const e=this.ufoElement.sighting.weatherSource;if(!this.weatherFromRecords||e===void 0||!I0(e))return;const t=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||t===this.weatherTrackSpan||(this.weatherTrackSpan=t,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const a of this.weatherFields)a.disabled=t&&e!==void 0&&a!==this.iceCrystalAlignmentInput&&a!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?a.title=this.messages.weatherWhilePlaying:a.title===this.messages.weatherWhilePlaying&&(a.title=this.fieldHints.get(a.id)??"");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&I0(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const s=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s,this.syncWeatherProvider();const n=t&&e!==void 0;if(this.weatherSourceLink.hidden=!n,n){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=[e.name,this.observationInstantLabel()].filter(Boolean).join(", ");return}const r=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&Js(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherLookupResult=void 0,this.followWeatherRecord(),this.weatherFromRecords=!Jt.fromFile(e.snapshots,"weather")&&(e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0),this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=S0[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),uT)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,s=this.lightPollutionProvider,n=e.event.time?.year,r=()=>{e.lightPollution!==void 0&&(e.lightPollution=void 0,e.provenance.clear("lightPollution"),this.lightPollutionInput.value="",this.ufoElement.refresh())};if(!t||t.lat===void 0||t.lng===void 0||n===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(n<s.year){r(),this.lightPollutionLookup={status:"too-early",year:n},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const a=await s.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=a,a.status==="found"?(e.lightPollution=a.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${s.citation}, at ${a.lat.toFixed(4)}, ${a.lng.toFixed(4)}: ${Math.round(a.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:a.lightPollution}),this.lightPollutionInput.value=String(a.lightPollution),this.ufoElement.refresh()):a.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=Dh(t);this.durationElement.set(i!==void 0?i/1e3:void 0,t.durationText)}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=Pk(this.ufoElement.sighting.event);this.durationElement.title=t==="imprecise"?this.messages.durationImprecise:""}syncSoundControls(){const e=this.shadow.getElementById("editor-mute"),t=this.shadow.getElementById("editor-volume");if(!e||!t)return;const i=this.ufoElement.audible,s=!i||this.ufoElement.muted;e.disabled=!i,t.hidden=!i,e.innerHTML=s?Je.MUTED:Je.VOLUME;const n=i?this.ufoElement.muted?this.messages.unmute:this.messages.mute:this.messages.noSound;e.title=n??"",e.setAttribute("aria-label",n??""),e.setAttribute("aria-pressed",String(s)),t.title=this.messages.volume??"",t.setAttribute("aria-label",this.messages.volume??""),t.value=String(this.ufoElement.muted?0:this.ufoElement.volume)}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;this.syncSoundControls(),de.show(this.playPauseButton,e?"⏸":"▶"),this.playPauseButton.disabled=!t;const i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[s,n]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])s.title=n,s.setAttribute("aria-label",n);this.refreshTimelineMarks()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[i,s]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${s} — ${t}`:s,i.classList.toggle("switchable",e),e?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}chooseTimeInputMode(){const e=this.ufoElement.sighting.event;this.startDate.setPrecise(js.opensPrecise(e.time)),this.endDate.setPrecise(js.opensPrecise(e.endTime))}syncObservationTimeFields(){this.startDate.time=this.ufoElement.sighting.event.time}syncObservationEndTimeFields(){this.endDate.time=this.ufoElement.sighting.event.endTime}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,i=t===void 0?void 0:Math.round(t/15),s=e!==void 0&&i!==void 0&&Math.abs(e-i)>zB;this.utcOffsetInput.classList.toggle("invalid",s),this.utcOffsetInput.title=s?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):"",this.showTimeZoneConsistency(s)}showTimeZoneConsistency(e){const t=this.ufoElement.sighting.event,i=this.placeZone&&t.time?.year!==void 0?this.timeZones.offsetHoursAt(this.placeZone,t.time):void 0,s=t.utcOffsetHours??(t.timeZone?this.timeZones.offsetHoursAt(t.timeZone,this.timeZoneReference()):void 0),n=i!==void 0&&s!==void 0&&s!==i;this.timeZoneSelect.classList.toggle("inconsistent",n&&this.timeZoneSelect.value!==""),this.utcOffsetInput.classList.toggle("inconsistent",n&&!e),this.timeZoneWarning.hidden=!n,this.timeZoneWarning.textContent=n?this.messages.utcOffsetInconsistent.replace("{zone}",this.placeZone).replace("{offset}",i>=0?`+${i}`:String(i)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),UB))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Sd&&Math.abs(e.lng-i)<Sd}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=qi(M0,this.chosenSourceId.get("elevation")),n=await new WM(s.create()).at(e,t);if(i!==this.groundElevationToken||n===void 0)return;this.groundElevationFor={lat:e,lng:t};const r=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(n);const a=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime)?.altitudeM;this.syncElevationField(r,a)}syncElevationField(e,t){const i=this.groundElevationM;this.elevationInput.value=String(Math.round(t??(i??0)+e)),this.elevationInput.min=i===void 0?"":String(i),this.elevationInput.title=i===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=i===void 0||Math.round(e)===0?"":this.messages.groundAt.replace("{m}",String(i))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0;const e=et(this.ufoElement.sighting,0);this.syncElevationField(e?.elevationM??0,e?.altitudeM),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncObserverMetadataFields(){this.witnessErrorView?.refresh();const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=this.said.read(e.observer?.title)??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.observerList.rename(ge.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(js.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.evaluationFields.show(e.account),this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.skySourcesInput.checked=e.skySources!==!1,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=_s(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??eg)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??t3)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),s!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),s!==this.elevationInput&&this.syncElevationField(t?.elevationM??0,t?.altitudeM)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,n=i.getInterpolatedShapeAt(s,this.currentSourceId),r=this.buildAppearanceShape(e??n?.bounds??this.defaultBounds(),n,t);this.commitShapes(s,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const s=fE(e,this.currentAppearance);return t?{...s,angle:t.angle,title:t.title,selected:t.selected}:s}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();for(const[i,s]of this.groupTabs.entries()){const n=s===e&&t;s.setAttribute("aria-expanded",String(n)),this.groupPanels[i].hidden=!n}if(t){const i=e.parentElement.getBoundingClientRect(),s=e.getBoundingClientRect();(s.left<i.left||s.right>i.right)&&(e.parentElement.scrollLeft+=s.left-i.left-(i.width-s.width)/2)}if(t&&e.getAttribute("aria-controls")==="group-decor"){const i=this.decorList.value;i!==""&&i!==this.currentDecorId&&this.selectDecor(i)}t&&e.getAttribute("aria-controls")==="group-observer"&&this.observerShown!==ge.OBSERVER_PRINCIPAL&&this.selectDecor(this.observerShown),t&&e.getAttribute("aria-controls")==="group-weather"&&this.syncSkyParts(),t&&e.getAttribute("aria-controls")==="group-shape"&&this.showPhenomenonPartWithContent(),t&&e.getAttribute("aria-controls")==="group-observation"&&this.candidatesView?.refresh(),this.placeDecorItem(),this.syncCanvasMode(),this.refreshTimelineMarks(),t&&this.sectionFolds.refresh(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>{this.syncFileEditor(!1),this.showFileItem(this.fileItemSelect.value)},()=>this.showFileNote(this.messages.importError,"error"))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await H(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-0VZmtiOX.js");return{SightingFileEditor:t}},__vite__mapDeps([43,20,44]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const s=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(s!==void 0){this.fileFocus="shape",this.selectUnit(s.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(s=>s.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,s]of t.entries()){const n=s.shapes.findIndex(r=>r.sourceId===e);if(n>=0)return["timeline","keyframes",i,"shapes",n]}}showFileNote(e,t="info"){Gt.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of Jt.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&Jt.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of Jt.NAMES){const n=Jt.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||Jt.put(s,e,Jt.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return qS.of(e,t,t==="thin"?Li.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(ge.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(ge.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Jf(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=qS.of(this.ownJson(Lf(e)),t,t==="thin"?Li.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){if(t.edited)try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i))return;const s=JSON.stringify(i.weatherTrack);if(i=this.withAnnexed(i),!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,r=!t&&this.fileTextApplied!==void 0&&s!==JSON.stringify(ge.weatherOf(this.fileTextApplied)),a={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=n,r&&!this.restoringWeather&&this.weatherFromRecords){const o=this.ufoElement.sighting.weatherSource;o===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):io.some(c=>c.id===o.id)&&this.askAboutWeather(a,o.name??o.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(o){this.showFileNote(o instanceof Yp?o.said(this.messages.formatVersionError):this.messages.importErrorMalformed,"error"),this.fileTextApplied=e}finally{this.applyingFileText=!1}}fileTextApplied;static weatherOf(e){try{return JSON.parse(e).weatherTrack}catch{return}}pendingWeatherEdit;restoringWeather=!1;askAboutWeather(e,t){this.cancelWeatherLookup(),this.pendingWeatherEdit=e,this.shadow.getElementById("file-ask-text").textContent=this.messages.weatherEditedAsk.replaceAll("{source}",t),this.shadow.getElementById("file-ask-stop").textContent=this.messages.weatherEditedStop,this.shadow.getElementById("file-ask-keep").textContent=this.messages.weatherEditedKeep,typeof this.fileAsk.showModal=="function"?this.fileAsk.showModal():this.fileAsk.setAttribute("open","")}closeFileAsk(){typeof this.fileAsk.close=="function"?this.fileAsk.close():this.fileAsk.removeAttribute("open")}stopReadingWeather(){this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState(),this.ufoElement.refresh(),this.syncFileEditor(!1)}keepReadingWeather(){const e=this.pendingWeatherEdit;if(this.pendingWeatherEdit=void 0,this.closeFileAsk(),e!==void 0){this.restoringWeather=!0;try{this.applyFileText(JSON.stringify({...this.sightingData,weatherTrack:e.track,weatherSource:e.source}))}finally{this.restoringWeather=!1}this.syncFileEditor(!1)}}applyingFileText=!1;patchingDraft=!1;leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(!1),0))}static SCENE_LINKED=["heading","pitch","focalLength","apparentWidth","realWidth","objectDistance","color","haloScale","cloudCover","windDirection","windSpeed","referenceOpacity"];setActiveSceneField(e){e!==this.activeSceneField&&(this.activeSceneField=e,e==="referenceOpacity"&&!this.ufoElement.referencesShown?(this.ufoElement.toggleReferences(),this.referencesShownForField=!0):e!=="referenceOpacity"&&this.referencesShownForField&&(this.ufoElement.referencesShown&&this.ufoElement.toggleReferences(),this.referencesShownForField=!1),this.refreshSceneField())}static COMPASS_STEP_DEG=45;static HORIZON_STEP_DEG=2;showOrientation(e,t){const i=a=>this.rounded(a).toLocaleString(this.language,{maximumFractionDigits:1}),s=a=>a.x>=-.05&&a.x<=1.05&&a.y>=-.05&&a.y<=1.05;let n;if(e!==void 0){const a=(e%360+360)%360,o=[];for(let c=0;c<360;c+=ge.COMPASS_STEP_DEG){const h=this.sceneElement.horizonPointAt(c);h&&s(h)&&o.push({...h,label:this.naming.point(c)})}n={label:this.messages.overlayHeading.replaceAll("{deg}",i(a)).replaceAll("{point}",this.naming.point(a)),compass:o}}let r;if(t!==void 0){const a=[[]];for(let o=0;o<=360;o+=ge.HORIZON_STEP_DEG){const c=this.sceneElement.horizonPointAt(o);c&&Math.abs(c.x-.5)<1.5&&Math.abs(c.y-.5)<1.5?a[a.length-1].push(c):a[a.length-1].length>0&&a.push([])}r={line:a,label:this.messages.overlayHorizon.replaceAll("{deg}",i(t))}}this.sceneFieldOverlay.orientation(n,r)}refreshSceneField(){const e=this.sceneFieldOverlay;if(!e)return;const t=this.activeSceneField,i=this.ufoElement.sighting,s=this.ufoElement.currentTime,n=this.ufoElement.canvasElement,r=this.messages,a=c=>this.numberOrUndefined(c.value),o=(c,h=1)=>c===void 0?"?":c.toLocaleString(this.language,{maximumFractionDigits:h});if(t==="pitch")this.showOrientation(void 0,a(this.pitchInput)??0);else if(t==="heading")this.showOrientation(a(this.headingInput)??0,void 0);else if(t==="focalLength"){const c=Li.fovOf(i,s),d=2*Qr.of(i.instrument,n.height,c).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",o(c)).replaceAll("{h}",o(d)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const c=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!c){e.hide();return}const h=c.bounds,u=[[a(this.apparentWidthInput),"°",1],[a(this.realWidthInput)," m",1],[a(this.objectDistanceInput)," m",0]].filter(([p])=>p!==void 0).map(([p,f,m])=>`${o(p,m)}${f}`).join(" · ");e.measure((h.x+h.width/2)/n.width,(h.y+h.height/2)/n.height,Math.max(h.width,h.height)*1.3/n.width,u)}else if(t==="windDirection"||t==="windSpeed"){const c=a(this.windDirectionInput)??0,h=c-(a(this.headingInput)??0);e.wind(h,r.overlayWind.replaceAll("{point}",this.naming.point(c)).replaceAll("{speed}",o(a(this.windSpeedInput))))}else e.hide()}attachWitnessErrors(){const e=this,t=()=>this.ufoElement.sighting,i=()=>this.ufoElement.currentTime,s=this.shadow.querySelector('rr0-date-input[name="obs-time"]');this.witnessErrorView.attach({kind:"time",label:s.closest("label"),input:s,path:()=>t().event.time?"time":void 0,value:()=>t().event.time?.hour!==void 0?0:void 0}),this.witnessErrorView.attach({kind:"duration",label:this.durationElement.closest("label"),input:this.durationElement,path:()=>t().event.durationSeconds!==void 0?"durationSeconds":void 0,value:()=>t().event.durationSeconds});const n=c=>{let h=-1;return c.forEach((d,u)=>{d<=i()&&(h=u)}),h===-1&&c.length>0?0:h};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const c=n(t().observerTrack.allKeyframes.map(h=>h.t));return c===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${c}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const c=t().timeline.allKeyframes,h=n(c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId)).map(f=>f.t));if(h===-1||this.apparentWidthInput.value==="")return;const d=c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId))[h],u=c.indexOf(d),p=d.shapes.findIndex(f=>f.sourceId===this.currentSourceId);return`timeline.keyframes.${u}.shapes.${p}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const a=document.createElement("div");a.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(a);const o=c=>c?.closest("label")??void 0;this.candidatesView=new Wn({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const c=this.ufoElement.sighting.event,h=c.place?.[0];if(!h||c.time?.year===void 0||c.time.hour===void 0)return;const d=Js(c.time,h.lng,c.utcOffsetHours);return d?{date:d,observer:{lat:h.lat,lng:h.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:c=>mo(c,this.instrumentGain()),fieldLabels:()=>({time:o(s),heading:o(this.headingInput),size:o(this.apparentWidthInput),duration:o(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:c=>{const h=`${c}/${this.language}`;return this.poherMatrix?.key!==h&&(this.poherMatrix={key:h,loaded:yl.load(c,this.language,d=>ba.json(d))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const c=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,h=this.sceneElement.satellitePassesDuring(c);return h.length>0?{passes:h,positionsAt:d=>this.sceneElement.satellitePositionsAt(d)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const c=this.ufoElement.sighting.interpretation;return[...c&&(c.bodies.length>0||hi.computes(c,mc.kinds()))?[{id:"own",label:this.said.read(c.title)??this.principalObserverLabel(),interpretation:c}]:[],...this.readings]},computed:c=>this.sceneElement.computedInterpretation(c),starName:c=>this.naming.star({name:c}),projectionAt:(c,h)=>this.sceneElement.bodyProjectionAt(c,h),variants:()=>this.ufoElement.sighting.variants,keep:c=>this.editVariants(h=>[...h,c]),remove:c=>this.editVariants(h=>h.filter((d,u)=>u!==c))},a)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,s=i.place?.[0];if(s&&i.time?.year!==void 0&&i.time.hour!==void 0){const h=Js(i.time,s.lng,i.utcOffsetHours);h&&(t.sunAltitudeDeg=Di("Sun",h,{lat:s.lat,lng:s.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const h=_s(e,0);t.cloudCover=h.cloudCover,t.lightning=h.storm,t.lowVisibility=h.precipitationType!=="none"&&h.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const h=n.allKeyframes.filter(p=>p.shapes.some(f=>f.sourceId===r)),d=h.map(p=>({t:p.t,shape:n.getShapeAt(p.t,r)})).filter(p=>p.shape?.aim),u=n.getInterpolatedShapeAt(h[0]?.t??0,r);if(u?.aim&&(t.elevationDeg=u.aim.altitudeDeg),u?.angular){t.widthDeg=u.angular.widthDeg;const p=u.angular.heightDeg>0?u.angular.widthDeg/u.angular.heightDeg:1;t.round=u.kind==="oval"&&p>.8&&p<1.25}if(u?.brightness!==void 0&&(t.brightness=u.brightness),d.length>1){const p=(v,b)=>{const w=Math.PI/180,y=Math.sin(v.altitudeDeg*w)*Math.sin(b.altitudeDeg*w)+Math.cos(v.altitudeDeg*w)*Math.cos(b.altitudeDeg*w)*Math.cos((v.azimuthDeg-b.azimuthDeg)*w);return Math.acos(Math.max(-1,Math.min(1,y)))/w},f=d.slice(1).map((v,b)=>({deg:p(d[b].shape.aim,v.shape.aim),s:(v.t-d[b].t)/1e3}));t.sweepDeg=p(d[0].shape.aim,d[d.length-1].shape.aim);const m=f.reduce((v,b)=>v+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const g=(d[d.length-1].t-d[0].t)/1e3;if(g>0){t.speedDegPerS=m/g;const v=Math.max(...f.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?v/t.speedDegPerS:0}}}const a=new Set(n.sourceIds.map(h=>n.groupMembers(h)?.[0]??h));a.size>0&&(t.count=a.size);const o=[...a].map(h=>n.getInterpolatedShapeAt(0,h)?.aim).filter(h=>h!==void 0);if(o.length>=3){const h=Math.PI/180,d=o.map(m=>({x:(((m.azimuthDeg-o[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*h),y:m.altitudeDeg}));let[u,p]=[d[0],d[1]];for(const m of d)for(const g of d)Math.hypot(m.x-g.x,m.y-g.y)>Math.hypot(u.x-p.x,u.y-p.y)&&([u,p]=[m,g]);const f=Math.hypot(u.x-p.x,u.y-p.y);t.aligned=f>0&&d.every(m=>Math.abs((p.x-u.x)*(u.y-m.y)-(u.x-m.x)*(p.y-u.y))/f<=Math.max(.5,f*.1))}const c=new Set([...a].map(h=>n.getInterpolatedShapeAt(0,h)?.color).filter(h=>h!==void 0));return c.size>0&&(t.colors=[...c]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(h=>h.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}static SCENE_HEIGHT_KEY="rr0-editor-scene-height";resizeScene(e){const t=this.shadow.querySelector(".app"),i=this.sceneElement,s=n=>{n===void 0?t.style.removeProperty("--rr0-scene-max-height"):t.style.setProperty("--rr0-scene-max-height",`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,n)))}px`);try{n===void 0?localStorage.removeItem(ge.SCENE_HEIGHT_KEY):localStorage.setItem(ge.SCENE_HEIGHT_KEY,t.style.getPropertyValue("--rr0-scene-max-height"))}catch{}};try{const n=localStorage.getItem(ge.SCENE_HEIGHT_KEY);n&&/^\d+px$/.test(n)&&t.style.setProperty("--rr0-scene-max-height",n)}catch{}e.addEventListener("pointerdown",n=>{n.preventDefault();const r=n.clientY,a=i.getBoundingClientRect().height;e.setPointerCapture?.(n.pointerId),e.classList.add("dragging");const o=h=>s(a+h.clientY-r),c=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",c),e.removeEventListener("pointercancel",c)};e.addEventListener("pointermove",o),e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}),e.addEventListener("keydown",n=>{n.key!=="ArrowUp"&&n.key!=="ArrowDown"||(n.preventDefault(),s(i.getBoundingClientRect().height+(n.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>s(void 0))}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=a=>{const o=this.groupTabs.find(c=>c.getAttribute("aria-controls")===a);o&&this.toggleGroup(o,!0)},s=a=>()=>{this.touch(),this.armHistory(),a(),this.scheduleHistoryRecord(),this.refreshTimelineMarks()},r=[this.showsBodies?{id:"bodies",label:t.bodiesTrack,color:"#f5c451",...this.eventMarks("bodies"),open:()=>this.chooseAccountView(!0),selected:this.pickedEvent(this.bodiesEventsPanel),select:a=>this.pickEvent(Number(a)),add:()=>this.bodyEditor?s(()=>this.bodyEditor.keyframeHere())():this.chooseAccountView(!0)}:{id:"shapes",label:t.shapesTrack,color:"#f5c451",...this.eventMarks("phenomenon"),open:()=>this.revealShapePanel(),selected:this.pickedEvent(this.phenomenonEventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>{e.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,!1)})},{id:"observer",label:t.observerTrack,color:"#7fd4ff",...this.eventMarks("observer"),open:()=>i("group-location"),selected:this.pickedEvent(this.eventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(a=>a.t),open:()=>i("group-weather"),add:s(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(a=>a.t),open:()=>i("group-sound"),add:s(()=>this.applySoundAtPlayhead())}];this.timelineTracks.show(r,this.ufoElement.seekableDuration,this.ufoElement.currentTime)}eventMarks(e){const t=this.ufoElement.sighting;if(e==="bodies")return this.bodyMarks();const i=e==="observer"?ft.observerTrackIsExpanded(t):ft.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(h=>h.t)};const n=this.ufoElement.seekableDuration,r=h=>e==="observer"?Kt.isObserver(t,h):Kt.isPhenomenon(t,h),a=(t.events??[]).map((h,d)=>({event:h,index:d})).filter(({event:h})=>r(h)),o=new Set(a.map(({event:h})=>h.who)).size>1,c=a.map(({event:h,index:d})=>{const u=this.messages.events.kinds[h.eventType]??h.eventType;return{id:String(d),t:h.t,until:h.until??n,label:e==="phenomenon"&&o?`${this.shapesLabel(h.who??"")} · ${u}`:u}});return{times:[],spans:c}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(o=>o.id)),s=o=>Kt.partOf(o)?.element??o??"",n=(e.events??[]).map((o,c)=>({event:o,index:c})).filter(({event:o})=>i.has(s(o.who)));if(n.length===0||!ft.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(o=>o.track.map(c=>c.t)))].sort((o,c)=>o-c)};const r=this.ufoElement.seekableDuration,a=n.map(({event:o,index:c})=>{const h=t.find(f=>f.id===s(o.who)),d=Kt.partOf(o.who)?.part,u=this.messages.events.kinds[o.eventType]??o.eventType,p=[...t.length>1?[this.said.read(h?.title)??s(o.who)]:[],...d?[d]:[]];return{id:String(c),t:o.t,until:o.until??r,label:[...p,u].join(" · ")}});return{times:[],spans:a}}pickedEvent(e){const t=e?.pickedIndex,i=e===this.eventsPanel?"events-section":e===this.phenomenonEventsPanel?"phenomenon-events-section":"bodies-events-section",s=this.shadow.getElementById(i);return t===void 0||!s||s.closest("[hidden]")?void 0:String(t)}pickEvent(e){const t=this.ufoElement.sighting,i=t.events?.[e];if(!i)return;const s=i.who??Kt.observerId(t);if(Kt.isObserver(t,i)){const n=this.groupTabs.find(r=>r.getAttribute("aria-controls")==="group-location");n&&this.toggleGroup(n,!0),this.eventsPanel.pick(e)}else Kt.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(Kt.partOf(s)?.element??s),this.bodiesEventsPanel.pick(e),this.refreshTracks()}));this.goToMark(i.t),this.refreshTracks()}shapesLabel(e){const t=this.ufoElement.sighting,i=t.timeline.groupOf(e);if(i)return this.said.read(i.title)??e;const s=t.timeline.allKeyframes.map(n=>n.shapes.find(r=>r.sourceId===e)?.shape.title).find(n=>n!==void 0);return this.said.read(s)??e}get showsBodies(){return this.accountViewSelect.value==="bodies"}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(o,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${o})`})),i=o=>{if(this.showsBodies){const h=this.eventMarks("bodies");return h.spans?h.spans.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.bodiesTrack,h.times)}const{spans:c}=this.eventMarks("phenomenon");return c?c.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(h=>!o||h.shapes.some(d=>this.selectedSourceIds.has(d.sourceId))).map(h=>h.t))},s=()=>{const{times:o,spans:c}=this.eventMarks("observer");return c?c.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.observerTrack,o)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(o=>o.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(o=>o.t)),a=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?s():this.isGroupIdOpen("group-weather")?n():this.isGroupIdOpen("group-sound")?r():[...i(!1),...s(),...n(),...r()];for(const o of e.milestones)a.push({t:o.t,kind:"milestone",label:this.said.read(o.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration),this.refreshTracks(),this.eventsPanel?.sync(),this.phenomenonEventsPanel?.sync(),this.bodiesEventsPanel?.sync(),this.witnessErrorView?.refreshFields(),this.activeSceneField&&this.refreshSceneField()}seekTo(e){this.goToMark(e*1e3)}set passages(e){const t=this.shadow.getElementById("moment-passages");t.replaceChildren(...(e??[]).map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.className="at",n.innerHTML=Je.PLAY,n.append(i.clock),n.addEventListener("click",()=>this.seekTo(i.at));const r=document.createElement("button");return r.type="button",r.className="excerpt",r.textContent=i.said,r.title=i.where,r.addEventListener("click",()=>i.open()),s.append(n,r),s})),t.hidden=t.childElementCount===0}set interviewSources(e){this.saidInterviews=e,this.witnessErrorView?.refreshFields()}valueSources(){if(!this.worded)return;const e=this.ufoElement.sighting.references.filter(t=>t.kind!=="video").map(t=>({id:t.id,label:this.said.read(t.title)??t.id}));return{messages:this.messages.basisSource,choices:{...this.saidInterviews?.length?{interviews:this.saidInterviews}:{},...e.length>0?{pictures:e}:{}}}}openSection(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);t&&this.toggleGroup(t,!0)}showRender(){this.sceneElement.scrollIntoView?.({block:"center",behavior:"smooth"})}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-file")?this.fileFocus==="decor"&&this.editableDecor()!==void 0?"decor":this.fileFocus==="shape"&&this.selectedSourceIds.size>0?"shape":"scene":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-weather")&&this.openSkyParts().some(e=>e.category==="skyEvent")?"scene":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",s=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",t&&this.currentReference()&&this.loadPictureRegistration(),this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,s&&this.ufoElement.repaintOverlay(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const n=this.currentReference();n&&this.syncReferenceStatus(n),this.syncStreetSearchAvailability(),this.syncBodiesShown()}skyOf(e){const t=mc.kinds();if(hi.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...hi.computedPart(e,t)}}),this.skyPart.sky}skyPart;syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading,i=this.ufoElement.sighting.interpretation,s=t?i:this.skyOf(i);this.sceneElement.compareAccount=t&&s!==void 0&&this.accountCompareInput.checked,this.sceneElement.interpretation!==s&&(this.sceneElement.interpretation=s);const n=t&&s!==void 0?"bodies":"shapes",r=this.accountViewSelect.value!==n;this.accountViewSelect.value=n,r&&this.refreshTimelineMarks(),this.syncSkyParts(),this.shadow.getElementById("account-view-row").hidden=this.isReading,this.shadow.getElementById("account-compare-row").hidden=this.isReading||n!=="bodies"}syncSkyParts(){if(this.isGroupIdOpen("group-weather")){this.showAircraftFlights();for(const e of this.openSkyParts())this.loadSkyPartEditor(e)?.then(t=>t.refresh())}}chooseAccountView(e){const t=this.groupTabs.find(s=>s.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const s of this.subgroupTabs){if(s.parentElement!==t)continue;const n=s===e;s.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(s.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(s=>s.sync());const i=[...this.skyParts.values()].find(s=>s.tab===e);i&&this.loadSkyPartEditor(i)?.then(s=>s.sync()),e.getAttribute("aria-controls")==="weather-aircraft"&&this.showAircraftFlights(),this.syncCanvasMode()}showPhenomenonPartWithContent(){const e=this.ufoElement.sighting,t=e.timeline.sourceIds.length>0,i=(e.interpretation?.bodies?.length??0)>0,n=this.shadow.getElementById("shape-bodies")?.hidden===!1?!i&&t?"shape-shapes":void 0:!t&&i?"shape-bodies":void 0,r=n&&this.subgroupTabs.find(c=>c.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:a,opensMostLacking:o}=this;this.openSubgroup(r),this.sectionChosen=a,this.opensMostLacking=o}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){if(!this.paramSummaryBuilder)return;const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|"),s=JSON.stringify(this.ufoElement.sighting.account??null);if(i===this.paramSummarySignature){s!==this.assessedAccount?(this.assessedAccount=s,this.assessSoon()):this.assessmentsOwed&&this.ufoElement.playbackState!=="playing"&&this.assessSoon();return}this.assessedAccount=s,this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.assessSoon()}assessmentsOwed=!1;assessSoon(){if(this.ufoElement.playbackState==="playing"){this.assessmentsOwed=!0;return}this.assessmentsOwed=!1,this.runAssessments()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=ge.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==s.group&&(i=void 0),e.includes(s.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=s.group;const a=document.createElement("span");a.className="param-nest-label",a.textContent=s.group==="assessment"?this.messages.assessmentGroup:s.group==="summary"?this.messages.summaryGroup:ge.tabLabel(this.groupTabs[this.summaryPanelIndex(s.group)]),r.append(a),i={group:s.group,element:r},t.push(r)}const n=this.paramChip(s);i?i.element.append(n):t.push(n)}this.paramSummary.replaceChildren(...t),this.shadow.getElementById("label-param-summary").textContent=this.messages.paramSummaryTitle.replace("{n}",String(t.length)),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),gI.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return this.panelIndex(e==="phenomenon"?"shape":e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]},"bg-information":{panel:"observer",fields:["accountSource"]},"bg-occupation":{panel:"observer",fields:["observerOccupationKind"]},"bg-relation":{panel:"observer",fields:["observersRelation"]},"bg-activity":{panel:"observer",fields:["observerActivity"]},"bg-age":{panel:"observer",fields:["observerAge"]},"bg-appearance":{panel:"observer",fields:["strangeness-appearance"]},"bg-movement":{panel:"observer",fields:["strangeness-movement"]},"bg-incongruity":{panel:"observer",fields:["strangeness-incongruity"]},"bg-close":{panel:"observer",fields:["strangeness-close"]},"bg-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-occupants":{panel:"observer",fields:["strangeness-beings"]}};assessmentChips=[];assessmentToken=0;assessedAccount="";async runAssessments(){const e=++this.assessmentToken,t=await new EM(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=s=>{const n=s.querySelector(".tab-badge");return n&&!n.hidden?Number(n.textContent):0},t=this.groupTabs.find(s=>this.isGroupOpen(s));let i=t&&e(t)>0?t:void 0;for(const s of this.groupTabs)e(s)>(i?e(i):0)&&(i=s);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
|
|
12302
|
-
`)}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const n of e){const r=ge.QUESTION_FIELDS[n];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const o=this.shadow.getElementById(a);o&&!o.hidden&&o.value===""&&t.add(a)}}for(const[n,r]of Object.entries(ge.QUESTION_FIELDS))for(const a of ge.QUESTION_FIELDS[n].fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=t.has(a)&&!o.classList.contains("missing-required");o.classList.toggle("wanted",c),(c||o.title===this.messages.questionUnanswered)&&(o.title=c?this.messages.questionUnanswered:this.fieldHints.get(a)??"")}const i=new Map;let s;for(const[n,r]of Object.entries(ge.QUESTION_FIELDS))for(const a of r.fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=o.classList.contains("missing-required");!c&&!o.classList.contains("wanted")||(c&&(s=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const n of this.groupTabs){const r=this.panelOf(n),a=i.get(r)??0,o=r===s,c=ge.badgeOn(n);c.hidden=a===0,c.textContent=String(a),c.classList.toggle("optional",!o);const h=a===0?void 0:o?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a));h?n.dataset.unanswered=h:delete n.dataset.unanswered,ge.titleGroupTab(n)}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field,e.detail&&(t.title=e.detail);const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const n=document.createElement("span");n.className="param-chip-swatch",n.style.background=e.color,t.append(n)}const s=document.createElement("span");return s.className="param-chip-value",s.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(s),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const s=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const n=t.dataset.field;if(n.startsWith("shape:")){this.selectedSourceIds=new Set([n.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(n.startsWith("body:")){const a=this.subgroupTabs.find(o=>o.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(o=>o.show(n.slice(5)));return}if(n.startsWith("decor:")){this.currentDecorId=n.slice(6),this.refreshDecorList(),this.decorList.focus();return}const r=this.shadow.getElementById(n);r===null||!s.contains(r)||(this.revealSubgroupOf(r),this.sectionFolds.reveal(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.showAircraftFlights(),this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe();for(const i of this.openSkyParts())i.editor?.setTime?.(this.ufoElement.currentTime);for(const i of[this.eventsPanel,this.phenomenonEventsPanel,this.bodiesEventsPanel])i?.setTime(this.ufoElement.currentTime);this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.samplingRateInput!==this.shadow.activeElement&&(this.samplingRateInput.value=this.ufoElement.sighting.sampleMs===void 0?"":String(this.ufoElement.sighting.sampleMs)),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.getElementById("shape-row");t&&Ln.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=e?t:this.fieldHints.get(i.id)??""}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:jB(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.shadow.activeElement!==this.shapeRotationInput&&(this.shapeRotationInput.value=String(ge.rotationDeg(e.angle))),this.refreshApparentSize())}static rotationDeg(e){const t=(e*180/Math.PI%360+540)%360-180;return Math.round((t===-180?180:t)*10)/10}updateShapeRotation(){const e=this.numberOrUndefined(this.shapeRotationInput.value);if(e===void 0)return;const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);s&&(this.commitShapes(i,[{sourceId:this.currentSourceId,shape:{...s,angle:e*Math.PI/180}}]),this.ufoElement.refresh())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,Ft.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,Ft.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(Ft.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(Ft.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!s)return;const n=this.currentProjection(),r=n.degToPx(e),a=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),o={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-a)/2,width:r,height:a},c=n.ofBounds(o),h=s.kind==="oval"?{...s,bounds:o,angular:c}:{...s,bounds:o,angular:c,points:this.scalePoints(s,o)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,s=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(n=>({x:n.x*i,y:n.y*s}))}refreshFilterOptions(){const e={[is.NONE.id]:this.messages.filterNone,[is.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[is.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==is.ALL.length||is.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||is.NONE.id;this.filterSelect.replaceChildren();for(const r of is.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=n}const s=this.ufoElement?.sighting?.instrument;for(const n of this.filterSelect.options){const r=!s||is.usableWith(is.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,s={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,video:this.messages.instrumentCategoryVideo,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},n=r=>{const a=this.naming.instrument(r),o=Vt.unavailability(r,t);if(!o)return{id:r.id,label:a};const c=(o.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(o.from)).replace("{to}",String(o.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:c}:{id:r.id,label:a,disabledReason:c}};this.instrumentSelect.choices=Vt.CATEGORIES.map(r=>({label:s[r],children:bp.filter(a=>a.category===r).map(n)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=ge.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const n=Number(i[1]),r=Number(i[2]);return r>0?n/r:void 0}const s=Number(t);return Number.isFinite(s)&&s>0?s:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=et(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??Vt.fieldOfViewDeg(t),r=s?Vt.focalLengthMmFor(t,n):n;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=s?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=s?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=s!==void 0&&s.focalRangeMm===void 0,this.focalLengthInput.min=String(s?s.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(s?s.focalRangeMm?.maxMm??2e3:179),rn.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=s&&n!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(n,n<10?1:0)):"";const a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const o=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":ge.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const d of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(d,zt.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const c=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const h=pc.byId(e.film);this.isoInput.placeholder=c?c.autoExposure?"auto":String(h?.iso??c.iso):"",this.setRowVisible(this.isoInput,c!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,c?.autoExposure===!0),this.meteringSelect.disabled=e.iso!==void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,s!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=is.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Vt.fieldOfViewDeg(e),s=Vt.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>VB||t.observerTrack.addKeyframe(n.t,{...n.pose,fovDeg:s})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,s=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!s){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(s.max,Math.max(s.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return et(e,this.ufoElement.currentTime)?.fovDeg??Vt.fieldOfViewDeg(e.instrument)}currentProjection(){return Qr.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=Ft.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const s=et(this.ufoElement.sighting,this.ufoElement.currentTime),n=s?.focusDistanceM;if(n!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(n));return}const r=(s?Vt.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,a=s?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const o=this.ufoElement.canvasElement.height;if(o<=0)return;const c=2*q1*e/o*i.heightMm,h=r*r/(a*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const s=this.numberOrUndefined(this.realWidthInput.value),n=s!==void 0&&(t!==void 0&&s<t||i!==void 0&&s>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),a=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+a+n;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+n}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),s=(m,g)=>Number(m.toFixed(g)),n=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??FB,a=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),o=a!==void 0&&a<r,c=s(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:s(Ft.sizeMAt(c,h),2),lengthM:s(Ft.sizeMAt(c,h),2),heightM:s(Ft.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},f={t,...p,distanceM:c,...o?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=H(async()=>{const{BodyEditor:e}=await import("./BodyEditor-COLTBHzX.js");return{BodyEditor:e}},[],import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,bodySelected:()=>this.bodiesEventsPanel.render(),said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},duration:()=>this.ufoElement.seekableDuration,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,s)=>this.sceneElement.groundAlong(t,i,s)},this.language),this.bodyEditor)),this.bodyEditorLoading}openSkyParts(){return[...this.skyParts.values()].filter(e=>!e.panel.hidden)}wantedSkyParts(){const e=mc.kinds().filter(i=>i.editor).map(i=>({key:`interpretation:${i.key}`,id:`interpretation-${i.key}`,category:"interpretation",kind:i,titles:i.messages,create:()=>i.editor().then(s=>n=>s(n,{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),shapes:()=>this.bodyShapeIds().map(r=>({id:r,label:this.shapeLabel(r)})),currentTime:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,seekTo:r=>this.goToMark(r),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language))})),t=Nf.map(i=>sa.of(i)).filter(i=>i.editor).map(i=>({key:`skyEvent:${i.key}`,id:`sky-event-${i.key}`,category:"skyEvent",kind:i,titles:i.messages,create:()=>i.editor().then(s=>n=>s(n,{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),currentTime:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,seekTo:r=>this.goToMark(r),pointAt:(r,a)=>{this.headingInput.value=String(this.rounded(r)),this.pitchInput.value=String(this.rounded(a)),this.updateObserver()},changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language))}));return[...e,...t]}buildSkyParts(){const e=this.shadow.getElementById("weather-tabs"),t=this.shadow.getElementById("sky-event-parts");if(!e||!t)return;const i=this.wantedSkyParts();for(const[s,n]of this.skyParts)if(!i.some(r=>r.key===s&&r.kind===n.kind)){if(n.tab.getAttribute("aria-expanded")==="true"){const r=this.subgroupTabs.find(a=>a.parentElement===e&&a!==n.tab);r&&this.openSubgroup(r)}n.tab.remove(),n.panel.remove(),this.subgroupTabs.splice(this.subgroupTabs.indexOf(n.tab),1),this.skyParts.delete(s)}for(const s of i){if(this.skyParts.has(s.key))continue;const n=document.createElement("button");n.className="subgroup-tab",n.type="button",n.setAttribute("aria-controls",s.id),n.setAttribute("aria-expanded","false");const r=document.createElement("span");r.id=`label-${s.id}`,this.nameSkyPart(r,s.titles),n.append(r),n.addEventListener("click",()=>this.openSubgroup(n)),e.append(n),this.subgroupTabs.push(n);const a=document.createElement("section");a.className="subgroup-panel",a.id=s.id,a.hidden=!0,a.setAttribute("aria-labelledby",r.id);const o=document.createElement("div");o.className="toolbar";const c=document.createElement("div");c.id=`${s.id}-editor`,o.append(c),a.append(o),t.before(a),this.skyParts.set(s.key,{...s,tab:n,label:r,panel:a})}for(const s of i){const n=this.skyParts.get(s.key);e.append(n.tab),t.before(n.panel)}}applyPerceptionLabels(){const e=this.decidedLanguage;if(e===void 0)return;const t=[...new Set(za.ALL.map(i=>i.messages))];Promise.all(t.map(i=>i.load(e))).then(i=>{this.decidedLanguage===e&&(this.perceptionSettings.labels=Object.assign({},...i))},()=>{})}nameSkyPart(e,t){const i=this.decidedLanguage;i!==void 0&&t.load(i).then(s=>{this.decidedLanguage===i&&(e.textContent=s.title)},()=>{})}loadSkyPartEditor(e){return e.loading??=e.create().then(t=>(e.editor=t(e.panel.querySelector(`#${e.id}-editor`)),e.editor)),e.loading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const n=i===void 0||i<=0?void 0:Ft.sizeMAt(e.distanceM,i);this.realWidthInput.value=n===void 0?"":this.plain(n,n<1?2:n<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const s={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=s.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,s=Qr.of(i.instrument,Ft.CANVAS_HEIGHT_PX,Li.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const a=Li.aimOf(i,e,r.shape.bounds),o=s.ofBounds(r.shape.bounds),{aim:c,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:o}:{...h,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.ufoElement.sighting.timeline.sourceIds.length>0&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const s=/^ufo-(\d+)$/.exec(e);return s?`${this.messages.shape} ${s[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;this.currentSourceId=this.newSourceIds(1)[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}newSourceIds(e){const t=this.ufoElement.sighting.timeline,i=[];t.sourceIds.length===0&&this.currentSourceId!==void 0&&i.push(this.currentSourceId);const s=new Set([...t.sourceIds,this.currentSourceId]);let n=s.size+1;for(;i.length<e;){for(;s.has(`ufo-${n}`);)n++;i.push(`ufo-${n}`),s.add(`ufo-${n}`)}return i}shapeAddKinds(){const e=this.messages,t={triangle:e.modelTriangle,saucer:e.modelSaucer,cigar:e.modelCigar,chevron:e.modelChevron,light:e.modelLight};return[{value:"oval",label:e.oval},{value:"polygon",label:e.polygon},...ec.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),s=e.shapesIn(i,this.currentAppearance),n=this.newSourceIds(s.length),r=this.shapeAddKinds().find(h=>h.value===e.id).label,a=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",o={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},c=s.map((h,d)=>{const u=e.partNames[d],p=u?`${r} ${a}, ${o[u]}`:`${r} ${a}`;return{sourceId:n[d],shape:{...h,title:this.said.write(void 0,p,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,c),n.length>1&&t.group(n),this.currentSourceId=n[n.length-1],this.selectedSourceIds=new Set(n),this.refreshSourceList(),this.ufoElement.refresh()}duplicateSelected(){if(this.hideContextMenu(),this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(r=>this.selectedSourceIds.has(r));if(t.length===0)return;const i=this.newSourceIds(t.length),s=24;for(const r of e.allKeyframes){const a=r.shapes.filter(o=>t.includes(o.sourceId)).map(o=>{const{bounds:c}=o.shape;return{sourceId:i[t.indexOf(o.sourceId)],shape:{...o.shape,bounds:{...c,x:c.x+s,y:c.y+s}}}});a.length>0&&this.commitShapes(r.t,a)}const n=e.groupMembers(t[0]);t.length>1&&n?.length===t.length&&t.every(r=>n.includes(r))&&e.group(i),this.currentSourceId=i[i.length-1],this.selectedSourceIds=new Set(i),this.refreshSourceList(),this.ufoElement.refresh()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??mp,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const s=document.createElement("option");s.value=i,s.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(s)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const s=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorList.kindLabel(e.kind)} ${s}`}addOwnAircraft(){this.addDecor("aircraft"),this.revealDecorPanel()}addDecor(e=this.decorList.pickedKind??"building"){this.observerAdded=e==="observer";const t=this.ufoElement.sighting,s={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="trafficlight"?{lights:Iu.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Tu}:{},windows:Q3(e)};t.decor=[...t.decor,s],this.currentDecorId=s.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(s.id,e)}readSceneryChoice(){try{return localStorage.getItem(ge.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(ge.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(ge.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(ge.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await H(()=>import("./surroundingsSources-z7680fTA.js"),[],import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const s=document.createElement("option");s.value=ge.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=a.credit,o}),r=new Option(this.messages.sourceFile,ge.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(s,...n,r),this.surveyIds=t.map(a=>a.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==ge.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?ge.FILE_SOURCE:this.sceneryChoice===ge.NO_SCENERY?ge.NO_SCENERY:this.surveyIds.includes(this.sceneryChoice??"")?this.sceneryChoice:this.defaultSurveyId??this.surveyIds[0]),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-radius-row").hidden=e||this.sceneryChoice===ge.NO_SCENERY;const t=this.shadow.getElementById("scenery-file-link");t.hidden=!e,e&&(t.textContent=this.sectionFilePanel.itemLabel("decor"),t.title=this.sectionFilePanel.where("decor"))}setDecorFromFile(e){const t=this.ufoElement.sighting;if(this.sectionFromFile("decor")===e)return;const i={...t.snapshots??{}};e?i.decor=i.decor??{}:delete i.decor,t.snapshots=us.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?Eg.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const s=this.ufoElement.sighting.decor.find(n=>n.id===e);!s||s.model||s.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(n=>n.id===e?{...n,model:{id:i.id},sizeM:i.sizeM}:n),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleModuleNaming())}defaultAircraft(){const e=2*ky,t=Math.round(e/$B*1e3);return{lights:Iu.byId("airliner")?.create(),track:[{t:0,eastM:-ky,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:ky,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(s=>s.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=Rf(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(s=>{this.drawnEntryAsked!==i||!s||(this.drawnEntry=s,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const s=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=i!==""?i:s?mg[s.kind]?.id:void 0;return n!==void 0?this.decorModelProvider.entry(n).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):s===void 0?void 0:{decorKind:s.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(s=>{const n=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);s.model={url:i.url,credit:n!==void 0&&r!==void 0?{title:n,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,s]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),n=this.ufoElement.sighting.decor.find(o=>o.id===e.id);if(!n||n.model?.id!==t||!s?.sizeM)return;const r=n.sizeM!==void 0&&i?.sizeM!==void 0&&n.sizeM.widthM===i.sizeM.widthM&&n.sizeM.lengthM===i.sizeM.lengthM&&n.sizeM.heightM===i.sizeM.heightM;if(n.sizeM&&!r)return;const a={...n.sizeM,...Object.fromEntries(Object.entries(s.sizeM).filter(([,o])=>o!==void 0).map(([o,c])=>[o,this.roundedMeters(c)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(s=>s.t===e)||(t.milestones=bh([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(s=>s.t===e);i&&(t.milestones=t.milestones.filter(s=>s.t!==i.t),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh())}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=bh(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;Ln.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=ge.OBSERVER_PRINCIPAL,t=this.ufoElement.sighting.decor.filter(s=>s.kind==="observer");this.currentDecorId!==void 0&&t.some(s=>s.id===this.currentDecorId)&&this.observerAdded&&(this.observerShown=this.currentDecorId),this.observerAdded=!1,t.some(s=>s.id===this.observerShown)||(this.observerShown=e),this.observerList.setItems([{id:e,label:this.principalObserverLabel()},...t.map(s=>({id:s.id,label:this.decorLabel(s)}))],this.observerShown);const i=this.observerShown!==e;this.observerList.setRemoveEnabled(i),this.observerList.setActionEnabled("look-at-observer",i),this.placeDecorItem()}principalObserverLabel(){const e=[this.observerTitleInput.value,this.observerFirstNamesInput.value,this.observerLastNameInput.value].map(t=>t.trim()).filter(Boolean).join(" ");return e===""?this.messages.principalObserver:`${e} (${this.messages.principalObserver.toLowerCase()})`}observerAdded=!1;selectObserver(e){this.observerShown=e,e!==ge.OBSERVER_PRINCIPAL&&this.selectDecor(e),this.refreshObserverList()}placeDecorItem(){const e=this.shadow.getElementById("decor-item"),t=this.shadow.getElementById("observer-decor-host"),i=this.shadow.getElementById("observer-principal");if(!e||!t||!i)return;const s=this.observerShown!==ge.OBSERVER_PRINCIPAL;if(i.hidden=s,s&&this.isGroupIdOpen("group-observer")){e.parentElement!==t&&t.append(e),e.hidden=!1;return}e.parentElement===t&&this.shadow.getElementById("decor-list-header").after(e),e.hidden=this.decorList.value===""}syncDecorFields(){this.syncDecorVisibility()}async findGhosts(){const e=this.currentReference();if(e?.src){this.searchingGhosts=!0,this.syncFindGhosts(e);try{const{GhostSearchView:t}=await H(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([50,35]),import.meta.url),i=this.messages,s={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},n=await new t(this.ghostsStatus,s).search(e.src);this.ghostFinding=n&&n.pairs.length>0?{referenceId:e.id,src:e.src,search:n}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t||e?.kind==="video",this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}syncFilmStocks(e,t){const i=pc.forInstrument(t);this.setRowVisible(this.filmStockSelect,i.length>0);const s=e.event.time?.year??void 0,n=`${t.id}|${s}|${e.film}|${this.messages.filmStockAny}`;if(this.filmStockKey===n)return;this.filmStockKey=n,this.filmStockSelect.innerHTML="";const r=(o,c,h=!1)=>{const d=document.createElement("option");d.value=o,d.textContent=c,d.disabled=h,this.filmStockSelect.appendChild(d)};r("",this.messages.filmStockAny);const a=i.map(o=>({stock:o,gap:pc.gap(o,t,s)}));for(const{stock:o}of a.filter(c=>!c.gap))r(o.id,o.name);for(const{stock:o,gap:c}of a.filter(h=>h.gap)){const h=c.kind==="before"?this.messages.filmStockNotYet.replace("{from}",String(c.from)):this.messages.filmStockNoLonger.replace("{to}",String(c.to));r(o.id,`${o.name} (${h})`,o.id!==e.film)}this.filmStockSelect.value=e.film??""}filmStockKey;updateExposureSettings(){const e=this.ufoElement.sighting;e.iso=this.numberOrUndefined(this.isoInput.value),e.film=this.filmStockSelect.value||void 0,this.isoInput.placeholder=String(pc.byId(e.film)?.iso??e.instrument.medium?.iso??"");const t=this.meteringSelect.value;e.metering=t==="average"||t==="highlights"?t:void 0,this.meteringSelect.disabled=e.iso!==void 0,this.ufoElement.refresh()}updateLens(){const e=this.lensGlassSelect.value,t={...e?{glass:e}:{},drops:this.numberOrUndefined(this.lensDropsInput.value),condensation:this.numberOrUndefined(this.lensCondensationInput.value),dirt:this.numberOrUndefined(this.lensDirtInput.value),...this.lensShelteredInput.checked?{sheltered:!0}:{}};for(const i of["drops","condensation","dirt"])t[i]===void 0&&delete t[i];this.ufoElement.sighting.lens=Object.keys(t).length>0?t:void 0,this.ufoElement.refresh()}label(e,t){const i=this.shadow.getElementById(e);i&&(i.textContent=t)}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}decorBaseShownFor;showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1,this.decorBaseShownFor=void 0;return}const t=this.decorBaseShownFor!==e.id;if(this.decorBaseShownFor=e.id,this.decorBaseShown){this.decorBaseForm.sync(t),this.decorStateForm.sync(t);return}this.decorBaseShown=!0;const i=()=>new Il(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?Ba.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(bc.resolve(Xr.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(bc.resolve(Xr.STATE,this.decorParameterTexts),i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const s of this.ufoElement.sighting.decor){if(s.id===e)continue;const{eastM:n,northM:r}=ia(s,t);i.push({id:s.id,label:this.decorLabel(s),eastM:n,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(n=>n.id!==void 0)};const s=JSON.stringify(this.observerSaid??null);s!==this.observerSaidShown&&(this.observerSaidShown=s,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const s of e)t===void 0||t==="stated"?i.clear(s):i.set(s,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=yh.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:pe.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:yh.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:Xr.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:mg[e.kind]?.id}}placedByAuthor(e){if(!e.lamp?.supposed)return e;const t=this.sceneElement.decorDrawnOffset(e.id),{supposed:i,...s}=e.lamp,n={...e,eastM:e.eastM+(t?.eastM??0),northM:e.northM+(t?.northM??0),...Object.keys(s).length>0?{lamp:s}:{}};Object.keys(s).length===0&&delete n.lamp;const r=this.ufoElement.sighting;return r.decor=r.decor.map(a=>a.id===e.id?n:a),n}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId);if(!i)return;const s=t==="eastM"||t==="northM"?this.placedByAuthor(i):i;if((t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const n=this.ufoElement.currentTime,r=Ba.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(c=>c.id===s.id?Ba.apply(c,r,t,n):c),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const o=a.decor.find(c=>c.id===s.id);t==="title"&&this.decorList.rename(o.id,this.decorLabel(o)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?Ai.of(e,this.publishedParametersOf(e)):void 0,i=t&&bc.resolve(t,this.decorParameterTexts);if(!e||!i){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const s=`${e.id}|${i.kind}|${i.parameters.map(a=>a.key).join(",")}`;if(s===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=s;const n=e.id,r=new Il(()=>this.ufoElement.sighting.decor.find(a=>a.id===n),a=>{const o=this.ufoElement.sighting;o.decor=o.decor.map(c=>{if(c.id!==n)return c;const h=structuredClone(c);return a(h),h})});this.decorParameterForm.show(i,r,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++,this.meteorMagnitudeLimit());e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;meteorMagnitudeLimit(){const e=this.ufoElement.sighting,t=this.observerAtStart(),i=e.event.time?.year!==void 0?Js(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=Di("Sun",i,t).altitudeDeg;return mo(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Dr;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Wg;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new Bs(["en"]);tagNames=new j1({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){if(!this.worded)return;this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,s=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?Js(i,t.lng,e.event.utcOffsetHours):void 0,n=JSON.stringify([s?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,_s(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey,e.skySources]);if(n===this.skyCandidatesKey)return;if(this.skyCandidatesKey=n,!s||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},a=e.skySources!==!1,o=[this.starsClause(s,r),a?this.showerClause(s,r):this.messages.skyByHand,this.cometClause(s,r),this.novaClause(s,r),this.eclipseClause(s,r),this.moonClause(s,r),a?this.satelliteClause(s,r):void 0,a?this.reentryClause(s,r):void 0,a?this.fireballClause(s,r):void 0,this.opticsClause(s,r),this.rainbowClause(s,r),this.glowClause(s,r)].filter(c=>c!==void 0);a||(this.showMeteorButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0),this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · ")),this.labelSkyButtons()}labelSkyButtons(){const e=this.messages,t=[[this.showMeteorButton,e.showMeteor,e.noMeteor],[this.showCometButton,e.showComet,e.noComet],[this.showNovaButton,e.showNova,e.noNova],[this.showSatelliteButton,e.showSatellite,e.noSatellite],[this.showFireballButton,e.showFireball,e.noFireball]];for(const[i,s,n]of t){const r=i.disabled?n:s;i.title=r,i.setAttribute("aria-label",r)}}instrumentGain(){const e=this.ufoElement.sighting;return wn.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Li.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Di("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=mo(i,s,n),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<BB)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,c=Math.abs(s)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(s>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(o)).replace("{gain}",a(Math.abs(s))).replace("{eye}",a(mo(i,0,n)));return r<=Vp?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(Vp))}showerClause(e,t){const i=ls.observedRatePerHour(ls.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=uu.activeAt(e);if(s.length===0)return this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyNothingActive.replace("{sporadic}",i);const n=s.map(r=>{const a=uu.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:uu.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.rate-r.rate)[0];return n.rate<=0?(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(n.entry.shower))):(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerActive.replace("{name}",this.naming.shower(n.entry.shower)).replace("{altitude}",String(Math.round(n.position.altitudeDeg))).replace("{bearing}",this.naming.towards(n.position.azimuthDeg)).replace("{rate}",n.rate.toLocaleString(void 0,{maximumFractionDigits:n.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=Y0.brightestAt(e,t);if(!i||i.magnitude>Du){this.showCometButton.disabled=!0;return}return this.showCometButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.cometText(i)}novaClause(e,t){const i=$g.brightestAt(e,t);if(!i||i.magnitude>Du){this.showNovaButton.disabled=!0;return}return this.showNovaButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.novaText(i)}eclipseClause(e,t){const i=Is.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=Di("Sun",i.peak,t),n=r=>r.replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return n(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Di("Moon",e,t);if(i.altitudeDeg<=0||Yl(e).illuminatedFraction<.97)return;const s=[],n=er.distanceKm(e,t),r=er.relativeToMean(er.radiusAtKm(n)),a=n<=er.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=er.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&s.push(a.replace("{distance}",(Math.round(n/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(er.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Yg.isIn(e)&&s.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),s.length>0?s.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=Oa.visibilityAt(e,t),s=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(s!==void 0)return s;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const n=mo(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=n),a=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",a);const o=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",o).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",a):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),s=i+this.satelliteSpanMs(),n=[i,s,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==n){const c={key:n,status:"loading"};this.reentries=c,ge.reentryArchive.candidates(i,s,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=Oa.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(a.length===0)return;const o=a.slice(0,3).map(c=>this.reentryText(c));return a.length>3&&o.push(this.messages.skyReentriesMore.replace("{count}",String(a.length-3))),this.messages.skyReentries.replace("{list}",o.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,s=new Date(e.timeMs);if(t.precision==="day"){const a=s.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}const n=this.observerClock(s).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",n).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",n).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",n)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(c=>c.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(c=>c.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses();if(this.showSatelliteButton.disabled=this.aimableSatellitePasses(i).length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const n=i[0].peak,a=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",n.object.name).replace("{magnitude}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg)).replace("{time}",this.observerClock(n.date)),o=this.starlinkTrain(i);return o?`${a}, ${o}`:a}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const s=i.peak.magnitude;if(s===void 0)return!1;const n=Di("Sun",i.peak.date,t);return s<=mo(n.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,s)=>i.peak.magnitude-s.peak.magnitude)}aimableSatellitePasses(e){return e.filter(t=>this.passTimelineMs(t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(t.peak.altitudeDeg,t.peak.azimuthDeg))}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:a,launch:o}=r.peak.object;a!=="starlink"||!o||(r.peak.date.getTime()-Date.parse(`${o}T00:00:00Z`))/864e5>60||t.set(o,(t.get(o)??0)+1)}const[i,s]=[...t.entries()].sort((r,a)=>a[1]-r[1])[0]??[];if(!i||!s||s<3)return;const n=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(s)).replace("{date}",n)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=et(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=Js(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(s=>`${s.object.norad}@${s.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>va.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=va.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,s)=>i.magnitude-s.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,s=i.from[2]-i.to[2],n=Math.abs(s)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/s));return i.t-t.getTime()+n*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const s=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",s.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(s.record.t))).replace("{altitude}",String(Math.round(s.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(s.peak.azimuthDeg)).replace("{distance}",String(Math.round(s.peak.distanceKm/10)*10)).replace("{stations}",String(s.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const s=Js(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=this.aimableFireballs(this.strikingFireballs(s,this.observerAtStart()),s);if(n.length===0)return;const r=n[this.fireballRank++%n.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,s),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=_s(this.ufoElement.sighting,0),s=Di("Sun",e,t),n=Di("Moon",e,t),r=Et.deckLitUntilDeg(Et.DECK_HEIGHT_M),a=s.altitudeDeg>-r,o=a?s:n;if(o.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(Et.strength(c,i.lowerCloudCover??i.cloudCover,o.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(Et.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??eg;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=_s(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=Di("Sun",e,t),n=Di("Moon",e,t),r=s.altitudeDeg>0,a=r?s:n;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const o=i.lowerCloudCover??i.cloudCover;if(qn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=qn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(qn.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Yl(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Di("Sun",e,t);if(i.altitudeDeg>ZB)return;const s=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),n=[];if(s.milkyWay&&n.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(s.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(s.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(s.milkyWay.azimuthDeg))),s.zodiacal){const p=s.zodiacal.sunSeparationDeg<=ni.CONE_SEPARATION_DEG;n.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(s.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(s.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(s.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(s.zodiacal.sunSeparationDeg))))}if(n.length>0)return this.listed(n);const r=this.decimal(s.darkestSkyMagPerArcsec2,1),a=Di("Moon",e,t),o=s.darkestSkyMagPerArcsec2<JB,c=this.ufoElement.sighting.lightPollution,h=fe.scatteringAt(90-a.altitudeDeg)*fe.moonOutput(fe.phaseAngleOf(Yl(e).illuminatedFraction),a.altitudeDeg)*fe.scatteredFraction(90),d=fe.artificialZenithNanolamberts(c)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(Yl(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=fe.artificialZenithNanolamberts(c)>fe.twilightExcessNanolamberts(i.altitudeDeg);return o&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):o?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Di("Sun",e,t),s=Di("Moon",e,t);return fe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:fe.phaseAngleOf(Yl(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new ni;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<Y0.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=Js(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Y0.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=Js(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=$g.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId);if(!e)return;const t=this.sceneElement.directionToDecor(e.id);if(t){this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver();return}const{eastM:i,northM:s,altitudeM:n}=ia(e,this.ufoElement.currentTime),r=Math.hypot(i,s);if(r===0&&n===0)return;const a=Math.atan2(i,s)*180/Math.PI,o=Math.atan2(n-WB-(et(this.ufoElement.sighting,this.ufoElement.currentTime)?.elevationM??0),r)*180/Math.PI;this.headingInput.value=String(Math.round(a*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??ge.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return fE(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Ed.width/2,y:e.height/2-Ed.height/2,width:Ed.width,height:Ed.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new GM(this.ufoElement.sighting.timeline,new qU(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t),this.recordButton.querySelector(".record-label")||this.recordButton.replaceChildren(Object.assign(document.createElement("span"),{className:"record-icon"}),Object.assign(document.createElement("span"),{className:"record-label"})),de.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=zs.preferencesFor(this);this.preferences=t;const i=Wa(t,Ga),s=this.decidedLanguage===void 0;if(this.decidedLanguage=i,s){for(const d of this.skyParts.values())this.nameSkyPart(d.label,d.titles);this.applyPerceptionLabels()}const n=this.narrativeProvider.localize?.(i),[r,a,o,c]=await Promise.all([Tw.load(i),i==="en"?{}:G_(i),bT(i),l8.load(i)]);if(await n,e!==this.localeToken)return;const h=i!==this.language;this.language=i,this.decorParameterTexts=c,this.naming=new Wg(o),this.said=new Bs(t),this.tagNames=new j1(a),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new Qc(r,this.naming,this.said,this.tagNames,{messages:r,locale:this.language},this.decorParameterTexts),this.refreshParamSummary()),h?this.showSaidTexts():this.showTags()}preferences=[];decidedLanguage;language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.worded=!0,this.currentSourceId===mp&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.sayLoadError(),this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.sourceSelect.setAttribute("aria-label",e.shape),this.shadow.getElementById("shape-empty").textContent=e.emptyShapes,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder;const t=(n,r,a)=>{this.shadow.getElementById(n).setAttribute(r,a),r==="title"&&this.fieldHints.set(n,a)};t("observerAge","placeholder",e.observerAgeUnit),t("observerOccupation","placeholder",e.observerOccupationExample),t("roll","title",e.rollHint),t("utcOffsetHours","title",e.utcOffsetHint),t("highCloudCover","title",e.highCloudCoverHint),t("cloudBase","title",e.cloudBaseHint),t("windDirection","title",e.windDirectionHint),t("soundPitch","title",e.soundPitchHint),t("brightness","title",e.brightnessHint),t("blur","title",e.blurHint),t("apparentWidth","title",e.apparentWidthHint),t("realWidth","title",e.realWidthHint),t("objectDistance","title",e.objectDistanceHint),t("sizeLock","title",e.sizeLockHint),this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.shadow.getElementById("label-shape-rotation").textContent=e.shapeRotation,this.shapeRotationInput.title=e.shapeRotationTitle,this.labelSizeLock.textContent=e.sizeLock;for(const[n,r]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=r;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.samplingRateInput.placeholder=String(ge.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(ge.DEFAULT_SAMPLE_MS)),this.labelDuration.textContent=e.duration,this.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.shadow.getElementById("label-account-compare").textContent=e.accountCompare,this.shadow.getElementById("account-compare-row").title=e.accountCompareHint;const i=this.shadow.getElementById("scene-resize");i&&(i.title=e.resizeScene,i.setAttribute("aria-label",e.resizeScene)),this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextDuplicateButton.textContent=e.duplicate,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.exportKmlButton.textContent=e.exportKml,this.exportKmlButton.title=e.exportKmlHint,this.exportGeoJsonButton.textContent=e.exportGeoJson,this.exportGeoJsonButton.title=e.exportGeoJsonHint,this.snapshotsPanel.localize(e),this.sectionFilePanel.localize(e),this.eventsPanel.localize(e.events),this.phenomenonEventsPanel.localize(e.events),this.bodiesEventsPanel.localize(e.events),this.aroundPanel.localize(e.around,{title:e.events.basisTitle,basis:e.events.basis,basisField:e.events.basisField,howField:e.events.howField,rationaleField:e.events.rationaleField}),this.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,this.labelImportFile.textContent=e.importFile,this.shadow.getElementById("label-whole-keyframes").textContent=e.wholeKeyframes,this.wholeKeyframesInput.closest("label").title=e.wholeKeyframesHint,this.importInput.placeholder=e.importUrlPlaceholder;for(const n of this.shadow.querySelectorAll(Vf))n.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.applyPerceptionLabels(),this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,Qs.say(this.labelAccountUrl,e.accountUrl,e.accountUrlHint),this.labelAccountFollowedUp.textContent=e.accountFollowedUp,this.evaluationFields.messages=e.accountEvaluation;for(const[n,r]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const a=this.shadow.getElementById(n);a&&(a.textContent=r)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.label("label-film-stock",e.filmStock),this.filmStockKey=void 0,this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.label("label-sky-sources",e.skySources),this.skySourcesInput.closest("label").title=e.skySourcesHint,this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"peak",label:e.decorPeak},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const s=this.shadow.getElementById("option-scenery-none");s&&(s.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[n,r]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=r,n.setAttribute("aria-label",r);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.decorBaseShownFor=void 0,this.decorBaseShown=!1,this.decorParametersShownFor=void 0,this.isConnected&&this.syncDecorVisibility(),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup;for(const n of this.skyParts.values())this.nameSkyPart(n.label,n.titles);for(const n of["location","decor","weather"]){const r=this.shadow.getElementById(`${n}-settings-button`);r?.setAttribute("title",e.dataSources),r?.setAttribute("aria-label",e.dataSources);const a=this.shadow.getElementById(`label-${n}-settings`);a&&(a.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language);for(const n of this.skyParts.values())n.editor?.setLanguage(this.language);this.modulesPanel?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new Qc(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language},this.decorParameterTexts),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.shadow.getElementById("label-aircraft-group").textContent=e.aircraftGroup,this.aircraftFlights.show(this.sceneElement.aircraftFlights,e,!0),this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.referenceKindSelect.querySelector("#reference-kind-video").textContent=e.referenceVideo,this.shadow.getElementById("label-reference-video-from").textContent=e.referenceVideoFrom,this.shadow.getElementById("label-reference-video-to").textContent=e.referenceVideoTo,this.shadow.getElementById("label-reference-video-rate").textContent=e.referenceVideoRate,this.referenceRemoveKeyButton.textContent=e.referenceRemoveKey,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=this.currentReference()?.kind==="video"?e.referenceVideoT:e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,Qs.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,r]of this.soundKindOptions)r.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e),this.refreshFileItems(),this.refreshSkyCandidates()}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])vr.popover(this.shadow.getElementById(s),e.close);vr.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),vr.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),vr.button(this.contextMenu,e.close,()=>this.hideContextMenu()),vr.button(this.decorContextMenu,e.close,()=>this.hideDecorContextMenu()),this.shadow.getElementById("label-editor-kicker").textContent=e.editorKicker,this.shadow.getElementById("label-save").textContent=e.save,this.shareDialog.useLanguage(this.language).then(s=>{s&&(this.shareMessages=s,this.shadow.getElementById("label-share").textContent=s.share,this.refreshEditorHead())});const i={observation:e.panelIntroObservation,observer:e.panelIntroObserver,location:e.panelIntroLocation,temporal:e.panelIntroTemporal,decor:e.panelIntroDecor,weather:e.panelIntroWeather,shape:e.panelIntroShape,sound:e.panelIntroSound,reference:e.panelIntroReference,file:e.panelIntroFile};for(const[s,n]of Object.entries(i)){const r=this.shadow.querySelector(`[aria-controls="group-${s}"]`);r.dataset.intro=n,ge.titleGroupTab(r)}this.refreshEditorHead()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const s=this.decorMoveAxis(e);if(i==="decor"&&s&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,s))return;const n=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const d=new Cb(this.selectedMembers()),u=ai.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=n.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?ai.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&ai.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const c=this.ufoElement.shapeAt(t.x,t.y,_0);if(!c){const d=s==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),a||!o)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===c.sourceId?c.shape:n.getInterpolatedShapeAt(r,d)??c.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(n=>this.selectedSourceIds.has(n))){if(i.length>=this.selectedSourceIds.size)return;for(const n of i)this.selectedSourceIds.delete(n);if(!this.selectedSourceIds.has(this.currentSourceId)){const n=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,a)=>n.indexOf(r)-n.indexOf(a)).pop()}}else{for(const n of i)this.selectedSourceIds.add(n);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,n=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(s,this.currentSourceId):void 0,a=n?.kind==="polygon"&&ai.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,_0);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const o=this.pickDecorAt(e),c=o?this.ufoElement.sighting.decor.find(h=>h.id===o):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(e.clientX-i.left)/i.width*2-1,n=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(s,n)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,s=i.filter(p=>this.selectedSourceIds.has(p)),n=i.length<=s.length,r=s.length>0&&i.slice(i.length-s.length).every(p=>this.selectedSourceIds.has(p)),a=s.length>0&&i.slice(0,s.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=n||r,this.contextSendToBackButton.disabled=n||a,this.contextBringToFrontButton.title=n?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=n?this.messages.onlyOneShape:a?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const o=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!o,this.contextUngroupButton.title=o?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?ai.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=mI;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const s=document.createElement("span");s.className="submenu-empty",s.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(s)}for(const s of t){const n=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(s)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,s,r.checked)),n.appendChild(r),n.appendChild(document.createTextNode(this.shapeLabel(s))),this.contextMasksSubmenu.appendChild(n)}for(const s of i){const n=this.sceneElement.bodyMaskedBy(s.id,e.id);if(n===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(s.title)??s.id,o=this.messages;r.textContent=`${a} — ${n>=.995?o.masksBodyFully:n>.005?o.masksBodyPartly.replace("{share}",String(Math.round(n*100))):o.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}updateDecorOccludesShape(e,t,i){const s=this.ufoElement.sighting;s.decor=s.decor.map(n=>{if(n.id!==e)return n;const r=i?[...new Set([...n.occludesSourceIds??[],t])]:(n.occludesSourceIds??[]).filter(a=>a!==t);return{...n,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const s=ai.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const s=ai.hitTestVertex(i,e);if(s===void 0)return;const n=ai.deleteVertex(i,s);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,s,n){this.dragState={kind:e,sourceId:t,original:i,handle:n,startPointer:s},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!s||!i)return!1;i.show(s);const n=i.readingNow(),r=this.skyDirectionOf(e);return!n||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:n.azimuthDeg,bodyAltitudeDeg:n.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const s=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+s,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(D0,(e.maxX-e.minX)/2*t.width),s=Math.max(D0,(e.maxY-e.minY)/2*t.height),n=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return this.withinReach({x:n-i/2,y:r-s/2,width:i,height:s})}withinReach(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),s=i.height>0?t.height/i.height:1,r=[this.shadow.querySelector(".playback-row"),this.ufoElement.shadowRoot?.querySelector(".controls")].map(m=>m?.getBoundingClientRect()).filter(m=>m!==void 0&&m.height>0&&m.top<i.bottom&&m.bottom>i.top).reduce((m,g)=>Math.max(m,(i.bottom-g.top)*s),0),a=k0,o=k0+NB,c=t.width-k0,h=t.height-r-k0,d=Math.max(e.x,a),u=Math.max(e.y,o),p=Math.min(e.x+e.width,c),f=Math.min(e.y+e.height,h);return p-d<D0||f-u<D0?e:{x:d,y:u,width:p-d,height:f-u}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),s=e.reading();if(!i||!s)return!1;const n=ai.hitTestHandle({bounds:i,angle:0},t);if(!n)return!1;if(n==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...s.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:n,centre:r,startPointer:t,startSizeM:{...s.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:s,startPointer:n,startSizeM:r,handle:a}=t,o=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=a==="e"||a==="w",h=a==="n"||a==="s",d=c?o(i.x-s.x,n.x-s.x):h?o(i.y-s.y,n.y-s.y):o(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:Dy};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:HB};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=pe.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:Ba.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!s||!i||(e.preventDefault(),i.show(s),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const s=this.pickDecorAt(e);if(s===i.id)return!0;const n=this.decorCanvasBounds();return n!==void 0&&t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+n.height?s===void 0||this.ufoElement.sighting.decor.find(a=>a.id===s)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const s=this.editableDecor();if(!s)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.ufoElement.shapeAt(t.x,t.y,_0)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=Ba.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),a=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,o=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,a);return!n||!o?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:o,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:n.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(s.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const s=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!s&&t.axis!=="up"||this.commitDecorBase(n=>{s&&(t.axis==="ground"||t.axis==="east")&&(n.eastM=this.roundedMeters(t.startEastM+s.x-t.startGround.x)),s&&(t.axis==="ground"||t.axis==="north")&&(n.northM=this.roundedMeters(t.startNorthM-(s.z-t.startGround.z))),t.axis==="up"&&(n.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const s=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:s?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:s?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:s},this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Tl(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Tl(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:s,startPointer:n}=this.dragState,r=t.x-n.x,a=t.y-n.y,o=s.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+a}}}));this.commitShapes(i,o)}else if(this.dragState.kind==="group-resize"){const{group:s,handle:n}=this.dragState;this.commitShapes(i,s.resize(n,t))}else if(this.dragState.kind==="group-rotate"){const{group:s,startPointer:n}=this.dragState;this.commitShapes(i,s.rotate(t,n))}else if(this.dragState.kind==="vertex"){const{sourceId:s,original:n,vertexIndex:r}=this.dragState,a=ai.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:a}])}else{const{kind:s,sourceId:n,original:r,handle:a}=this.dragState,o=s==="resize"?ai.resizeShape(r,a,t):ai.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:s,startPitchDeg:n,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<GB)return;this.cameraDragState.moved=!0}const a=s+(t.x-i.x)*Dy,o=Math.max(-90,Math.min(90,n-(t.y-i.y)*Dy));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=o,this.sceneElement.setIndoorLook(a,o),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver(),this.rounded(a)!==this.rounded(s)&&(this.cameraDragState.headingTurned=!0),this.rounded(o)!==this.rounded(n)&&(this.cameraDragState.pitchTurned=!0),this.showOrientation(this.cameraDragState.headingTurned?a:void 0,this.cameraDragState.pitchTurned?o:void 0),this.showViewDragHint(e.altKey);const c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=c.allKeyframes.find(u=>u.t===h);d&&d.viewOnly===!0!==e.altKey&&(c.setViewOnly(h,e.altKey),this.ufoElement.refresh())}showViewDragHint(e){const t=this.shadow.getElementById("view-drag-hint");t&&(t.hidden=e===void 0,e!==void 0&&(t.textContent=e?this.messages.viewDragHintHeld:this.messages.viewDragHint,t.toggleAttribute("data-held",e)))}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}if(!this.dragState&&!this.cameraDragState)return;const e=this.cameraDragState&&!this.cameraDragState.insideDecor;this.showViewDragHint(void 0),this.dragState=void 0,this.cameraDragState=void 0,e&&this.refreshSceneField(),this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp)}walkOrTurn(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing"||this.isObserverInsideDecor())return;const t=e.shiftKey?YB:1,i=this.numberOrUndefined(this.headingInput.value)??0;if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.headingInput.value=String(this.rounded(i+(e.key==="ArrowRight"?1:-1)*XB*t)),this.updateObserver();return}const s=this.numberOrUndefined(this.latInput.value),n=this.numberOrUndefined(this.lngInput.value);if(s===void 0||n===void 0)return;const r=(e.key==="ArrowUp"?1:-1)*KB*t,a=i*Math.PI/180,o=wr(Math.sin(a)*r,-Math.cos(a)*r,s,n);this.latInput.value=o.lat.toFixed(7),this.lngInput.value=o.lng.toFixed(7);const c=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(c,this.plantingCentre()),this.surroundings.walked(o.lat,o.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=lt(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(o,c)=>Math.round((o-c)*1e3)/1e3,a=this.ufoElement.sighting;a.decor=a.decor.map(o=>({...o,eastM:r(o.eastM,s),northM:r(o.northM,n),...o.track?{track:o.track.map(c=>({...c,eastM:r(c.eastM,s),northM:r(c.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ul,i.width-Bc);break;case"ArrowRight":i.width+=Bc;break;case"ArrowUp":i.height=Math.max(ul,i.height-Bc);break;case"ArrowDown":i.height+=Bc;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Bc;break;case"ArrowRight":i.x+=Bc;break;case"ArrowUp":i.y-=Bc;break;case"ArrowDown":i.y+=Bc;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:s,shape:n}=i[0];this.commitShapes(t,[{sourceId:s,shape:{...n,bounds:this.nudgeBounds(n.bounds,e)}}])}else{const s=new Cb(i),n=this.nudgeBounds(s.bounds(),e);this.commitShapes(t,s.scaleTo(n))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),s=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const o=r?this.bodyCanvasBounds():void 0,c=o&&ai.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const o=this.decorCanvasBounds(),c=o&&ai.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&!this.ufoElement.shapeAt(t.x,t.y,_0)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=ai.hitTestHandle({bounds:new Cb(this.selectedMembers()).bounds(),angle:0},t);if(o)return this.cursorForHandle(o,0)}else{const o=s.getInterpolatedShapeAt(n,this.currentSourceId);if(o?.kind==="polygon"&&ai.hitTestVertex(o,t)!==void 0)return"vertex";const c=o&&ai.hitTestHandle(o,t);if(o&&c)return this.cursorForHandle(c,o.angle)}return s.hitTest(n,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${ai.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),s=e.clientX-i.left,n=e.clientY-i.top;this.recorder?.onPointerMove(s,n),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(e3(this.buildPrototype({x:0,y:0,width:Ed.width,height:Ed.height}),s,n))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const QB={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},mT="rr0-sighting-editor";function m_(){lI(),MM(),d_(),eB(),JU(),nB(),yv(),customElements.get(mT)||customElements.define(mT,ge)}const g_="rr0-read",ez="rr0-edit",mh="in-place",tz="rr0-mode";class iz{static ask(e,t,i){const s=new CustomEvent(t,{detail:i,bubbles:!0,composed:!0,cancelable:!0});return e.dispatchEvent(s),s.defaultPrevented}}class $M{constructor(e,t,i=()=>{}){this.place=e,this.changed=i,t&&this.adopt(t)}reader;editor;handed;get reading(){return this.reader!==void 0}get editorLoaded(){return this.editor!==void 0}adopt(e){this.editor=e,e.switcher=this,e.hasAttribute(mh)||e.setAttribute(mh,""),e.addEventListener(g_,t=>{t.preventDefault();const i=t.detail;this.handed=i.src,this.read(i)})}async read({src:e,track:t}){const[{register:i,CASE_ELEMENT_NAME:s,OPEN_EVENTS_ATTRIBUTE:n},{registerSighting:r,SIGHTING_ELEMENT_NAME:a}]=await Promise.all([H(()=>import("./CaseElement-DzwFIDZZ.js"),__vite__mapDeps([51,52]),import.meta.url),H(()=>import("./SightingElement-BfxNhmfn.js"),[],import.meta.url)]);r(),i();const o=Vi.isCase(vs.read(e)??await ba.json(e)),c=document.createElement(o?s:a);c.setAttribute(mh,""),o&&t&&c.setAttribute(n,$M.fileKey(t)),c.setAttribute("src",e),c.addEventListener(ez,h=>{h.preventDefault(),this.edit(h.detail)}),this.reader?.remove(),this.place(c),this.editor&&(this.editor.hidden=!0),this.reader=c,this.changed({mode:"read",src:e,...t?{track:t}:{}})}async edit(e){const t=this.editor;if(t){if(this.dropReader(),vs.releaseCopies(),t.hidden=!1,this.changed({mode:"edit"}),e?.src!==void 0&&e.src!==this.handed){this.load(t,e.src,e.track);return}e?.track&&await t.openTrack(e.track);return}const{register:i,CASE_EDITOR_ELEMENT_NAME:s}=await H(async()=>{const{register:r,CASE_EDITOR_ELEMENT_NAME:a}=await Promise.resolve().then(()=>nz);return{register:r,CASE_EDITOR_ELEMENT_NAME:a}},void 0,import.meta.url);i();const n=document.createElement(s);this.adopt(n),e?.track&&n.setAttribute("track",e.track),e?.src&&n.setAttribute("src",e.src),this.dropReader(),this.place(n),this.changed({mode:"edit"})}async open(e){const t=this.editor;if(this.reading||!t)return this.read({src:e});this.load(t,e)}load(e,t,i){this.handed=void 0,i?e.setAttribute("track",i):e.removeAttribute("track"),e.setAttribute("src",t)}async startNew(){const e=this.editor;if(!e)return this.edit();this.reading&&await this.edit(),e.askBeforeReplacing(()=>{e.remove(),this.editor=void 0,this.edit()})}dropReader(){this.reader?.remove(),this.reader=void 0}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}}const Aw="rr0-case-editor",sz=`
|
|
12303
|
+
`)}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const n of e){const r=ge.QUESTION_FIELDS[n];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const o=this.shadow.getElementById(a);o&&!o.hidden&&o.value===""&&t.add(a)}}for(const[n,r]of Object.entries(ge.QUESTION_FIELDS))for(const a of ge.QUESTION_FIELDS[n].fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=t.has(a)&&!o.classList.contains("missing-required");o.classList.toggle("wanted",c),(c||o.title===this.messages.questionUnanswered)&&(o.title=c?this.messages.questionUnanswered:this.fieldHints.get(a)??"")}const i=new Map;let s;for(const[n,r]of Object.entries(ge.QUESTION_FIELDS))for(const a of r.fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=o.classList.contains("missing-required");!c&&!o.classList.contains("wanted")||(c&&(s=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const n of this.groupTabs){const r=this.panelOf(n),a=i.get(r)??0,o=r===s,c=ge.badgeOn(n);c.hidden=a===0,c.textContent=String(a),c.classList.toggle("optional",!o);const h=a===0?void 0:o?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a));h?n.dataset.unanswered=h:delete n.dataset.unanswered,ge.titleGroupTab(n)}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field,e.detail&&(t.title=e.detail);const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const n=document.createElement("span");n.className="param-chip-swatch",n.style.background=e.color,t.append(n)}const s=document.createElement("span");return s.className="param-chip-value",s.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(s),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const s=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const n=t.dataset.field;if(n.startsWith("shape:")){this.selectedSourceIds=new Set([n.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(n.startsWith("body:")){const a=this.subgroupTabs.find(o=>o.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(o=>o.show(n.slice(5)));return}if(n.startsWith("decor:")){this.currentDecorId=n.slice(6),this.refreshDecorList(),this.decorList.focus();return}const r=this.shadow.getElementById(n);r===null||!s.contains(r)||(this.revealSubgroupOf(r),this.sectionFolds.reveal(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.showAircraftFlights(),this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe();for(const i of this.openSkyParts())i.editor?.setTime?.(this.ufoElement.currentTime);for(const i of[this.eventsPanel,this.phenomenonEventsPanel,this.bodiesEventsPanel])i?.setTime(this.ufoElement.currentTime);this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.samplingRateInput!==this.shadow.activeElement&&(this.samplingRateInput.value=this.ufoElement.sighting.sampleMs===void 0?"":String(this.ufoElement.sighting.sampleMs)),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.getElementById("shape-row");t&&Ln.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=e?t:this.fieldHints.get(i.id)??""}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:jB(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.shadow.activeElement!==this.shapeRotationInput&&(this.shapeRotationInput.value=String(ge.rotationDeg(e.angle))),this.refreshApparentSize())}static rotationDeg(e){const t=(e*180/Math.PI%360+540)%360-180;return Math.round((t===-180?180:t)*10)/10}updateShapeRotation(){const e=this.numberOrUndefined(this.shapeRotationInput.value);if(e===void 0)return;const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);s&&(this.commitShapes(i,[{sourceId:this.currentSourceId,shape:{...s,angle:e*Math.PI/180}}]),this.ufoElement.refresh())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,Ft.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,Ft.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(Ft.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(Ft.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!s)return;const n=this.currentProjection(),r=n.degToPx(e),a=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),o={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-a)/2,width:r,height:a},c=n.ofBounds(o),h=s.kind==="oval"?{...s,bounds:o,angular:c}:{...s,bounds:o,angular:c,points:this.scalePoints(s,o)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,s=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(n=>({x:n.x*i,y:n.y*s}))}refreshFilterOptions(){const e={[is.NONE.id]:this.messages.filterNone,[is.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[is.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==is.ALL.length||is.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||is.NONE.id;this.filterSelect.replaceChildren();for(const r of is.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=n}const s=this.ufoElement?.sighting?.instrument;for(const n of this.filterSelect.options){const r=!s||is.usableWith(is.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,s={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,video:this.messages.instrumentCategoryVideo,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},n=r=>{const a=this.naming.instrument(r),o=Vt.unavailability(r,t);if(!o)return{id:r.id,label:a};const c=(o.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(o.from)).replace("{to}",String(o.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:c}:{id:r.id,label:a,disabledReason:c}};this.instrumentSelect.choices=Vt.CATEGORIES.map(r=>({label:s[r],children:bp.filter(a=>a.category===r).map(n)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=ge.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const n=Number(i[1]),r=Number(i[2]);return r>0?n/r:void 0}const s=Number(t);return Number.isFinite(s)&&s>0?s:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=et(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??Vt.fieldOfViewDeg(t),r=s?Vt.focalLengthMmFor(t,n):n;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=s?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=s?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=s!==void 0&&s.focalRangeMm===void 0,this.focalLengthInput.min=String(s?s.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(s?s.focalRangeMm?.maxMm??2e3:179),rn.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=s&&n!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(n,n<10?1:0)):"";const a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const o=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":ge.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const d of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(d,zt.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const c=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const h=pc.byId(e.film);this.isoInput.placeholder=c?c.autoExposure?"auto":String(h?.iso??c.iso):"",this.setRowVisible(this.isoInput,c!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,c?.autoExposure===!0),this.meteringSelect.disabled=e.iso!==void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,s!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=is.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Vt.fieldOfViewDeg(e),s=Vt.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>VB||t.observerTrack.addKeyframe(n.t,{...n.pose,fovDeg:s})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,s=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!s){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(s.max,Math.max(s.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return et(e,this.ufoElement.currentTime)?.fovDeg??Vt.fieldOfViewDeg(e.instrument)}currentProjection(){return Qr.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=Ft.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const s=et(this.ufoElement.sighting,this.ufoElement.currentTime),n=s?.focusDistanceM;if(n!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(n));return}const r=(s?Vt.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,a=s?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const o=this.ufoElement.canvasElement.height;if(o<=0)return;const c=2*q1*e/o*i.heightMm,h=r*r/(a*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const s=this.numberOrUndefined(this.realWidthInput.value),n=s!==void 0&&(t!==void 0&&s<t||i!==void 0&&s>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),a=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+a+n;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+n}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),s=(m,g)=>Number(m.toFixed(g)),n=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??FB,a=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),o=a!==void 0&&a<r,c=s(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:s(Ft.sizeMAt(c,h),2),lengthM:s(Ft.sizeMAt(c,h),2),heightM:s(Ft.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},f={t,...p,distanceM:c,...o?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=H(async()=>{const{BodyEditor:e}=await import("./BodyEditor-COLTBHzX.js");return{BodyEditor:e}},[],import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,bodySelected:()=>this.bodiesEventsPanel.render(),said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},duration:()=>this.ufoElement.seekableDuration,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,s)=>this.sceneElement.groundAlong(t,i,s)},this.language),this.bodyEditor)),this.bodyEditorLoading}openSkyParts(){return[...this.skyParts.values()].filter(e=>!e.panel.hidden)}wantedSkyParts(){const e=mc.kinds().filter(i=>i.editor).map(i=>({key:`interpretation:${i.key}`,id:`interpretation-${i.key}`,category:"interpretation",kind:i,titles:i.messages,create:()=>i.editor().then(s=>n=>s(n,{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),shapes:()=>this.bodyShapeIds().map(r=>({id:r,label:this.shapeLabel(r)})),currentTime:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,seekTo:r=>this.goToMark(r),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language))})),t=Nf.map(i=>sa.of(i)).filter(i=>i.editor).map(i=>({key:`skyEvent:${i.key}`,id:`sky-event-${i.key}`,category:"skyEvent",kind:i,titles:i.messages,create:()=>i.editor().then(s=>n=>s(n,{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),currentTime:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,seekTo:r=>this.goToMark(r),pointAt:(r,a)=>{this.headingInput.value=String(this.rounded(r)),this.pitchInput.value=String(this.rounded(a)),this.updateObserver()},changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language))}));return[...e,...t]}buildSkyParts(){const e=this.shadow.getElementById("weather-tabs"),t=this.shadow.getElementById("sky-event-parts");if(!e||!t)return;const i=this.wantedSkyParts();for(const[s,n]of this.skyParts)if(!i.some(r=>r.key===s&&r.kind===n.kind)){if(n.tab.getAttribute("aria-expanded")==="true"){const r=this.subgroupTabs.find(a=>a.parentElement===e&&a!==n.tab);r&&this.openSubgroup(r)}n.tab.remove(),n.panel.remove(),this.subgroupTabs.splice(this.subgroupTabs.indexOf(n.tab),1),this.skyParts.delete(s)}for(const s of i){if(this.skyParts.has(s.key))continue;const n=document.createElement("button");n.className="subgroup-tab",n.type="button",n.setAttribute("aria-controls",s.id),n.setAttribute("aria-expanded","false");const r=document.createElement("span");r.id=`label-${s.id}`,this.nameSkyPart(r,s.titles),n.append(r),n.addEventListener("click",()=>this.openSubgroup(n)),e.append(n),this.subgroupTabs.push(n);const a=document.createElement("section");a.className="subgroup-panel",a.id=s.id,a.hidden=!0,a.setAttribute("aria-labelledby",r.id);const o=document.createElement("div");o.className="toolbar";const c=document.createElement("div");c.id=`${s.id}-editor`,o.append(c),a.append(o),t.before(a),this.skyParts.set(s.key,{...s,tab:n,label:r,panel:a})}for(const s of i){const n=this.skyParts.get(s.key);e.append(n.tab),t.before(n.panel)}}applyPerceptionLabels(){const e=this.decidedLanguage;if(e===void 0)return;const t=[...new Set(za.ALL.map(i=>i.messages))];Promise.all(t.map(i=>i.load(e))).then(i=>{this.decidedLanguage===e&&(this.perceptionSettings.labels=Object.assign({},...i))},()=>{})}nameSkyPart(e,t){const i=this.decidedLanguage;i!==void 0&&t.load(i).then(s=>{this.decidedLanguage===i&&(e.textContent=s.title)},()=>{})}loadSkyPartEditor(e){return e.loading??=e.create().then(t=>(e.editor=t(e.panel.querySelector(`#${e.id}-editor`)),e.editor)),e.loading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const n=i===void 0||i<=0?void 0:Ft.sizeMAt(e.distanceM,i);this.realWidthInput.value=n===void 0?"":this.plain(n,n<1?2:n<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const s={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=s.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,s=Qr.of(i.instrument,Ft.CANVAS_HEIGHT_PX,Li.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const a=Li.aimOf(i,e,r.shape.bounds),o=s.ofBounds(r.shape.bounds),{aim:c,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:o}:{...h,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.ufoElement.sighting.timeline.sourceIds.length>0&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const s=/^ufo-(\d+)$/.exec(e);return s?`${this.messages.shape} ${s[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;this.currentSourceId=this.newSourceIds(1)[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}newSourceIds(e){const t=this.ufoElement.sighting.timeline,i=[];t.sourceIds.length===0&&this.currentSourceId!==void 0&&i.push(this.currentSourceId);const s=new Set([...t.sourceIds,this.currentSourceId]);let n=s.size+1;for(;i.length<e;){for(;s.has(`ufo-${n}`);)n++;i.push(`ufo-${n}`),s.add(`ufo-${n}`)}return i}shapeAddKinds(){const e=this.messages,t={triangle:e.modelTriangle,saucer:e.modelSaucer,cigar:e.modelCigar,chevron:e.modelChevron,light:e.modelLight};return[{value:"oval",label:e.oval},{value:"polygon",label:e.polygon},...ec.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),s=e.shapesIn(i,this.currentAppearance),n=this.newSourceIds(s.length),r=this.shapeAddKinds().find(h=>h.value===e.id).label,a=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",o={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},c=s.map((h,d)=>{const u=e.partNames[d],p=u?`${r} ${a}, ${o[u]}`:`${r} ${a}`;return{sourceId:n[d],shape:{...h,title:this.said.write(void 0,p,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,c),n.length>1&&t.group(n),this.currentSourceId=n[n.length-1],this.selectedSourceIds=new Set(n),this.refreshSourceList(),this.ufoElement.refresh()}duplicateSelected(){if(this.hideContextMenu(),this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(r=>this.selectedSourceIds.has(r));if(t.length===0)return;const i=this.newSourceIds(t.length),s=24;for(const r of e.allKeyframes){const a=r.shapes.filter(o=>t.includes(o.sourceId)).map(o=>{const{bounds:c}=o.shape;return{sourceId:i[t.indexOf(o.sourceId)],shape:{...o.shape,bounds:{...c,x:c.x+s,y:c.y+s}}}});a.length>0&&this.commitShapes(r.t,a)}const n=e.groupMembers(t[0]);t.length>1&&n?.length===t.length&&t.every(r=>n.includes(r))&&e.group(i),this.currentSourceId=i[i.length-1],this.selectedSourceIds=new Set(i),this.refreshSourceList(),this.ufoElement.refresh()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??mp,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const s=document.createElement("option");s.value=i,s.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(s)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const s=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorList.kindLabel(e.kind)} ${s}`}addOwnAircraft(){this.addDecor("aircraft"),this.revealDecorPanel()}addDecor(e=this.decorList.pickedKind??"building"){this.observerAdded=e==="observer";const t=this.ufoElement.sighting,s={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="trafficlight"?{lights:Iu.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Tu}:{},windows:Q3(e)};t.decor=[...t.decor,s],this.currentDecorId=s.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(s.id,e)}readSceneryChoice(){try{return localStorage.getItem(ge.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(ge.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(ge.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(ge.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await H(()=>import("./surroundingsSources-z7680fTA.js"),[],import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const s=document.createElement("option");s.value=ge.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=a.credit,o}),r=new Option(this.messages.sourceFile,ge.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(s,...n,r),this.surveyIds=t.map(a=>a.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==ge.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?ge.FILE_SOURCE:this.sceneryChoice===ge.NO_SCENERY?ge.NO_SCENERY:this.surveyIds.includes(this.sceneryChoice??"")?this.sceneryChoice:this.defaultSurveyId??this.surveyIds[0]),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-radius-row").hidden=e||this.sceneryChoice===ge.NO_SCENERY;const t=this.shadow.getElementById("scenery-file-link");t.hidden=!e,e&&(t.textContent=this.sectionFilePanel.itemLabel("decor"),t.title=this.sectionFilePanel.where("decor"))}setDecorFromFile(e){const t=this.ufoElement.sighting;if(this.sectionFromFile("decor")===e)return;const i={...t.snapshots??{}};e?i.decor=i.decor??{}:delete i.decor,t.snapshots=us.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?Eg.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const s=this.ufoElement.sighting.decor.find(n=>n.id===e);!s||s.model||s.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(n=>n.id===e?{...n,model:{id:i.id},sizeM:i.sizeM}:n),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleModuleNaming())}defaultAircraft(){const e=2*ky,t=Math.round(e/$B*1e3);return{lights:Iu.byId("airliner")?.create(),track:[{t:0,eastM:-ky,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:ky,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(s=>s.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=Rf(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(s=>{this.drawnEntryAsked!==i||!s||(this.drawnEntry=s,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const s=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=i!==""?i:s?mg[s.kind]?.id:void 0;return n!==void 0?this.decorModelProvider.entry(n).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):s===void 0?void 0:{decorKind:s.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(s=>{const n=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);s.model={url:i.url,credit:n!==void 0&&r!==void 0?{title:n,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,s]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),n=this.ufoElement.sighting.decor.find(o=>o.id===e.id);if(!n||n.model?.id!==t||!s?.sizeM)return;const r=n.sizeM!==void 0&&i?.sizeM!==void 0&&n.sizeM.widthM===i.sizeM.widthM&&n.sizeM.lengthM===i.sizeM.lengthM&&n.sizeM.heightM===i.sizeM.heightM;if(n.sizeM&&!r)return;const a={...n.sizeM,...Object.fromEntries(Object.entries(s.sizeM).filter(([,o])=>o!==void 0).map(([o,c])=>[o,this.roundedMeters(c)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(s=>s.t===e)||(t.milestones=bh([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(s=>s.t===e);i&&(t.milestones=t.milestones.filter(s=>s.t!==i.t),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh())}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=bh(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;Ln.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=ge.OBSERVER_PRINCIPAL,t=this.ufoElement.sighting.decor.filter(s=>s.kind==="observer");this.currentDecorId!==void 0&&t.some(s=>s.id===this.currentDecorId)&&this.observerAdded&&(this.observerShown=this.currentDecorId),this.observerAdded=!1,t.some(s=>s.id===this.observerShown)||(this.observerShown=e),this.observerList.setItems([{id:e,label:this.principalObserverLabel()},...t.map(s=>({id:s.id,label:this.decorLabel(s)}))],this.observerShown);const i=this.observerShown!==e;this.observerList.setRemoveEnabled(i),this.observerList.setActionEnabled("look-at-observer",i),this.placeDecorItem()}principalObserverLabel(){const e=[this.observerTitleInput.value,this.observerFirstNamesInput.value,this.observerLastNameInput.value].map(t=>t.trim()).filter(Boolean).join(" ");return e===""?this.messages.principalObserver:`${e} (${this.messages.principalObserver.toLowerCase()})`}observerAdded=!1;selectObserver(e){this.observerShown=e,e!==ge.OBSERVER_PRINCIPAL&&this.selectDecor(e),this.refreshObserverList()}placeDecorItem(){const e=this.shadow.getElementById("decor-item"),t=this.shadow.getElementById("observer-decor-host"),i=this.shadow.getElementById("observer-principal");if(!e||!t||!i)return;const s=this.observerShown!==ge.OBSERVER_PRINCIPAL;if(i.hidden=s,s&&this.isGroupIdOpen("group-observer")){e.parentElement!==t&&t.append(e),e.hidden=!1;return}e.parentElement===t&&this.shadow.getElementById("decor-list-header").after(e),e.hidden=this.decorList.value===""}syncDecorFields(){this.syncDecorVisibility()}async findGhosts(){const e=this.currentReference();if(e?.src){this.searchingGhosts=!0,this.syncFindGhosts(e);try{const{GhostSearchView:t}=await H(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([50,35]),import.meta.url),i=this.messages,s={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},n=await new t(this.ghostsStatus,s).search(e.src);this.ghostFinding=n&&n.pairs.length>0?{referenceId:e.id,src:e.src,search:n}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t||e?.kind==="video",this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}syncFilmStocks(e,t){const i=pc.forInstrument(t);this.setRowVisible(this.filmStockSelect,i.length>0);const s=e.event.time?.year??void 0,n=`${t.id}|${s}|${e.film}|${this.messages.filmStockAny}`;if(this.filmStockKey===n)return;this.filmStockKey=n,this.filmStockSelect.innerHTML="";const r=(o,c,h=!1)=>{const d=document.createElement("option");d.value=o,d.textContent=c,d.disabled=h,this.filmStockSelect.appendChild(d)};r("",this.messages.filmStockAny);const a=i.map(o=>({stock:o,gap:pc.gap(o,t,s)}));for(const{stock:o}of a.filter(c=>!c.gap))r(o.id,o.name);for(const{stock:o,gap:c}of a.filter(h=>h.gap)){const h=c.kind==="before"?this.messages.filmStockNotYet.replace("{from}",String(c.from)):this.messages.filmStockNoLonger.replace("{to}",String(c.to));r(o.id,`${o.name} (${h})`,o.id!==e.film)}this.filmStockSelect.value=e.film??""}filmStockKey;updateExposureSettings(){const e=this.ufoElement.sighting;e.iso=this.numberOrUndefined(this.isoInput.value),e.film=this.filmStockSelect.value||void 0,this.isoInput.placeholder=String(pc.byId(e.film)?.iso??e.instrument.medium?.iso??"");const t=this.meteringSelect.value;e.metering=t==="average"||t==="highlights"?t:void 0,this.meteringSelect.disabled=e.iso!==void 0,this.ufoElement.refresh()}updateLens(){const e=this.lensGlassSelect.value,t={...e?{glass:e}:{},drops:this.numberOrUndefined(this.lensDropsInput.value),condensation:this.numberOrUndefined(this.lensCondensationInput.value),dirt:this.numberOrUndefined(this.lensDirtInput.value),...this.lensShelteredInput.checked?{sheltered:!0}:{}};for(const i of["drops","condensation","dirt"])t[i]===void 0&&delete t[i];this.ufoElement.sighting.lens=Object.keys(t).length>0?t:void 0,this.ufoElement.refresh()}label(e,t){const i=this.shadow.getElementById(e);i&&(i.textContent=t)}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}decorBaseShownFor;showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1,this.decorBaseShownFor=void 0;return}const t=this.decorBaseShownFor!==e.id;if(this.decorBaseShownFor=e.id,this.decorBaseShown){this.decorBaseForm.sync(t),this.decorStateForm.sync(t);return}this.decorBaseShown=!0;const i=()=>new Il(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?Ba.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(bc.resolve(Xr.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(bc.resolve(Xr.STATE,this.decorParameterTexts),i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const s of this.ufoElement.sighting.decor){if(s.id===e)continue;const{eastM:n,northM:r}=ia(s,t);i.push({id:s.id,label:this.decorLabel(s),eastM:n,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(n=>n.id!==void 0)};const s=JSON.stringify(this.observerSaid??null);s!==this.observerSaidShown&&(this.observerSaidShown=s,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const s of e)t===void 0||t==="stated"?i.clear(s):i.set(s,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=yh.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:pe.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:yh.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:Xr.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:mg[e.kind]?.id}}placedByAuthor(e){if(!e.lamp?.supposed)return e;const t=this.sceneElement.decorDrawnOffset(e.id),{supposed:i,...s}=e.lamp,n={...e,eastM:e.eastM+(t?.eastM??0),northM:e.northM+(t?.northM??0),...Object.keys(s).length>0?{lamp:s}:{}};Object.keys(s).length===0&&delete n.lamp;const r=this.ufoElement.sighting;return r.decor=r.decor.map(a=>a.id===e.id?n:a),n}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId);if(!i)return;const s=t==="eastM"||t==="northM"?this.placedByAuthor(i):i;if((t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const n=this.ufoElement.currentTime,r=Ba.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(c=>c.id===s.id?Ba.apply(c,r,t,n):c),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const o=a.decor.find(c=>c.id===s.id);t==="title"&&this.decorList.rename(o.id,this.decorLabel(o)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?Ai.of(e,this.publishedParametersOf(e)):void 0,i=t&&bc.resolve(t,this.decorParameterTexts);if(!e||!i){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const s=`${e.id}|${i.kind}|${i.parameters.map(a=>a.key).join(",")}`;if(s===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=s;const n=e.id,r=new Il(()=>this.ufoElement.sighting.decor.find(a=>a.id===n),a=>{const o=this.ufoElement.sighting;o.decor=o.decor.map(c=>{if(c.id!==n)return c;const h=structuredClone(c);return a(h),h})});this.decorParameterForm.show(i,r,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++,this.meteorMagnitudeLimit());e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;meteorMagnitudeLimit(){const e=this.ufoElement.sighting,t=this.observerAtStart(),i=e.event.time?.year!==void 0?Js(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=Di("Sun",i,t).altitudeDeg;return mo(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Dr;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Wg;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new Bs(["en"]);tagNames=new j1({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){if(!this.worded)return;this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,s=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?Js(i,t.lng,e.event.utcOffsetHours):void 0,n=JSON.stringify([s?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,_s(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey,e.skySources]);if(n===this.skyCandidatesKey)return;if(this.skyCandidatesKey=n,!s||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},a=e.skySources!==!1,o=[this.starsClause(s,r),a?this.showerClause(s,r):this.messages.skyByHand,this.cometClause(s,r),this.novaClause(s,r),this.eclipseClause(s,r),this.moonClause(s,r),a?this.satelliteClause(s,r):void 0,a?this.reentryClause(s,r):void 0,a?this.fireballClause(s,r):void 0,this.opticsClause(s,r),this.rainbowClause(s,r),this.glowClause(s,r)].filter(c=>c!==void 0);a||(this.showMeteorButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0),this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · ")),this.labelSkyButtons()}labelSkyButtons(){const e=this.messages,t=[[this.showMeteorButton,e.showMeteor,e.noMeteor],[this.showCometButton,e.showComet,e.noComet],[this.showNovaButton,e.showNova,e.noNova],[this.showSatelliteButton,e.showSatellite,e.noSatellite],[this.showFireballButton,e.showFireball,e.noFireball]];for(const[i,s,n]of t){const r=i.disabled?n:s;i.title=r,i.setAttribute("aria-label",r)}}instrumentGain(){const e=this.ufoElement.sighting;return wn.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Li.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Di("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=mo(i,s,n),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<BB)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,c=Math.abs(s)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(s>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(o)).replace("{gain}",a(Math.abs(s))).replace("{eye}",a(mo(i,0,n)));return r<=Vp?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(Vp))}showerClause(e,t){const i=ls.observedRatePerHour(ls.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=uu.activeAt(e);if(s.length===0)return this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyNothingActive.replace("{sporadic}",i);const n=s.map(r=>{const a=uu.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:uu.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.rate-r.rate)[0];return n.rate<=0?(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(n.entry.shower))):(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerActive.replace("{name}",this.naming.shower(n.entry.shower)).replace("{altitude}",String(Math.round(n.position.altitudeDeg))).replace("{bearing}",this.naming.towards(n.position.azimuthDeg)).replace("{rate}",n.rate.toLocaleString(void 0,{maximumFractionDigits:n.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=Y0.brightestAt(e,t);if(!i||i.magnitude>Du){this.showCometButton.disabled=!0;return}return this.showCometButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.cometText(i)}novaClause(e,t){const i=$g.brightestAt(e,t);if(!i||i.magnitude>Du){this.showNovaButton.disabled=!0;return}return this.showNovaButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.novaText(i)}eclipseClause(e,t){const i=Is.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=Di("Sun",i.peak,t),n=r=>r.replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return n(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Di("Moon",e,t);if(i.altitudeDeg<=0||Yl(e).illuminatedFraction<.97)return;const s=[],n=er.distanceKm(e,t),r=er.relativeToMean(er.radiusAtKm(n)),a=n<=er.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=er.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&s.push(a.replace("{distance}",(Math.round(n/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(er.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Yg.isIn(e)&&s.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),s.length>0?s.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=Oa.visibilityAt(e,t),s=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(s!==void 0)return s;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const n=mo(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=n),a=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",a);const o=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",o).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",a):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),s=i+this.satelliteSpanMs(),n=[i,s,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==n){const c={key:n,status:"loading"};this.reentries=c,ge.reentryArchive.candidates(i,s,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=Oa.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(a.length===0)return;const o=a.slice(0,3).map(c=>this.reentryText(c));return a.length>3&&o.push(this.messages.skyReentriesMore.replace("{count}",String(a.length-3))),this.messages.skyReentries.replace("{list}",o.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,s=new Date(e.timeMs);if(t.precision==="day"){const a=s.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}const n=this.observerClock(s).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",n).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",n).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",n)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(c=>c.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(c=>c.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses();if(this.showSatelliteButton.disabled=this.aimableSatellitePasses(i).length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const n=i[0].peak,a=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",n.object.name).replace("{magnitude}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg)).replace("{time}",this.observerClock(n.date)),o=this.starlinkTrain(i);return o?`${a}, ${o}`:a}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const s=i.peak.magnitude;if(s===void 0)return!1;const n=Di("Sun",i.peak.date,t);return s<=mo(n.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,s)=>i.peak.magnitude-s.peak.magnitude)}aimableSatellitePasses(e){return e.filter(t=>this.passTimelineMs(t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(t.peak.altitudeDeg,t.peak.azimuthDeg))}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:a,launch:o}=r.peak.object;a!=="starlink"||!o||(r.peak.date.getTime()-Date.parse(`${o}T00:00:00Z`))/864e5>60||t.set(o,(t.get(o)??0)+1)}const[i,s]=[...t.entries()].sort((r,a)=>a[1]-r[1])[0]??[];if(!i||!s||s<3)return;const n=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(s)).replace("{date}",n)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=et(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=Js(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(s=>`${s.object.norad}@${s.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>va.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=va.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,s)=>i.magnitude-s.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,s=i.from[2]-i.to[2],n=Math.abs(s)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/s));return i.t-t.getTime()+n*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const s=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",s.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(s.record.t))).replace("{altitude}",String(Math.round(s.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(s.peak.azimuthDeg)).replace("{distance}",String(Math.round(s.peak.distanceKm/10)*10)).replace("{stations}",String(s.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const s=Js(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=this.aimableFireballs(this.strikingFireballs(s,this.observerAtStart()),s);if(n.length===0)return;const r=n[this.fireballRank++%n.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,s),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=_s(this.ufoElement.sighting,0),s=Di("Sun",e,t),n=Di("Moon",e,t),r=Et.deckLitUntilDeg(Et.DECK_HEIGHT_M),a=s.altitudeDeg>-r,o=a?s:n;if(o.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(Et.strength(c,i.lowerCloudCover??i.cloudCover,o.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(Et.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??eg;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=_s(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=Di("Sun",e,t),n=Di("Moon",e,t),r=s.altitudeDeg>0,a=r?s:n;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const o=i.lowerCloudCover??i.cloudCover;if(qn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=qn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(qn.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Yl(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Di("Sun",e,t);if(i.altitudeDeg>ZB)return;const s=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),n=[];if(s.milkyWay&&n.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(s.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(s.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(s.milkyWay.azimuthDeg))),s.zodiacal){const p=s.zodiacal.sunSeparationDeg<=ni.CONE_SEPARATION_DEG;n.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(s.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(s.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(s.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(s.zodiacal.sunSeparationDeg))))}if(n.length>0)return this.listed(n);const r=this.decimal(s.darkestSkyMagPerArcsec2,1),a=Di("Moon",e,t),o=s.darkestSkyMagPerArcsec2<JB,c=this.ufoElement.sighting.lightPollution,h=fe.scatteringAt(90-a.altitudeDeg)*fe.moonOutput(fe.phaseAngleOf(Yl(e).illuminatedFraction),a.altitudeDeg)*fe.scatteredFraction(90),d=fe.artificialZenithNanolamberts(c)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(Yl(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=fe.artificialZenithNanolamberts(c)>fe.twilightExcessNanolamberts(i.altitudeDeg);return o&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):o?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Di("Sun",e,t),s=Di("Moon",e,t);return fe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:fe.phaseAngleOf(Yl(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new ni;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<Y0.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=Js(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Y0.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=Js(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=$g.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId);if(!e)return;const t=this.sceneElement.directionToDecor(e.id);if(t){this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver();return}const{eastM:i,northM:s,altitudeM:n}=ia(e,this.ufoElement.currentTime),r=Math.hypot(i,s);if(r===0&&n===0)return;const a=Math.atan2(i,s)*180/Math.PI,o=Math.atan2(n-WB-(et(this.ufoElement.sighting,this.ufoElement.currentTime)?.elevationM??0),r)*180/Math.PI;this.headingInput.value=String(Math.round(a*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??ge.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return fE(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Ed.width/2,y:e.height/2-Ed.height/2,width:Ed.width,height:Ed.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new GM(this.ufoElement.sighting.timeline,new qU(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t),this.recordButton.querySelector(".record-label")||this.recordButton.replaceChildren(Object.assign(document.createElement("span"),{className:"record-icon"}),Object.assign(document.createElement("span"),{className:"record-label"})),de.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=zs.preferencesFor(this);this.preferences=t;const i=Wa(t,Ga),s=this.decidedLanguage===void 0;if(this.decidedLanguage=i,s){for(const d of this.skyParts.values())this.nameSkyPart(d.label,d.titles);this.applyPerceptionLabels()}const n=this.narrativeProvider.localize?.(i),[r,a,o,c]=await Promise.all([Tw.load(i),i==="en"?{}:G_(i),bT(i),l8.load(i)]);if(await n,e!==this.localeToken)return;const h=i!==this.language;this.language=i,this.decorParameterTexts=c,this.naming=new Wg(o),this.said=new Bs(t),this.tagNames=new j1(a),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new Qc(r,this.naming,this.said,this.tagNames,{messages:r,locale:this.language},this.decorParameterTexts),this.refreshParamSummary()),h?this.showSaidTexts():this.showTags()}preferences=[];decidedLanguage;language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.worded=!0,this.currentSourceId===mp&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.sayLoadError(),this.shapeAddMenu.setKinds(this.shapeAddKinds()),this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.sourceSelect.setAttribute("aria-label",e.shape),this.shadow.getElementById("shape-empty").textContent=e.emptyShapes,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder;const t=(n,r,a)=>{this.shadow.getElementById(n).setAttribute(r,a),r==="title"&&this.fieldHints.set(n,a)};t("observerAge","placeholder",e.observerAgeUnit),t("observerOccupation","placeholder",e.observerOccupationExample),t("roll","title",e.rollHint),t("utcOffsetHours","title",e.utcOffsetHint),t("highCloudCover","title",e.highCloudCoverHint),t("cloudBase","title",e.cloudBaseHint),t("windDirection","title",e.windDirectionHint),t("soundPitch","title",e.soundPitchHint),t("brightness","title",e.brightnessHint),t("blur","title",e.blurHint),t("apparentWidth","title",e.apparentWidthHint),t("realWidth","title",e.realWidthHint),t("objectDistance","title",e.objectDistanceHint),t("sizeLock","title",e.sizeLockHint),this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.shadow.getElementById("label-shape-rotation").textContent=e.shapeRotation,this.shapeRotationInput.title=e.shapeRotationTitle,this.labelSizeLock.textContent=e.sizeLock;for(const[n,r]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=r;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.samplingRateInput.placeholder=String(ge.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(ge.DEFAULT_SAMPLE_MS)),this.labelDuration.textContent=e.duration,this.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.shadow.getElementById("label-account-compare").textContent=e.accountCompare,this.shadow.getElementById("account-compare-row").title=e.accountCompareHint;const i=this.shadow.getElementById("scene-resize");i&&(i.title=e.resizeScene,i.setAttribute("aria-label",e.resizeScene)),this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextDuplicateButton.textContent=e.duplicate,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.exportKmlButton.textContent=e.exportKml,this.exportKmlButton.title=e.exportKmlHint,this.exportGeoJsonButton.textContent=e.exportGeoJson,this.exportGeoJsonButton.title=e.exportGeoJsonHint,this.snapshotsPanel.localize(e),this.sectionFilePanel.localize(e),this.eventsPanel.localize(e.events),this.phenomenonEventsPanel.localize(e.events),this.bodiesEventsPanel.localize(e.events),this.aroundPanel.localize(e.around,{title:e.events.basisTitle,basis:e.events.basis,basisField:e.events.basisField,howField:e.events.howField,rationaleField:e.events.rationaleField}),this.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,this.labelImportFile.textContent=e.importFile,this.shadow.getElementById("label-whole-keyframes").textContent=e.wholeKeyframes,this.wholeKeyframesInput.closest("label").title=e.wholeKeyframesHint,this.importInput.placeholder=e.importUrlPlaceholder;for(const n of this.shadow.querySelectorAll(Vf))n.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.applyPerceptionLabels(),this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,Qs.say(this.labelAccountUrl,e.accountUrl,e.accountUrlHint),this.labelAccountFollowedUp.textContent=e.accountFollowedUp,this.evaluationFields.messages=e.accountEvaluation;for(const[n,r]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const a=this.shadow.getElementById(n);a&&(a.textContent=r)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.label("label-film-stock",e.filmStock),this.filmStockKey=void 0,this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.label("label-sky-sources",e.skySources),this.skySourcesInput.closest("label").title=e.skySourcesHint,this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"peak",label:e.decorPeak},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const s=this.shadow.getElementById("option-scenery-none");s&&(s.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[n,r]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=r,n.setAttribute("aria-label",r);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.decorBaseShownFor=void 0,this.decorBaseShown=!1,this.decorParametersShownFor=void 0,this.isConnected&&this.syncDecorVisibility(),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup;for(const n of this.skyParts.values())this.nameSkyPart(n.label,n.titles);for(const n of["location","decor","weather"]){const r=this.shadow.getElementById(`${n}-settings-button`);r?.setAttribute("title",e.dataSources),r?.setAttribute("aria-label",e.dataSources);const a=this.shadow.getElementById(`label-${n}-settings`);a&&(a.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language);for(const n of this.skyParts.values())n.editor?.setLanguage(this.language);this.modulesPanel?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new Qc(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language},this.decorParameterTexts),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.shadow.getElementById("label-aircraft-group").textContent=e.aircraftGroup,this.aircraftFlights.show(this.sceneElement.aircraftFlights,e,!0),this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.referenceKindSelect.querySelector("#reference-kind-video").textContent=e.referenceVideo,this.shadow.getElementById("label-reference-video-from").textContent=e.referenceVideoFrom,this.shadow.getElementById("label-reference-video-to").textContent=e.referenceVideoTo,this.shadow.getElementById("label-reference-video-rate").textContent=e.referenceVideoRate,this.referenceRemoveKeyButton.textContent=e.referenceRemoveKey,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=this.currentReference()?.kind==="video"?e.referenceVideoT:e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,Qs.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,r]of this.soundKindOptions)r.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e),this.refreshFileItems(),this.refreshSkyCandidates()}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])vr.popover(this.shadow.getElementById(s),e.close);vr.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),vr.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),vr.button(this.contextMenu,e.close,()=>this.hideContextMenu()),vr.button(this.decorContextMenu,e.close,()=>this.hideDecorContextMenu()),this.shadow.getElementById("label-editor-kicker").textContent=e.editorKicker,this.shadow.getElementById("label-save").textContent=e.save,this.shareDialog.useLanguage(this.language).then(s=>{s&&(this.shareMessages=s,this.shadow.getElementById("label-share").textContent=s.share,this.refreshEditorHead())});const i={observation:e.panelIntroObservation,observer:e.panelIntroObserver,location:e.panelIntroLocation,temporal:e.panelIntroTemporal,decor:e.panelIntroDecor,weather:e.panelIntroWeather,shape:e.panelIntroShape,sound:e.panelIntroSound,reference:e.panelIntroReference,file:e.panelIntroFile};for(const[s,n]of Object.entries(i)){const r=this.shadow.querySelector(`[aria-controls="group-${s}"]`);r.dataset.intro=n,ge.titleGroupTab(r)}this.refreshEditorHead()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const s=this.decorMoveAxis(e);if(i==="decor"&&s&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,s))return;const n=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const d=new Cb(this.selectedMembers()),u=ai.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=n.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?ai.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&ai.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const c=this.ufoElement.shapeAt(t.x,t.y,_0);if(!c){const d=s==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),a||!o)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===c.sourceId?c.shape:n.getInterpolatedShapeAt(r,d)??c.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(n=>this.selectedSourceIds.has(n))){if(i.length>=this.selectedSourceIds.size)return;for(const n of i)this.selectedSourceIds.delete(n);if(!this.selectedSourceIds.has(this.currentSourceId)){const n=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,a)=>n.indexOf(r)-n.indexOf(a)).pop()}}else{for(const n of i)this.selectedSourceIds.add(n);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,n=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(s,this.currentSourceId):void 0,a=n?.kind==="polygon"&&ai.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,_0);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const o=this.pickDecorAt(e),c=o?this.ufoElement.sighting.decor.find(h=>h.id===o):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(e.clientX-i.left)/i.width*2-1,n=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(s,n)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,s=i.filter(p=>this.selectedSourceIds.has(p)),n=i.length<=s.length,r=s.length>0&&i.slice(i.length-s.length).every(p=>this.selectedSourceIds.has(p)),a=s.length>0&&i.slice(0,s.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=n||r,this.contextSendToBackButton.disabled=n||a,this.contextBringToFrontButton.title=n?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=n?this.messages.onlyOneShape:a?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const o=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!o,this.contextUngroupButton.title=o?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?ai.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=mI;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const s=document.createElement("span");s.className="submenu-empty",s.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(s)}for(const s of t){const n=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(s)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,s,r.checked)),n.appendChild(r),n.appendChild(document.createTextNode(this.shapeLabel(s))),this.contextMasksSubmenu.appendChild(n)}for(const s of i){const n=this.sceneElement.bodyMaskedBy(s.id,e.id);if(n===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(s.title)??s.id,o=this.messages;r.textContent=`${a} — ${n>=.995?o.masksBodyFully:n>.005?o.masksBodyPartly.replace("{share}",String(Math.round(n*100))):o.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}updateDecorOccludesShape(e,t,i){const s=this.ufoElement.sighting;s.decor=s.decor.map(n=>{if(n.id!==e)return n;const r=i?[...new Set([...n.occludesSourceIds??[],t])]:(n.occludesSourceIds??[]).filter(a=>a!==t);return{...n,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const s=ai.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const s=ai.hitTestVertex(i,e);if(s===void 0)return;const n=ai.deleteVertex(i,s);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,s,n){this.dragState={kind:e,sourceId:t,original:i,handle:n,startPointer:s},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!s||!i)return!1;i.show(s);const n=i.readingNow(),r=this.skyDirectionOf(e);return!n||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:n.azimuthDeg,bodyAltitudeDeg:n.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const s=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+s,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(D0,(e.maxX-e.minX)/2*t.width),s=Math.max(D0,(e.maxY-e.minY)/2*t.height),n=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return this.withinReach({x:n-i/2,y:r-s/2,width:i,height:s})}withinReach(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),s=i.height>0?t.height/i.height:1,r=[this.shadow.querySelector(".playback-row"),this.ufoElement.shadowRoot?.querySelector(".controls")].map(m=>m?.getBoundingClientRect()).filter(m=>m!==void 0&&m.height>0&&m.top<i.bottom&&m.bottom>i.top).reduce((m,g)=>Math.max(m,(i.bottom-g.top)*s),0),a=k0,o=k0+NB,c=t.width-k0,h=t.height-r-k0,d=Math.max(e.x,a),u=Math.max(e.y,o),p=Math.min(e.x+e.width,c),f=Math.min(e.y+e.height,h);return p-d<D0||f-u<D0?e:{x:d,y:u,width:p-d,height:f-u}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),s=e.reading();if(!i||!s)return!1;const n=ai.hitTestHandle({bounds:i,angle:0},t);if(!n)return!1;if(n==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...s.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:n,centre:r,startPointer:t,startSizeM:{...s.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:s,startPointer:n,startSizeM:r,handle:a}=t,o=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=a==="e"||a==="w",h=a==="n"||a==="s",d=c?o(i.x-s.x,n.x-s.x):h?o(i.y-s.y,n.y-s.y):o(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:Dy};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:HB};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=pe.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:Ba.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!s||!i||(e.preventDefault(),i.show(s),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const s=this.pickDecorAt(e);if(s===i.id)return!0;const n=this.decorCanvasBounds();return n!==void 0&&t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+n.height?s===void 0||this.ufoElement.sighting.decor.find(a=>a.id===s)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const s=this.editableDecor();if(!s)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.ufoElement.shapeAt(t.x,t.y,_0)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=Ba.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),a=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,o=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,a);return!n||!o?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:o,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:n.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(s.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const s=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!s&&t.axis!=="up"||this.commitDecorBase(n=>{s&&(t.axis==="ground"||t.axis==="east")&&(n.eastM=this.roundedMeters(t.startEastM+s.x-t.startGround.x)),s&&(t.axis==="ground"||t.axis==="north")&&(n.northM=this.roundedMeters(t.startNorthM-(s.z-t.startGround.z))),t.axis==="up"&&(n.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const s=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:s?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:s?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:s},this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Tl(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Tl(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:s,startPointer:n}=this.dragState,r=t.x-n.x,a=t.y-n.y,o=s.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+a}}}));this.commitShapes(i,o)}else if(this.dragState.kind==="group-resize"){const{group:s,handle:n}=this.dragState;this.commitShapes(i,s.resize(n,t))}else if(this.dragState.kind==="group-rotate"){const{group:s,startPointer:n}=this.dragState;this.commitShapes(i,s.rotate(t,n))}else if(this.dragState.kind==="vertex"){const{sourceId:s,original:n,vertexIndex:r}=this.dragState,a=ai.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:a}])}else{const{kind:s,sourceId:n,original:r,handle:a}=this.dragState,o=s==="resize"?ai.resizeShape(r,a,t):ai.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:s,startPitchDeg:n,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<GB)return;this.cameraDragState.moved=!0}const a=s+(t.x-i.x)*Dy,o=Math.max(-90,Math.min(90,n-(t.y-i.y)*Dy));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=o,this.sceneElement.setIndoorLook(a,o),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver(),this.rounded(a)!==this.rounded(s)&&(this.cameraDragState.headingTurned=!0),this.rounded(o)!==this.rounded(n)&&(this.cameraDragState.pitchTurned=!0),this.showOrientation(this.cameraDragState.headingTurned?a:void 0,this.cameraDragState.pitchTurned?o:void 0),this.showViewDragHint(e.altKey);const c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=c.allKeyframes.find(u=>u.t===h);d&&d.viewOnly===!0!==e.altKey&&(c.setViewOnly(h,e.altKey),this.ufoElement.refresh())}showViewDragHint(e){const t=this.shadow.getElementById("view-drag-hint");t&&(t.hidden=e===void 0,e!==void 0&&(t.textContent=e?this.messages.viewDragHintHeld:this.messages.viewDragHint,t.toggleAttribute("data-held",e)))}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}if(!this.dragState&&!this.cameraDragState)return;const e=this.cameraDragState&&!this.cameraDragState.insideDecor;this.showViewDragHint(void 0),this.dragState=void 0,this.cameraDragState=void 0,e&&this.refreshSceneField(),this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp)}walkOrTurn(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing"||this.isObserverInsideDecor())return;const t=e.shiftKey?YB:1,i=this.numberOrUndefined(this.headingInput.value)??0;if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.headingInput.value=String(this.rounded(i+(e.key==="ArrowRight"?1:-1)*XB*t)),this.updateObserver();return}const s=this.numberOrUndefined(this.latInput.value),n=this.numberOrUndefined(this.lngInput.value);if(s===void 0||n===void 0)return;const r=(e.key==="ArrowUp"?1:-1)*KB*t,a=i*Math.PI/180,o=wr(Math.sin(a)*r,-Math.cos(a)*r,s,n);this.latInput.value=o.lat.toFixed(7),this.lngInput.value=o.lng.toFixed(7);const c=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(c,this.plantingCentre()),this.surroundings.walked(o.lat,o.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=lt(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(o,c)=>Math.round((o-c)*1e3)/1e3,a=this.ufoElement.sighting;a.decor=a.decor.map(o=>({...o,eastM:r(o.eastM,s),northM:r(o.northM,n),...o.track?{track:o.track.map(c=>({...c,eastM:r(c.eastM,s),northM:r(c.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ul,i.width-Bc);break;case"ArrowRight":i.width+=Bc;break;case"ArrowUp":i.height=Math.max(ul,i.height-Bc);break;case"ArrowDown":i.height+=Bc;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Bc;break;case"ArrowRight":i.x+=Bc;break;case"ArrowUp":i.y-=Bc;break;case"ArrowDown":i.y+=Bc;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:s,shape:n}=i[0];this.commitShapes(t,[{sourceId:s,shape:{...n,bounds:this.nudgeBounds(n.bounds,e)}}])}else{const s=new Cb(i),n=this.nudgeBounds(s.bounds(),e);this.commitShapes(t,s.scaleTo(n))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),s=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const o=r?this.bodyCanvasBounds():void 0,c=o&&ai.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const o=this.decorCanvasBounds(),c=o&&ai.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&!this.ufoElement.shapeAt(t.x,t.y,_0)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=ai.hitTestHandle({bounds:new Cb(this.selectedMembers()).bounds(),angle:0},t);if(o)return this.cursorForHandle(o,0)}else{const o=s.getInterpolatedShapeAt(n,this.currentSourceId);if(o?.kind==="polygon"&&ai.hitTestVertex(o,t)!==void 0)return"vertex";const c=o&&ai.hitTestHandle(o,t);if(o&&c)return this.cursorForHandle(c,o.angle)}return s.hitTest(n,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${ai.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),s=e.clientX-i.left,n=e.clientY-i.top;this.recorder?.onPointerMove(s,n),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(e3(this.buildPrototype({x:0,y:0,width:Ed.width,height:Ed.height}),s,n))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const QB={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},mT="rr0-sighting-editor";function m_(){lI(),MM(),d_(),eB(),JU(),nB(),yv(),customElements.get(mT)||customElements.define(mT,ge)}const g_="rr0-read",ez="rr0-edit",mh="in-place",tz="rr0-mode";class iz{static ask(e,t,i){const s=new CustomEvent(t,{detail:i,bubbles:!0,composed:!0,cancelable:!0});return e.dispatchEvent(s),s.defaultPrevented}}class $M{constructor(e,t,i=()=>{}){this.place=e,this.changed=i,t&&this.adopt(t)}reader;editor;handed;get reading(){return this.reader!==void 0}get editorLoaded(){return this.editor!==void 0}adopt(e){this.editor=e,e.switcher=this,e.hasAttribute(mh)||e.setAttribute(mh,""),e.addEventListener(g_,t=>{t.preventDefault();const i=t.detail;this.handed=i.src,this.read(i)})}async read({src:e,track:t}){const[{register:i,CASE_ELEMENT_NAME:s,OPEN_EVENTS_ATTRIBUTE:n},{registerSighting:r,SIGHTING_ELEMENT_NAME:a}]=await Promise.all([H(()=>import("./CaseElement-CVi_yfyW.js"),__vite__mapDeps([51,52]),import.meta.url),H(()=>import("./SightingElement-Bdkf99VT.js"),[],import.meta.url)]);r(),i();const o=Vi.isCase(vs.read(e)??await ba.json(e)),c=document.createElement(o?s:a);c.setAttribute(mh,""),o&&t&&c.setAttribute(n,$M.fileKey(t)),c.setAttribute("src",e),c.addEventListener(ez,h=>{h.preventDefault(),this.edit(h.detail)}),this.reader?.remove(),this.place(c),this.editor&&(this.editor.hidden=!0),this.reader=c,this.changed({mode:"read",src:e,...t?{track:t}:{}})}async edit(e){const t=this.editor;if(t){if(this.dropReader(),vs.releaseCopies(),t.hidden=!1,this.changed({mode:"edit"}),e?.src!==void 0&&e.src!==this.handed){this.load(t,e.src,e.track);return}e?.track&&await t.openTrack(e.track);return}const{register:i,CASE_EDITOR_ELEMENT_NAME:s}=await H(async()=>{const{register:r,CASE_EDITOR_ELEMENT_NAME:a}=await Promise.resolve().then(()=>nz);return{register:r,CASE_EDITOR_ELEMENT_NAME:a}},void 0,import.meta.url);i();const n=document.createElement(s);this.adopt(n),e?.track&&n.setAttribute("track",e.track),e?.src&&n.setAttribute("src",e.src),this.dropReader(),this.place(n),this.changed({mode:"edit"})}async open(e){const t=this.editor;if(this.reading||!t)return this.read({src:e});this.load(t,e)}load(e,t,i){this.handed=void 0,i?e.setAttribute("track",i):e.removeAttribute("track"),e.setAttribute("src",t)}async startNew(){const e=this.editor;if(!e)return this.edit();this.reading&&await this.edit(),e.askBeforeReplacing(()=>{e.remove(),this.editor=void 0,this.edit()})}dropReader(){this.reader?.remove(),this.reader=void 0}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}}const Aw="rr0-case-editor",sz=`
|
|
12303
12304
|
<style>
|
|
12304
12305
|
/* What the layout adapts to: the width this editor is given, never the window's. */
|
|
12305
12306
|
:host { display: block; container-type: inline-size; }
|