@rr0/ufoathome 0.204.1 → 0.204.2
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-Dk3rKiVm.js → CaseReportExport-DQ4bO4eb.js} +1 -1
- package/dist-embed-sighting/SightingMessages_en-Bih7ljAQ.js +1 -0
- package/dist-embed-sighting/SightingMessages_es-CHrrXx-N.js +1 -0
- package/dist-embed-sighting/SightingMessages_fr-B2NUAkiz.js +1 -0
- package/dist-embed-sighting/SightingMessages_it-OGLqMUWg.js +1 -0
- package/dist-embed-sighting/rr0-sighting.mjs +85 -81
- package/dist-embed-sighting-editor/{CaseElement-4CRoH54h.js → CaseElement-zFqMRzIe.js} +2 -2
- package/dist-embed-sighting-editor/{CaseReportExport-W1lO4CR3.js → CaseReportExport-C7dPT0eH.js} +1 -1
- package/{dist-embed-ufoathome/SightingEditorMessages_en-V_dJYjNb.js → dist-embed-sighting-editor/SightingEditorMessages_en-CS2iXwDm.js} +1 -1
- package/{dist-embed-ufoathome/SightingEditorMessages_es-DauDuhPa.js → dist-embed-sighting-editor/SightingEditorMessages_es-C8Vw_4b_.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_fr-zxTvQa2I.js → SightingEditorMessages_fr-AYgrnKFD.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_it-vvaao68O.js → SightingEditorMessages_it-DZyzwScx.js} +1 -1
- package/dist-embed-sighting-editor/{SightingElement-4YMo_us5.js → SightingElement-Bf654S_I.js} +5 -5
- package/dist-embed-sighting-editor/{SightingLabels_en-dOsFjVRL.js → SightingLabels_en-trAaLk8Q.js} +1 -1
- package/{dist-embed-ufoathome/SightingLabels_es-CKlP2BDO.js → dist-embed-sighting-editor/SightingLabels_es-Geji-Hhz.js} +1 -1
- package/dist-embed-sighting-editor/{SightingLabels_fr-Cpkcf5_9.js → SightingLabels_fr-BVnntoiD.js} +1 -1
- package/{dist-embed-ufoathome/SightingLabels_it-3127rMXm.js → dist-embed-sighting-editor/SightingLabels_it-B9FWbLXW.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_en-Drcr3k4V.js → SightingMessages_en-D90vDTQ7.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_es-BcaWM7Oy.js → SightingMessages_es-D8laK6OY.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_fr-7IYuW095.js → SightingMessages_fr-Gq3IMFTE.js} +1 -1
- package/dist-embed-sighting-editor/{SightingMessages_it-BhDmZn6p.js → SightingMessages_it-BXDxv-lE.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +16 -12
- package/dist-embed-ufoathome/{AdsbLolArchiveProvider-BJm3HMv9.js → AdsbLolArchiveProvider-JK7ddZzC.js} +1 -1
- package/dist-embed-ufoathome/{Aurora-DooZfol8.js → Aurora-UBzKnuxt.js} +1 -1
- package/dist-embed-ufoathome/{AuroraEditor-COl6Uq7r.js → AuroraEditor-B0Q9h5C6.js} +1 -1
- package/dist-embed-ufoathome/{AuroraSimulation-8865pkCY.js → AuroraSimulation-Cj8dyvm4.js} +1 -1
- package/dist-embed-ufoathome/{BallesterGuaspAssessor-CKK5Iybb.js → BallesterGuaspAssessor-DZ5guaNx.js} +1 -1
- package/dist-embed-ufoathome/{BeamEditor-D6I1zG9Z.js → BeamEditor-Dgo8WSF9.js} +1 -1
- package/dist-embed-ufoathome/{BeamSystem-BI4-w_0X.js → BeamSystem-BbSsBbZk.js} +1 -1
- package/dist-embed-ufoathome/{BodyEditor-yBNJy9AC.js → BodyEditor-Cav_-OeQ.js} +1 -1
- package/dist-embed-ufoathome/{CaseEditorElement-CPt1laCe.js → CaseEditorElement-CK82yjEn.js} +6 -6
- package/dist-embed-ufoathome/{CaseElement-CTZ3YIL0.js → CaseElement-Bm6xPD0e.js} +3 -3
- package/dist-embed-ufoathome/{CaseReportExport-UNmAQ_xa.js → CaseReportExport-D_I2ml6F.js} +3 -3
- package/dist-embed-ufoathome/{ColumnResize-D6vA9JBg.js → ColumnResize-DksRZriL.js} +4 -4
- package/dist-embed-ufoathome/{ControlPasses-Bwafi16d.js → ControlPasses-BpLNDq5G.js} +1 -1
- package/dist-embed-ufoathome/{CoverageAssessor-DINhJJFz.js → CoverageAssessor-UyH_dVvr.js} +1 -1
- package/dist-embed-ufoathome/{Flightradar24Provider-BEVn6h-k.js → Flightradar24Provider-XASYwL-N.js} +1 -1
- package/dist-embed-ufoathome/{GLTFLoader-CqzCNjEl.js → GLTFLoader-s3EU9qS0.js} +1 -1
- package/dist-embed-ufoathome/{GeoJsonExport-B4GBH7Ei.js → GeoJsonExport-BCtJzQ9B.js} +1 -1
- package/dist-embed-ufoathome/{GeographicFigures-wtF2TmIn.js → GeographicFigures-DINsiWL0.js} +1 -1
- package/dist-embed-ufoathome/{HynekAssessor-De0RmEd0.js → HynekAssessor-D5zxfJ44.js} +1 -1
- package/dist-embed-ufoathome/{InterviewEditorElement-BVfNqEBS.js → InterviewEditorElement-CQNMEirl.js} +1 -1
- package/dist-embed-ufoathome/{InterviewElement-BBEmBs1S.js → InterviewElement-BouR8Xii.js} +1 -1
- package/dist-embed-ufoathome/{KmlExport-C8yk8C7s.js → KmlExport-C8zEY6ew.js} +1 -1
- package/dist-embed-ufoathome/{LaserBeam-BGs1pXaE.js → LaserBeam-CDTsYUwS.js} +1 -1
- package/dist-embed-ufoathome/{LaunchEditor-CBEW_ih2.js → LaunchEditor-C91_y6bJ.js} +1 -1
- package/dist-embed-ufoathome/{LaunchPlume-BbsUUQE0.js → LaunchPlume-Je5cyuGE.js} +1 -1
- package/dist-embed-ufoathome/{LaunchSimulation-DJJaKJGV.js → LaunchSimulation-BsCQGsdb.js} +1 -1
- package/dist-embed-ufoathome/{ModelSource-B2Ie3T9B.js → ModelSource-7jnvikmB.js} +1 -1
- package/dist-embed-ufoathome/{ModelThumbnails-BOfC5SZt.js → ModelThumbnails-DhEg69n0.js} +1 -1
- package/dist-embed-ufoathome/{ModelViewer-CXP4K0sx.js → ModelViewer-BQJyyY66.js} +1 -1
- package/dist-embed-ufoathome/{ModulesPanelElement-DPkBhz-Y.js → ModulesPanelElement-Ct9DMG0-.js} +1 -1
- package/dist-embed-ufoathome/{NearestApproach-D2cz2_44.js → NearestApproach-BFKGUqFb.js} +1 -1
- package/dist-embed-ufoathome/{PoherAssessor-CNOuLGVz.js → PoherAssessor-Cmw5u2Nv.js} +1 -1
- package/dist-embed-ufoathome/{PoherSelfCheck-DnXcStjH.js → PoherSelfCheck-BjmenygA.js} +1 -1
- package/dist-embed-ufoathome/{ReentryEditor-BCQM22Ps.js → ReentryEditor-x_C9chQN.js} +1 -1
- package/dist-embed-ufoathome/{ReentrySimulation-BFhCb4sM.js → ReentrySimulation-D0XIfeyt.js} +1 -1
- package/dist-embed-ufoathome/{ReferenceSystem-aZKW97nH.js → ReferenceSystem-Cv556rkv.js} +1 -1
- package/dist-embed-ufoathome/{ScenarioReadings-_IkJEoIB.js → ScenarioReadings-YJ8iIjyw.js} +1 -1
- package/dist-embed-ufoathome/{ScenarioSweep-DOvp2pYT.js → ScenarioSweep-DTqJSF5a.js} +1 -1
- package/dist-embed-ufoathome/{SearchlightEditor-C8Jwy1VZ.js → SearchlightEditor-Dy-gMDUN.js} +1 -1
- package/dist-embed-ufoathome/{SearchlightSystem-D2TFaVqO.js → SearchlightSystem-C-qAMIFS.js} +1 -1
- package/dist-embed-ufoathome/{ShareDialogElement-Dsc4v4jd.js → ShareDialogElement-DMDY7Hlo.js} +16 -12
- package/{dist-embed-sighting-editor/SightingEditorMessages_en-V_dJYjNb.js → dist-embed-ufoathome/SightingEditorMessages_en-CS2iXwDm.js} +1 -1
- package/{dist-embed-sighting-editor/SightingEditorMessages_es-DauDuhPa.js → dist-embed-ufoathome/SightingEditorMessages_es-C8Vw_4b_.js} +1 -1
- package/dist-embed-ufoathome/{SightingEditorMessages_fr-zxTvQa2I.js → SightingEditorMessages_fr-AYgrnKFD.js} +1 -1
- package/dist-embed-ufoathome/{SightingEditorMessages_it-vvaao68O.js → SightingEditorMessages_it-DZyzwScx.js} +1 -1
- package/dist-embed-ufoathome/{SightingElement-CFItfa0b.js → SightingElement-DZlh5u4N.js} +5 -5
- package/dist-embed-ufoathome/{SightingLabels_en-dOsFjVRL.js → SightingLabels_en-trAaLk8Q.js} +1 -1
- package/{dist-embed-sighting-editor/SightingLabels_es-CKlP2BDO.js → dist-embed-ufoathome/SightingLabels_es-Geji-Hhz.js} +1 -1
- package/dist-embed-ufoathome/{SightingLabels_fr-Cpkcf5_9.js → SightingLabels_fr-BVnntoiD.js} +1 -1
- package/{dist-embed-sighting-editor/SightingLabels_it-3127rMXm.js → dist-embed-ufoathome/SightingLabels_it-B9FWbLXW.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_en-Drcr3k4V.js → SightingMessages_en-D90vDTQ7.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_es-BcaWM7Oy.js → SightingMessages_es-D8laK6OY.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_fr-7IYuW095.js → SightingMessages_fr-Gq3IMFTE.js} +1 -1
- package/dist-embed-ufoathome/{SightingMessages_it-BhDmZn6p.js → SightingMessages_it-BXDxv-lE.js} +1 -1
- package/dist-embed-ufoathome/{TraceSystem-_cZ6PZho.js → TraceSystem-DYmjmB9_.js} +1 -1
- package/dist-embed-ufoathome/{VideoButton-CeAdEi2m.js → VideoButton-CvAmQpx0.js} +1 -1
- package/dist-embed-ufoathome/rr0-ufoathome.mjs +3 -3
- package/dist-embed-ufoathome/{surroundingsSources-B7gbT2Pb.js → surroundingsSources-DtoCfflQ.js} +1 -1
- package/dist-embed-ufoathome/{trafficRuntime-BKNJgPC4.js → trafficRuntime-CyYep5Cc.js} +1 -1
- package/package.json +1 -1
- package/dist-embed-sighting/SightingMessages_en-DKFVZnDu.js +0 -1
- package/dist-embed-sighting/SightingMessages_es-DYQlWvm0.js +0 -1
- package/dist-embed-sighting/SightingMessages_fr-BygVDDY9.js +0 -1
- package/dist-embed-sighting/SightingMessages_it-BI7GnXPz.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./LanternEditor-Hd-8kmET.js","./SkyEventEditorStyle-CvY_AhbI.js","./SkyLantern-Cj60Cn9B.js","./BirdEditor-CbYZcYyG.js","./BirdFlock-Dv9Awhvf.js","./DroneEditor-D6k4gYj4.js","./DroneParameters-CdQbwFKD.js","./DroneFlight-D-MWhrXa.js","./BalloonEditor-Drb5evP5.js","./BalloonFlight-CGXmDbNq.js","./AirshipFlight-Cvl6xWPY.js","./AirshipEditor-BVlkWwdL.js","./SightingEditorMessages_en-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./LanternEditor-Hd-8kmET.js","./SkyEventEditorStyle-CvY_AhbI.js","./SkyLantern-Cj60Cn9B.js","./BirdEditor-CbYZcYyG.js","./BirdFlock-Dv9Awhvf.js","./DroneEditor-D6k4gYj4.js","./DroneParameters-CdQbwFKD.js","./DroneFlight-D-MWhrXa.js","./BalloonEditor-Drb5evP5.js","./BalloonFlight-CGXmDbNq.js","./AirshipFlight-Cvl6xWPY.js","./AirshipEditor-BVlkWwdL.js","./SightingEditorMessages_en-CS2iXwDm.js","./SightingLabels_en-trAaLk8Q.js","./SightingEditorMessages_fr-AYgrnKFD.js","./SightingLabels_fr-BVnntoiD.js","./SightingEditorMessages_es-C8Vw_4b_.js","./SightingLabels_es-Geji-Hhz.js","./SightingEditorMessages_it-DZyzwScx.js","./SightingLabels_it-B9FWbLXW.js","./SightingMessages_en-D90vDTQ7.js","./SightingMessages_fr-Gq3IMFTE.js","./SightingMessages_es-D8laK6OY.js","./SightingMessages_it-BXDxv-lE.js","./ShareCodeEditor-CF7IVeXv.js","./index-DSNA74v6.js","./ScenarioSweep-ByqOTfs2.js","./SatellitePasses-Pfro2-0Z.js","./ScenarioReadings-DyMshXS4.js","./BeamSystem-BCaOtm3H.js","./LaserBeam-Ca2QUeCT.js","./BeamEditor-DP2LNObR.js","./LaunchSimulation-B0DgOoJM.js","./LaunchPlume-Dos-OyTV.js","./LaunchEditor-BykQEscN.js","./ReentryEditor-CNLwoAIZ.js","./AuroraSimulation-CX7V0obh.js","./Aurora-DOIRpjiG.js","./AuroraEditor-B0tCM7E7.js","./SearchlightSystem-B_RPbGj4.js","./SearchlightEditor-sQh92hx7.js","./HynekAssessor-B4ej1xgG.js","./NearestApproach-jDpDx7cm.js","./BallesterGuaspAssessor-DEJId5n8.js","./CoverageAssessor-CcVuVsG0.js","./ContrailSystem-ChbOVWp-.js","./ContrailGrowth-DwHS8If9.js","./ReferenceSystem-B0tZDQ1-.js","./PictureFetch-C3wgf1ZV.js","./trafficRuntime-eGXY41n0.js","./GenerativeKit-BmhvjjzB.js","./browser-CltifEM0.js","./VideoExport-B8ZhHNnd.js","./ModelThumbnails-dnCeD6UT.js","./ModelSource-szsl2QtY.js","./ModelViewer-BNGSukqO.js","./SightingFileEditor-tIOJTG_y.js","./sightingSchema-DoPVOlCB.js","./ModulesPanelElement-DTnJICg0.js","./ModuleSession-DOhPD2XZ.js","./KmlExport-DIxM5Hpx.js","./GeographicFigures-Bo9rsT_L.js","./GeoJsonExport-CdadOwd2.js","./GhostSearchView-Dlhj3xWa.js","./CaseElement-zFqMRzIe.js","./SightingElement-Bf654S_I.js","./InterviewEditorElement-Bo4OG2ig.js","./InterviewMedia-CGVsMdje.js","./InterviewElement-Ala811KB.js","./interviewJson-BJF9C-Rb.js","./QuestionnaireFeed-B0j8W4JM.js","./QuestionnaireImport-BmcxlQBq.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
const v5="modulepreload",b5=function(l,e){return new URL(l,e).href},kx={},F=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=b5(h,i),h in kx)return;kx[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":v5,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 xt{constructor(e){this.entries=e}static same(e,t){return typeof e=="number"&&typeof t=="number"?e===t||Math.abs(e-t)<=1e-9*Math.max(1,Math.abs(e),Math.abs(t)):Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((i,s)=>xt.same(i,t[s])):typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null&&!Array.isArray(e)&&!Array.isArray(t)?[...new Set([...Object.keys(e),...Object.keys(t)])].every(s=>xt.same(e[s],t[s])):e===t}static free(e){return e?.basis==="assumed"||e?.basis==="fitted"}static empty(){return new xt(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 xt(new Map);return{recording:xt.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=xt.writableHolderOf(i,a,s);if(!o)continue;const c=a[a.length-1],h=o[c];h!==void 0&&(r.of!==void 0&&!xt.same(r.of,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 xt.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}),xt.stripValue(e.value,t,i)):Array.isArray(e)?e.map((s,n)=>xt.stripValue(s,[...t,String(n)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([s,n])=>[s,xt.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 vf 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 Tn{static CURRENT={sighting:4,case:1,interview:1};static SCHEMA_BASE="https://ufoathome.org/schema";static schemaUrl(e,t=Tn.CURRENT[e]){return`${Tn.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 Tn.check(e,"sighting")}static check(e,t){const i=Tn.of(e),s=Tn.CURRENT[t];if(typeof i!="number"||!Number.isInteger(i)||i!==s)throw new vf(t,i,s);return e}}class Wt{static built=new WeakMap;static computers=new WeakMap;static loading=new WeakMap;static loaded(e,t){return t.every(i=>Wt.itemsOf(e,i.key).length===0||Wt.computers.has(i))}static load(e,t){return Promise.all(t.filter(i=>Wt.itemsOf(e,i.key).length>0&&!Wt.computers.has(i)).map(i=>{let s=Wt.loading.get(i);return s||(s=i.compute().then(n=>{Wt.computers.set(i,n)}),s.catch(()=>Wt.loading.delete(i)),Wt.loading.set(i,s)),s.catch(()=>{})})).then(()=>{})}static of(e){let t=Wt.built.get(e);return t||(t=e.create(),Wt.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=>Wt.itemsOf(e,i.key).length>0)}static expand(e,t,i){return Wt.expandWithKinds(e,t,i).interpretation}static expandWithKinds(e,t,i){const s=new Map,n=new Map;if(!e||!Wt.computes(e,t))return{interpretation:e,kindOf:s,phenomenonOf:n};const r=t.flatMap(a=>Wt.itemsOf(e,a.key).flatMap(o=>{const c=Wt.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 phenomena(e,t){const i=new Set;for(const s of t)for(const n of Wt.itemsOf(e,s.key)){const r=s.phenomenon?.(n);r&&i.add(r)}return i}static computedPart(e,t){const i={};for(const s of t){const n=Wt.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)}}const Dx=Object.freeze(Object.defineProperty({__proto__:null,InterpretationKinds:Wt},Symbol.toStringTag,{value:"Module"}));class i3 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 y5{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 i3(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 y5(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 i3(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 w5=["en","fr","es","it"];class $t{static catalog(e){const t=new Map;return{load(i){const s=$t.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 w5.includes(t)?t:"en"}}const M5=$t.catalog({en:()=>F(()=>import("./FlareKindMessages_en-j3CY_TxX.js"),[],import.meta.url).then(l=>l.flareKindMessages_en),fr:()=>F(()=>import("./FlareKindMessages_fr-B2MezoN2.js"),[],import.meta.url).then(l=>l.flareKindMessages_fr),es:()=>F(()=>import("./FlareKindMessages_es-CZgrFIOO.js"),[],import.meta.url).then(l=>l.flareKindMessages_es),it:()=>F(()=>import("./FlareKindMessages_it-CmZmb3RP.js"),[],import.meta.url).then(l=>l.flareKindMessages_it)});class uc{constructor(e={}){this.options=e,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wait=e.wait??(t=>new Promise(i=>setTimeout(i,t)))}static URL="https://historical-forecast-api.open-meteo.com/v1/forecast";static CREDIT="Open-Meteo historical forecast";static LEVELS=[850,700,600,500,400,300];static RETRIES=6;static RETRY_MS=2e3;days=new Map;fetchImpl;wait;async profile(e,t,i){const n=new Date(Math.floor(i.getTime()/36e5)*36e5),r=(i.getTime()-n.getTime())/36e5,a=await this.hourly(e,t,n);if(r<1e-6)return a;const o=await this.hourly(e,t,new Date(n.getTime()+36e5));return a.levels.length!==o.levels.length?r<.5?a:o:{...a,hour:i.toISOString().slice(0,16),levels:a.levels.map((c,h)=>{const[d,u]=eo.vector(c.wind),[p,f]=eo.vector(o.levels[h].wind);return{aboveGroundM:c.aboveGroundM+r*(o.levels[h].aboveGroundM-c.aboveGroundM),wind:eo.fromVector(d+r*(p-d),u+r*(f-u))}})}}async hourly(e,t,i){const s=i.toISOString().slice(0,13)+":00",n=s.slice(0,10),r=`${e.toFixed(4)},${t.toFixed(4)},${n}`;let a=this.days.get(r);return a||(a=this.day(e,t,n,r),a.catch(()=>this.days.delete(r)),this.days.set(r,a)),uc.profileOf(await a,s)}static profileOf(e,t){const i=e.hourly,s=i.time.indexOf(t);if(s<0)throw new Error(`No wind for ${t} in the archive's answer`);const n=c=>(c+180)%360,r=[],a=i.wind_speed_10m?.[s],o=i.wind_direction_10m?.[s];typeof a=="number"&&typeof o=="number"&&r.push({aboveGroundM:10,wind:{towardDeg:n(o),speedMS:a}});for(const c of uc.LEVELS){const h=i[`geopotential_height_${c}hPa`]?.[s],d=i[`wind_speed_${c}hPa`]?.[s],u=i[`wind_direction_${c}hPa`]?.[s];if(typeof h!="number"||typeof d!="number"||typeof u!="number")continue;const p=h-e.elevation;p<=(r[r.length-1]?.aboveGroundM??0)||r.push({aboveGroundM:p,wind:{towardDeg:n(u),speedMS:d}})}if(r.length===0)throw new Error(`No wind for ${t} in the archive's answer`);return{lat:e.latitude,lng:e.longitude,elevationM:e.elevation,hour:t,levels:r,credit:uc.CREDIT}}async day(e,t,i,s){const n=await this.options.cache?.get(s);if(n)return JSON.parse(n);const r=["wind_speed_10m","wind_direction_10m",...uc.LEVELS.flatMap(c=>[`wind_speed_${c}hPa`,`wind_direction_${c}hPa`,`geopotential_height_${c}hPa`])],a=new URLSearchParams({latitude:String(e),longitude:String(t),start_date:i,end_date:i,hourly:r.join(","),wind_speed_unit:"ms",timezone:"GMT"}),o=`${this.options.url??uc.URL}?${a}`;for(let c=0;;c++){const h=await this.fetchImpl(o);if(h.ok){const d=await h.text();return await this.options.cache?.set(s,d),JSON.parse(d)}if((h.status===429||h.status>=500)&&c<uc.RETRIES){await this.wait(uc.RETRY_MS*2**c);continue}throw new Error(`The wind archive answered ${h.status} for ${s}`)}}}class eo{static at(e,t){const i=e.levels;if(t<=i[0].aboveGroundM)return{...i[0].wind};for(let s=1;s<i.length;s++){const n=i[s-1],r=i[s];if(t<=r.aboveGroundM){const a=(t-n.aboveGroundM)/(r.aboveGroundM-n.aboveGroundM),[o,c]=eo.vector(n.wind),[h,d]=eo.vector(r.wind);return eo.fromVector(o+a*(h-o),c+a*(d-c))}}return{...i[i.length-1].wind}}static vector(e){const t=e.towardDeg*Math.PI/180;return[e.speedMS*Math.sin(t),e.speedMS*Math.cos(t)]}static fromVector(e,t){return{towardDeg:(Math.atan2(e,t)*180/Math.PI+360)%360,speedMS:Math.hypot(e,t)}}static rounded(e){return{towardDeg:Math.round(e.towardDeg)%360,speedMS:Math.round(e.speedMS*100)/100}}}const x5=Object.freeze(Object.defineProperty({__proto__:null,OpenMeteoWindProfiles:uc,Winds:eo},Symbol.toStringTag,{value:"Module"})),E5=eo.rounded,Rx={key:"flares",messages:M5,phenomenon:()=>"DecoyFlare",inWind:(l,e)=>({...l,wind:E5(e.at(l.aircraft.altitudeM))}),compute:()=>F(async()=>{const{DecoyFlare:l}=await import("./DecoyFlare-DUt1_LcW.js");return{DecoyFlare:l}},[],import.meta.url).then(({DecoyFlare:l})=>e=>l.bodiesOf(e))},S5=$t.catalog({en:()=>F(()=>import("./LanternKindMessages_en-CQXdJ-k6.js"),[],import.meta.url).then(l=>l.lanternKindMessages_en),fr:()=>F(()=>import("./LanternKindMessages_fr-D7tQa_tQ.js"),[],import.meta.url).then(l=>l.lanternKindMessages_fr),es:()=>F(()=>import("./LanternKindMessages_es-BOO6kPjs.js"),[],import.meta.url).then(l=>l.lanternKindMessages_es),it:()=>F(()=>import("./LanternKindMessages_it-B8J-29Mj.js"),[],import.meta.url).then(l=>l.lanternKindMessages_it)}),Cx=eo.rounded,Ox={key:"lanterns",messages:S5,phenomenon:()=>"SkyLantern",inWind:(l,e)=>{const t=l.site.altitudeM??0,i=l.windAloft?.atM??1e3;return{...l,wind:Cx(e.at(10)),windAloft:{...Cx(e.at(t+i)),atM:i}}},compute:()=>F(async()=>{const{SkyLantern:l}=await import("./SkyLantern-Cj60Cn9B.js");return{SkyLantern:l}},[],import.meta.url).then(({SkyLantern:l})=>(e,t)=>l.bodiesOf(e,t?.obstacles)),editor:()=>F(async()=>{const{LanternEditor:l}=await import("./LanternEditor-Hd-8kmET.js");return{LanternEditor:l}},__vite__mapDeps([0,1,2]),import.meta.url).then(({LanternEditor:l})=>(e,t,i)=>new l(e,t,i))},A5=$t.catalog({en:()=>F(()=>import("./BirdKindMessages_en-c_-L7frF.js"),[],import.meta.url).then(l=>l.birdKindMessages_en),fr:()=>F(()=>import("./BirdKindMessages_fr-C1TuqqEj.js"),[],import.meta.url).then(l=>l.birdKindMessages_fr),es:()=>F(()=>import("./BirdKindMessages_es-8Zo2t0o4.js"),[],import.meta.url).then(l=>l.birdKindMessages_es),it:()=>F(()=>import("./BirdKindMessages_it-DQZcrCkf.js"),[],import.meta.url).then(l=>l.birdKindMessages_it)}),Lx={key:"birds",messages:A5,phenomenon:()=>"Birds",compute:()=>F(async()=>{const{BirdFlock:l}=await import("./BirdFlock-Dv9Awhvf.js").then(e=>e.b);return{BirdFlock:l}},[],import.meta.url).then(({BirdFlock:l})=>(e,t)=>l.bodiesOf(e,t?.obstacles)),editor:()=>F(async()=>{const{BirdEditor:l}=await import("./BirdEditor-CbYZcYyG.js");return{BirdEditor:l}},__vite__mapDeps([3,1,4]),import.meta.url).then(({BirdEditor:l})=>(e,t,i)=>new l(e,t,i))},T5=$t.catalog({en:()=>F(()=>import("./DroneKindMessages_en-CLygXcsv.js"),[],import.meta.url).then(l=>l.droneKindMessages_en),fr:()=>F(()=>import("./DroneKindMessages_fr-CAX15_pk.js"),[],import.meta.url).then(l=>l.droneKindMessages_fr),es:()=>F(()=>import("./DroneKindMessages_es-B9XFRYnQ.js"),[],import.meta.url).then(l=>l.droneKindMessages_es),it:()=>F(()=>import("./DroneKindMessages_it-CSGsCaJQ.js"),[],import.meta.url).then(l=>l.droneKindMessages_it)}),Px={quadcopter:"ConsumerDrone",saucer:"ConsumerDrone","fixed-wing":"MilitaryDrone"},Nx={key:"drones",messages:T5,phenomenon:l=>Px[l.airframe]??Px.quadcopter,compute:()=>F(async()=>{const{DroneFlight:l}=await import("./DroneFlight-D-MWhrXa.js").then(e=>e.c);return{DroneFlight:l}},[],import.meta.url).then(({DroneFlight:l})=>e=>l.bodiesOf(e)),editor:()=>F(async()=>{const{DroneEditor:l}=await import("./DroneEditor-D6k4gYj4.js");return{DroneEditor:l}},__vite__mapDeps([5,1,6,7]),import.meta.url).then(({DroneEditor:l})=>(e,t,i)=>new l(e,t,i))},I5=$t.catalog({en:()=>F(()=>import("./BalloonKindMessages_en-C6tZ-5gT.js"),[],import.meta.url).then(l=>l.balloonKindMessages_en),fr:()=>F(()=>import("./BalloonKindMessages_fr-C3QJIuDJ.js"),[],import.meta.url).then(l=>l.balloonKindMessages_fr),es:()=>F(()=>import("./BalloonKindMessages_es-BfoEjhe1.js"),[],import.meta.url).then(l=>l.balloonKindMessages_es),it:()=>F(()=>import("./BalloonKindMessages_it-CkO7mqHp.js"),[],import.meta.url).then(l=>l.balloonKindMessages_it)}),EH=["round","star","heart","figure"];class Mg{static HELIUM_KG_MOL=.0040026;static ALL=[{id:"hot-air",modelId:"ufoathome-balloon-hot-air",envelope:"open",launchVolumeM3:2550,maxVolumeM3:2550,massKg:540,dragCoefficient:.5,aspect:1.461,widthM:16.5,color:"#c8202f",stripeColor:"#f5c400",albedo:.4,burner:{heatingKS:1.2,coolingS:400,blastS:6,maxExcessK:100,flameCdM2:2e4,envelopeCdM2:40,color:"#ffb347"},phenomenon:"WeatherBalloonsOrMongolfieres",durationS:3600},{id:"party",modelId:"ufoathome-balloon-latex",envelope:"elastic",launchVolumeM3:.0115,maxVolumeM3:.0335,massKg:.0045,dragCoefficient:.47,aspect:1.13,color:"#d8263a",albedo:.35,phenomenon:"WeatherBalloonsOrMongolfieres",durationS:3600},{id:"led",modelId:"ufoathome-balloon-led",envelope:"elastic",launchVolumeM3:.0141,maxVolumeM3:.041,massKg:.0075,dragCoefficient:.47,aspect:1.115,color:"#ffffff",albedo:.5,glow:{candela:.5,color:"#ffffff"},phenomenon:"LedBalloon",durationS:3600},{id:"foil",modelId:"ufoathome-balloon-foil",envelope:"vented",launchVolumeM3:.014,maxVolumeM3:.014,massKg:.01,dragCoefficient:.6,aspect:1.034,widthM:.45,depthRatio:.267,color:"#c9cdd2",albedo:.85,finish:"mirror",spins:!0,shapes:{round:{modelId:"ufoathome-balloon-foil",aspect:1.034,widthM:.45,depthRatio:.267,launchVolumeM3:.014,maxVolumeM3:.014,massKg:.01,color:"#c9cdd2"},star:{modelId:"ufoathome-balloon-foil-star",aspect:1.029,widthM:.5,depthRatio:.183,launchVolumeM3:.012,maxVolumeM3:.012,massKg:.009,color:"#e0b83a"},heart:{modelId:"ufoathome-balloon-foil-heart",aspect:.903,widthM:.5,depthRatio:.2,launchVolumeM3:.014,maxVolumeM3:.014,massKg:.01,color:"#d81e3c"},figure:{modelId:"ufoathome-balloon-foil-figure",aspect:1.112,widthM:.8,depthRatio:.127,launchVolumeM3:.05,maxVolumeM3:.05,massKg:.03,color:"#f0a3c8"}},phenomenon:"FoilBalloon",durationS:3600},{id:"pilot",modelId:"ufoathome-balloon-latex",envelope:"elastic",launchVolumeM3:.144,maxVolumeM3:.57,massKg:.045,dragCoefficient:.4,aspect:1.13,color:"#f0e6cf",albedo:.55,lamp:{candela:1,color:"#fff1c4"},phenomenon:"WeatherBalloonsOrMongolfieres",durationS:5400},{id:"weather",modelId:"ufoathome-balloon-latex",envelope:"elastic",launchVolumeM3:1.75,maxVolumeM3:118.9,massKg:.85,dragCoefficient:.3,aspect:1.13,color:"#f2ece0",albedo:.55,phenomenon:"WeatherBalloonsOrMongolfieres",durationS:7200},{id:"stratospheric",modelId:"ufoathome-balloon-stratospheric",envelope:"vented",launchVolumeM3:219,maxVolumeM3:14e3,massKg:210,dragCoefficient:.4,aspect:.91,color:"#e9eef2",albedo:.8,ballastKg:20,phenomenon:"StratosphericBalloons",durationS:10800},{id:"stratospheric-large",modelId:"ufoathome-balloon-stratospheric",envelope:"vented",launchVolumeM3:730,maxVolumeM3:15e4,massKg:700,dragCoefficient:.4,aspect:.91,color:"#e9eef2",albedo:.8,ballastKg:140,phenomenon:"StratosphericBalloons",durationS:14400},{id:"superpressure",modelId:"ufoathome-balloon-latex",envelope:"superpressure",launchVolumeM3:45,maxVolumeM3:523,massKg:44,dragCoefficient:.4,aspect:1.13,color:"#eef1f4",albedo:.8,phenomenon:"StratosphericBalloons",durationS:10800},{id:"infrared",modelId:"ufoathome-balloon-stratospheric",envelope:"open",launchVolumeM3:2075,maxVolumeM3:45e3,massKg:150,dragCoefficient:.4,aspect:.91,color:"#9aa0a8",albedo:.4,insideExcessK:20,phenomenon:"StratosphericBalloons",durationS:10800},{id:"prank-candles",modelId:"ufoathome-balloon-prank",envelope:"open",launchVolumeM3:.25,maxVolumeM3:.25,massKg:.02,dragCoefficient:.6,aspect:1.515,widthM:.6,color:"#f4f4f4",albedo:.6,insideExcessK:60,spins:!0,sways:!0,flames:{count:4,candela:.5,color:"#ffb347",burnS:720,coolingS:15},phenomenon:"SkyLantern",durationS:1200},{id:"prank-flares",modelId:"ufoathome-balloon-prank",envelope:"open",launchVolumeM3:2,maxVolumeM3:2,massKg:.3,dragCoefficient:.6,aspect:1.515,widthM:1.2,color:"#2b2d30",albedo:.1,insideExcessK:80,spins:!0,sways:!0,flames:{count:1,candela:150,color:"#ff3a20",burnS:900,coolingS:30},phenomenon:"SkyLantern",durationS:1500},{id:"anti-hail",modelId:"ufoathome-balloon-latex",envelope:"elastic",launchVolumeM3:.65,maxVolumeM3:8,massKg:.4,dragCoefficient:.35,aspect:1.13,color:"#f2ece0",albedo:.55,torch:{aboveM:600,candela:300,color:"#ff9a3c",burnS:90,fallMS:4},phenomenon:"ParachuteFlare",durationS:1200},{id:"solar",modelId:"ufoathome-balloon-latex",envelope:"open",launchVolumeM3:14,maxVolumeM3:14,massKg:.4,dragCoefficient:.47,aspect:1.13,color:"#151515",albedo:.05,insideExcessK:10,phenomenon:"WeatherBalloonsOrMongolfieres",durationS:3600},{id:"captive",modelId:"ufoathome-balloon-latex",envelope:"sealed",tethered:!0,launchVolumeM3:14,maxVolumeM3:14,massKg:8,dragCoefficient:.47,aspect:1.13,color:"#f4f4f4",albedo:.7,phenomenon:"WeatherBalloonsOrMongolfieres",durationS:3600}];static byId(e){return Mg.ALL.find(t=>t.id===e)}}const Fx=eo.rounded,Ux={key:"balloons",messages:I5,phenomenon:l=>{const e=typeof l.balloon=="string"?l.balloon:l.balloon?.id;return(Mg.byId(e)??Mg.ALL[0]).phenomenon},inWind:(l,e)=>{const t=l.site.altitudeM??0;return{...l,wind:Fx(e.at(10)),windsAloft:e.levels.filter(i=>i>t+10).map(i=>({...Fx(e.at(i)),atM:Math.round(i-t)}))}},compute:()=>F(async()=>{const{BalloonFlight:l}=await import("./BalloonFlight-CGXmDbNq.js");return{BalloonFlight:l}},[],import.meta.url).then(({BalloonFlight:l})=>e=>l.bodiesOf(e)),editor:()=>F(async()=>{const{BalloonEditor:l}=await import("./BalloonEditor-Drb5evP5.js");return{BalloonEditor:l}},__vite__mapDeps([8,1,6,7,9]),import.meta.url).then(({BalloonEditor:l})=>(e,t,i)=>new l(e,t,i))},_5=$t.catalog({en:()=>F(()=>import("./AirshipKindMessages_en-DzGapVTV.js"),[],import.meta.url).then(l=>l.airshipKindMessages_en),fr:()=>F(()=>import("./AirshipKindMessages_fr-BTXNsW5W.js"),[],import.meta.url).then(l=>l.airshipKindMessages_fr),es:()=>F(()=>import("./AirshipKindMessages_es-TE93uMSC.js"),[],import.meta.url).then(l=>l.airshipKindMessages_es),it:()=>F(()=>import("./AirshipKindMessages_it-Cwa3MnJ-.js"),[],import.meta.url).then(l=>l.airshipKindMessages_it)}),Am=(l,e,t,i=5)=>({"nav-left":{color:"#ff2a1a",candela:i,leds:[{at:l,radiusM:.06}]},"nav-right":{color:"#2aff5a",candela:i,leds:[{at:e,radiusM:.06}]},tail:{color:"#ffffff",candela:i,leds:[{at:t,radiusM:.06}]}});class xg{static ALL=[{id:"blimp",modelId:"ufoathome-airship-blimp",sizeM:{widthM:14.72,lengthM:59.46,heightM:17.59},cruiseMS:15,maxSpeedMS:22,color:"#c9ccd1",finColor:"#1d3f8a",albedo:.6,sign:{color:"#fff4d8",luminanceCdM2:150,lit:!0},lights:{...Am([-1.22,-8.6,-9],[1.22,-8.6,-9],[0,0,29.7]),strobe:{color:"#ffffff",candela:400,hz:1,flashS:.06,leds:[{at:[0,-10.15,-9],radiusM:.08}]}},sound:"light-piston",phenomenon:"Airship"},{id:"zeppelin-nt",modelId:"ufoathome-airship-zeppelin-nt",sizeM:{widthM:18.2,lengthM:75.11,heightM:19.55},cruiseMS:19,maxSpeedMS:35,color:"#eef0f2",finColor:"#eef0f2",albedo:.75,sign:{color:"#fff4d8",luminanceCdM2:150,lit:!1},lights:{...Am([-1.32,-8.4,-14],[1.32,-8.4,-14],[0,0,37.5]),strobe:{color:"#ffffff",candela:400,hz:1,flashS:.06,leds:[{at:[0,-9.65,-14],radiusM:.08}]}},sound:"light-piston",phenomenon:"Airship"},{id:"lightship",modelId:"ufoathome-airship-lightship",sizeM:{widthM:10.16,lengthM:39.66,heightM:11.98},cruiseMS:13,maxSpeedMS:20,color:"#f4f4f2",finColor:"#f4f4f2",albedo:.7,glowCdM2:20,lights:Am([-.82,-5.9,-6],[.82,-5.9,-6],[0,0,19.8]),sound:"light-piston",phenomenon:"Airship"},{id:"aerostat",modelId:"ufoathome-airship-aerostat",sizeM:{widthM:25.14,lengthM:63.6,heightM:27.05},cruiseMS:0,maxSpeedMS:0,tethered:!0,color:"#f2f2f0",finColor:"#f2f2f0",albedo:.7,lights:{nose:{color:"#ff2a1a",candela:2e3,hz:.5,flashS:.6,leds:[{at:[0,-4.2,-30],radiusM:.12}]},stern:{color:"#ff2a1a",candela:2e3,hz:.5,flashS:.6,leds:[{at:[0,-6.3,22],radiusM:.12}]}},phenomenon:"Airship"},{id:"rigid",modelId:"ufoathome-airship-rigid",sizeM:{widthM:33.38,lengthM:236.66,heightM:35.79},cruiseMS:32,maxSpeedMS:36,color:"#b9bcbf",finColor:"#b9bcbf",albedo:.55,lights:Am([-3.02,-16.5,-80],[3.02,-16.5,-80],[0,0,118.3],10),sound:"piston-heavy",phenomenon:"Airship"}];static byId(e){return xg.ALL.find(t=>t.id===e)}}const Bx={key:"airships",messages:_5,phenomenon:l=>{const e=typeof l.airship=="string"?l.airship:l.airship?.id;return(xg.byId(e)??xg.ALL[0]).phenomenon},compute:()=>F(async()=>{const{AirshipFlight:l}=await import("./AirshipFlight-Cvl6xWPY.js");return{AirshipFlight:l}},__vite__mapDeps([10,7]),import.meta.url).then(({AirshipFlight:l})=>e=>l.bodiesOf(e)),editor:()=>F(async()=>{const{AirshipEditor:l}=await import("./AirshipEditor-BVlkWwdL.js");return{AirshipEditor:l}},__vite__mapDeps([11,1,6,7,10]),import.meta.url).then(({AirshipEditor:l})=>(e,t,i)=>new l(e,t,i))},s3=Xe.point("interpretations").provide(Xe.BUILT_IN,[{id:Rx.key,name:"Decoy flares",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Rx},{id:Ox.key,name:"Sky lanterns",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Ox},{id:Lx.key,name:"Birds",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Lx},{id:Nx.key,name:"Drones",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Nx},{id:Ux.key,name:"Balloons",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Ux},{id:Bx.key,name:"Airships",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Bx}]);class to{static kinds(){return s3.map(e=>Wt.of(e))}}const zx=Object.freeze(Object.defineProperty({__proto__:null,INTERPRETATION_SOURCES:s3,InterpretationRegistry:to},Symbol.toStringTag,{value:"Module"}));class xi{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static INTERVIEW_EVENT="interview";static check(e){return Tn.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===xi.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===xi.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===xi.INTERPRETATION_EVENT?s.sighting!==void 0&&i.includes(s.sighting):s.eventType!==xi.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===xi.SIGHTING_EVENT?a.interpretationOf:a.eventType===xi.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 xi.withModelsFrom(xt.strip({title:e.title,bodies:e.bodies??[],smoke:e.smoke,findings:e.findings,...Wt.computedPart(e,to.kinds())}).recording,t);if(!e.url)return{title:e.title,bodies:[]};const s=new URL(e.url,t).href,n=await i(s),r=xt.strip("timeline"in n&&n.interpretation?n.interpretation:n).recording;return xi.withModelsFrom({title:e.title??r.title,bodies:r.bodies??[],smoke:r.smoke,findings:r.findings,...Wt.computedPart(r,to.kinds())},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 W{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=W.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=W.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=W.draw('<path d="M5 3.2v9.6L12.6 8z"/>',"currentColor");static PAUSE=W.draw('<path d="M5.5 3.5v9M10.5 3.5v9"/>');static RECORD=W.draw('<circle cx="8" cy="8" r="4.2" fill="var(--error, #d93025)" stroke="none"/>');static STOP=W.draw('<rect x="4" y="4" width="8" height="8" rx="1.2"/>',"currentColor");static PREVIOUS_MARK=W.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=W.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=W.draw('<path d="M4 4l8 8M12 4l-8 8"/>');static PLUS=W.draw('<path d="M8 3v10M3 8h10"/>');static COPY=W.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=W.draw('<circle cx="8" cy="8" r="6"/><path d="M8 4.6V8l2.4 1.6"/>');static INTERVIEW=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.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=W.draw('<path d="M4 1.8h5.2L12.5 5v9.2H4z"/><path d="M9 1.8V5.2h3.5"/>');static RAIN=W.draw('<path d="M4.6 9.3h6.6a2.3 2.3 0 0 0 .3-4.6 3.4 3.4 0 0 0-6.5-.5 2.6 2.6 0 0 0-.4 5.1z"/><path d="M5.6 11.3l-.8 2.2M8.3 11.3l-.8 2.2M11 11.3l-.8 2.2"/>');static WIND=W.draw('<path d="M2 6.2h8.3a2 2 0 1 0-2-2"/><path d="M2 9.6h10.3a1.9 1.9 0 1 1-1.9 1.9"/><path d="M2 13h4.5"/>');static AIRCRAFT=W.draw('<path d="M8 1.8c.6 0 .9.8.9 1.8v3l5.1 2.9v1.3L8.9 9.4v2.8l1.6 1.2v1.1L8 13.8l-2.5.7v-1.1l1.6-1.2V9.4L2 10.8V9.5l5.1-2.9v-3c0-1 .3-1.8.9-1.8z"/>');static LANTERN=W.draw('<path d="M5.2 4.6h5.6l-.9 7.2H6.1z"/><path d="M6.5 4.6V3h3v1.6"/><path d="M8 11.8v2.4"/><path d="M8 7.2c.7.6.7 1.5 0 2.1-.7-.6-.7-1.5 0-2.1z"/>');static BIRD=W.draw('<path d="M1.8 7.8c2-1.8 4-1.6 6.2.9 2.2-2.5 4.2-2.7 6.2-.9"/>');static BALLOON=W.draw('<path d="M8 1.8c2.6 0 4.3 2 4.3 4.4 0 2.7-2.3 4.8-4.3 5.6-2-.8-4.3-2.9-4.3-5.6 0-2.4 1.7-4.4 4.3-4.4z"/><path d="M8 11.8c-.6 1-.2 1.6.4 2.4"/>');static AIRSHIP=W.draw('<ellipse cx="7.4" cy="6.8" rx="5.6" ry="2.9"/><path d="M12.4 5.4 14.6 3.8v6l-2.2-1.6"/><path d="M6 9.7h2.8v1.6H6z"/>');static AURORA=W.draw('<path d="M1.8 6.2c2-2.2 4.2.8 6.2-1.2s4.2.8 6.2-1.2"/><path d="M3.6 6v5.6M6.4 6v7M9.4 5.2v6.2M12.2 4.6v5"/>');static DRONE=W.draw('<rect x="6" y="6.5" width="4" height="3" rx=".8"/><path d="M6 7 3.8 4.8M10 7l2.2-2.2M6 9l-2.2 2.2M10 9l2.2 2.2"/><path d="M2 4.8h3.6M10.4 4.8H14M2 11.2h3.6M10.4 11.2H14"/>');static LAUNCH=W.draw('<path d="M8 1.8c2 1.6 3 3.9 3 6.6V11H5V8.4c0-2.7 1-5 3-6.6z"/><path d="M5 9.2 3.2 11v2.2L5 12M11 9.2l1.8 1.8v2.2L11 12"/><path d="M7 13.2 8 15l1-1.8"/><circle cx="8" cy="6.5" r="1.1"/>');static SEARCHLIGHT=W.draw('<path d="M7.2 12.2 4 4.2M8.8 12.2 12 4.2"/><ellipse cx="3.6" cy="3.2" rx="1.8" ry=".8"/><ellipse cx="12.4" cy="3.2" rx="1.8" ry=".8"/><path d="M6 12.4h4v1.8H6z"/>');static BEAM=W.draw('<path d="M7.4 12.6 4.2 2M8.6 12.6 11.8 2"/><path d="M6.2 12.6h3.6v1.8H6.2z"/>');static SHAPES=W.draw('<circle cx="5.6" cy="6" r="3.2"/><rect x="8.2" y="8.2" width="5.8" height="5.8" rx="1"/>');static BODIES=W.draw('<path d="M8 1.8 13.5 4.8v6.4L8 14.2 2.5 11.2V4.8z"/><path d="M2.5 4.8 8 7.8l5.5-3M8 7.8v6.4"/>');static ID_CARD=W.draw('<rect x="2" y="3.5" width="12" height="9" rx="1.5"/><circle cx="5.8" cy="7.2" r="1.4"/><path d="M3.8 10.8c.4-1.1 1.1-1.6 2-1.6s1.6.5 2 1.6M9.5 6.5h3M9.5 9h2.5"/>');static STRANGE=W.draw('<circle cx="8" cy="8" r="6"/><path d="M6.3 6.3a1.8 1.8 0 1 1 2.5 1.7c-.5.2-.8.6-.8 1.1v.4"/><path d="M8 11.6v.1"/>');static EYE=W.draw('<path d="M1.5 8s2.4-4.3 6.5-4.3S14.5 8 14.5 8 12.1 12.3 8 12.3 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="2"/>');static PERCEPTION=W.draw('<circle cx="8" cy="8" r="2"/><path d="M8 2v2M8 12v2M2 8h2M12 8h2M3.8 3.8l1.4 1.4M10.8 10.8l1.4 1.4M3.8 12.2l1.4-1.4M10.8 5.2l1.4-1.4"/>');static GAUGE=W.draw('<path d="M2.5 11a5.5 5.5 0 0 1 11 0"/><path d="M8 11l2.6-3.2"/><circle cx="8" cy="11" r=".9"/>');static HAZE=W.draw('<path d="M2 5.5h12M3.5 8.5h9M2 11.5h12"/>');static MOON=W.draw('<path d="M10.8 2.6a5.6 5.6 0 1 0 2.6 9.6 4.6 4.6 0 0 1-2.6-9.6z"/>');static SLIDERS=W.draw('<path d="M2.5 4h11M2.5 8h11M2.5 12h11"/><circle cx="6" cy="4" r="1.3" fill="var(--ground-raised, Canvas)"/><circle cx="10.5" cy="8" r="1.3" fill="var(--ground-raised, Canvas)"/><circle cx="5" cy="12" r="1.3" fill="var(--ground-raised, Canvas)"/>');static GLOBE=W.draw('<circle cx="8" cy="8" r="6"/><path d="M2 8h12M8 2c1.8 1.7 2.6 3.7 2.6 6S9.8 12.3 8 14M8 2C6.2 3.7 5.4 5.7 5.4 8s.8 4.3 2.6 6"/>');static GAZE=W.draw('<circle cx="8" cy="8" r="6"/><path d="M10.6 5.4 9 9 5.4 10.6 7 7z"/>');static EVENTS=W.draw('<path d="M2 8h12"/><circle cx="4" cy="8" r="1.4"/><circle cx="8.5" cy="8" r="1.4"/><circle cx="12.5" cy="8" r="1.4"/>');static TOWN=W.draw('<path d="M1.5 13.5h13"/><path d="M3 13.5V9l2.5-2L8 9v4.5"/><path d="M10 13.5v-6h3.5v6"/>');static FLAG=W.draw('<path d="M4 14V2.5"/><path d="M4 3h7.5l-1.8 2.6L11.5 8.2H4"/>');static MIC=W.draw('<rect x="6" y="2" width="4" height="7.5" rx="2"/><path d="M3.8 7.8a4.2 4.2 0 0 0 8.4 0M8 12v2"/>');static CAMERA=W.draw('<path d="M2 5.5h2.6l1.2-1.8h4.4l1.2 1.8H14V13H2z"/><circle cx="8" cy="9" r="2.3"/>');static LANDMARK=W.draw('<path d="M1.5 13.5 6 5l3 5.2 1.6-2.4 3.9 5.7z"/>');static GHOST=W.draw('<path d="M8 2.2 13 5.1v5.8L8 13.8 3 10.9V5.1z"/>');static TRACE=W.draw('<path d="M2.5 12.5c2-4 4-1 6-4s3.5-3 5-5"/><circle cx="2.5" cy="12.5" r="1"/><circle cx="13.5" cy="3.5" r="1"/>');static APPEARANCE=W.draw('<path d="M8 2l1.5 4.5L14 8l-4.5 1.5L8 14l-1.5-4.5L2 8l4.5-1.5z"/>');static RULER=W.draw('<rect x="1.8" y="5.5" width="12.4" height="5" rx="1"/><path d="M4.5 5.5v2M7 5.5v2.6M9.5 5.5v2M12 5.5v2.6"/>');static PATH=W.draw('<path d="M2.5 12C4 6 9 3.5 13 4"/><path d="M10.5 2.3 13 4l-2 2.3"/>');static IDEA=W.draw('<path d="M5.5 10.5a4 4 0 1 1 5 0c-.6.5-.9 1-.9 1.6v.4H6.4v-.4c0-.6-.3-1.1-.9-1.6z"/><path d="M6.5 14.2h3"/>');static section(e){return{"label-section-identity":W.ID_CARD,"label-section-profile":W.WITNESS,"label-section-testimony":W.INTERVIEW,"strangeness-section":W.STRANGE,"label-section-vision":W.EYE,"label-section-perception":W.PERCEPTION,"witness-conditions":W.GAUGE,"viewing-conditions":W.HAZE,"moon-gauge":W.MOON,"error-parameters":W.SLIDERS,"label-section-coordinates":W.GLOBE,"label-section-gaze":W.GAZE,"label-section-events":W.EVENTS,"label-section-night-sky":W.STAR,"around-section":W.TOWN,"label-section-survey":W.ENVIRONMENT,"label-section-period":W.DATE,"label-milestones":W.FLAG,"label-section-heard":W.SOUND,"label-section-sound-recording":W.MIC,"label-section-picture":W.PICTURES,"label-section-pose":W.CAMERA,"label-reference-landmarks":W.LANDMARK,"label-reference-ghosts":W.GHOST,"label-trace-import":W.TRACE,"label-section-appearance":W.APPEARANCE,"label-section-size":W.RULER,"label-section-path":W.PATH,"label-section-phenomenon-events":W.EVENTS,"label-section-bodies-events":W.EVENTS,candidates:W.IDEA}[e]}static part(e){return{"weather-precipitation":W.RAIN,"weather-clouds":W.SKY,"weather-wind":W.WIND,"weather-aircraft":W.AIRCRAFT,"interpretation-lanterns":W.LANTERN,"interpretation-birds":W.BIRD,"interpretation-drones":W.DRONE,"interpretation-balloons":W.BALLOON,"interpretation-airships":W.AIRSHIP,"sky-event-launches":W.LAUNCH,"sky-event-beams":W.BEAM,"sky-event-searchlights":W.SEARCHLIGHT,"sky-event-reentries":W.FIREBALL,"sky-event-auroras":W.AURORA,"shape-shapes":W.SHAPES,"shape-bodies":W.BODIES}[e]}static BY_GLYPH={"🗑":W.TRASH,"🎯":W.TARGET,"+":W.PLUS,"✕":W.CLOSE,"▶":W.PLAY,"⏸":W.PAUSE,"⏺":W.RECORD,"⏹":W.STOP};static show(e,t){if(e.dataset.icon===t&&e.firstChild)return;const i=W.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; }
|
|
@@ -241,7 +241,7 @@ button.event-mark:focus-visible { outline: 2px solid var(--tl-sky); outline-offs
|
|
|
241
241
|
background: var(--line-strong, rgba(127, 127, 127, .5)); opacity: 0; transition: opacity .15s ease; }
|
|
242
242
|
.column-resize:is(:hover, :focus-visible, .dragging)::after { opacity: 1; }
|
|
243
243
|
.column-resize:focus-visible { outline: none; }
|
|
244
|
-
`;static MIN_PX=200;static OTHER_MIN_PX=320;label(e){this.grip.title=e,this.grip.setAttribute("aria-label",e)}set(e){const t=this.host;if(e===void 0)t.style.removeProperty(this.property);else{const i=Math.max(this.minPx,t.getBoundingClientRect().width-io.OTHER_MIN_PX);t.style.setProperty(this.property,`${Math.round(Math.min(i,Math.max(this.minPx,e)))}px`)}try{e===void 0?localStorage.removeItem(this.key):localStorage.setItem(this.key,t.style.getPropertyValue(this.property))}catch{}}}class si{static NAMES=["weather","place","lightPollution","decor"];static KEYS={weather:["weatherTrack","weatherSource"],place:["place"],lightPollution:["lightPollution"],decor:["decor"]};static annexName(e,t){return`${e}.${t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}.json`}static taken(e,t){const i={};if(e==="decor")return Array.isArray(t.decor)&&(i.decor=t.decor.filter(si.surveyed)),i;for(const s of si.KEYS[e])t[s]!==void 0&&(i[s]=t[s]);return i}static strip(e,t){if(e==="decor"){const i=Array.isArray(t.decor)?t.decor.filter(s=>!si.surveyed(s)):[];i.length>0?t.decor=i:delete t.decor;return}for(const i of si.KEYS[e])delete t[i]}static put(e,t,i){if(e==="decor"){if(!Array.isArray(i.decor))return;const s=Array.isArray(t.decor)?t.decor.filter(n=>!si.surveyed(n)):[];t.decor=[...s,...i.decor];return}for(const s of si.KEYS[e])i[s]!==void 0&&(t[s]=i[s])}static surveyed(e){return typeof e=="object"&&e!==null&&typeof e.origin=="string"}static fromFile(e,t){return e?.[t]!==void 0&&e[t].live!==!0}}class ms{static NAMES=["relief","imagery","roads","water","railways","upperAir","map"];static TERRAIN=["relief","imagery","roads","water","railways"];static held(e,t){if(!e||e.live)return;const i=e[t];return i&&!i.live&&!i.refresh&&i.src!==void 0?i:void 0}static isLive(e,t){return e?.live===!0||e?.[t]?.live===!0}static annexName(e,t){const i=t==="relief"||t==="imagery"||t==="map"?"zip":"json",s=t.replace(/[A-Z]/g,n=>`-${n.toLowerCase()}`);return`${e}.${s}.${i}`}static isEmpty(e){return!e||!e.live&&ms.NAMES.every(t=>!e[t])&&si.NAMES.every(t=>!e[t])}}class ys{static files=new Map;static hold(e){for(const[t,i]of e)ys.files.set(ys.key(t),i)}static releaseCopies(){for(const[e,t]of ys.files)t.local||ys.files.delete(e)}static clear(){ys.files.clear()}static localBase(){return new URL(`local/${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}/`,location.href).href}static read(e){const t=ys.files.get(ys.key(e));return t===void 0?void 0:structuredClone(t.json)}static changed(...e){return e.some(t=>t!==void 0&&ys.files.get(ys.key(t))?.changed===!0)}static local(e){return e!==void 0&&ys.files.get(ys.key(e))?.local===!0}static key(e){const t=new URL(e,location.href);return t.hash="",t.href}}class il extends Error{constructor(e,t,i){super(`${e}: ${t}${i===void 0?"":` (HTTP ${i})`}`),this.kind=e,this.url=t,this.status=i,this.name="SightingFetchError"}}class aa{static async recording(e){const t=ys.read(e);if(t!==void 0)return t;const i=await aa.json(e);for(const s of si.NAMES){const n=i?.snapshots?.[s];if(!(!n?.src||n.live))try{const r=Tn.recording(await aa.json(new URL(n.src,new URL(e,location.href)).href));si.put(s,i,r)}catch{}}return i}static async json(e){const t=new URL(e,location.href),i=ys.read(t.href);if(i!==void 0)return i;if(location.protocol==="https:"&&t.protocol==="http:")throw new il("mixed-content",e);let s;try{s=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!s.ok)throw new il("status",e,s.status);try{return await s.json()}catch{throw new il("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new il("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new il("cors",e)}catch{return new il("unreachable",e)}}}const k5=Object.freeze(Object.defineProperty({__proto__:null,SightingFetch:aa,SightingFetchError:il},Symbol.toStringTag,{value:"Module"}));class _o{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(e,t,i){const s=new URL(`${e}.mjs`,t);return s.href.startsWith(`${_o.CDN}/`)?`${i}/lib/${e}.mjs`:(s.pathname=s.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),s.href)}static VERSION_PARAMETER="v";static pinnable(e){return e in _o.DIRECTORIES}static pinnedLink(e,t){const i=new URL(e);return i.searchParams.set(_o.VERSION_PARAMETER,t),i.href}static pinned(e,t){return`${_o.CDN}/${_o.PACKAGE}@${t}/${_o.DIRECTORIES[e]}/${e}.mjs`}}class $h{static PRODUCTION="https://ufoathome.org";static home(){try{const e=new URL(import.meta.url),t=new URL(location.href);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]"||t.hostname.endsWith(".localhost"))&&e.origin===t.origin?t.origin:$h.PRODUCTION}catch{return $h.PRODUCTION}}}const Gr=["en","fr","es","it"],D5={en:()=>F(()=>import("./UfoMessages_en-DdCKc-Ez.js"),[],import.meta.url).then(l=>l.ufoMessages_en),fr:()=>F(()=>import("./UfoMessages_fr-CGkQBn5r.js"),[],import.meta.url).then(l=>l.ufoMessages_fr),es:()=>F(()=>import("./UfoMessages_es-CO-v8Jl6.js"),[],import.meta.url).then(l=>l.ufoMessages_es),it:()=>F(()=>import("./UfoMessages_it-BScqxIaH.js"),[],import.meta.url).then(l=>l.ufoMessages_it)},R5=$t.catalog(D5),C5={en:()=>F(()=>import("./SightingEditorMessages_en-V_dJYjNb.js"),__vite__mapDeps([12,13]),import.meta.url).then(l=>l.sightingEditorMessages_en),fr:()=>F(()=>import("./SightingEditorMessages_fr-zxTvQa2I.js"),__vite__mapDeps([14,15]),import.meta.url).then(l=>l.sightingEditorMessages_fr),es:()=>F(()=>import("./SightingEditorMessages_es-DauDuhPa.js"),__vite__mapDeps([16,17]),import.meta.url).then(l=>l.sightingEditorMessages_es),it:()=>F(()=>import("./SightingEditorMessages_it-vvaao68O.js"),__vite__mapDeps([18,19]),import.meta.url).then(l=>l.sightingEditorMessages_it)},eM=$t.catalog(C5);function SH(l){return eM.load(l)}const O5={en:()=>F(()=>import("./SightingMessages_en-Drcr3k4V.js"),__vite__mapDeps([20,13]),import.meta.url).then(l=>l.sightingMessages_en),fr:()=>F(()=>import("./SightingMessages_fr-7IYuW095.js"),__vite__mapDeps([21,15]),import.meta.url).then(l=>l.sightingMessages_fr),es:()=>F(()=>import("./SightingMessages_es-BcaWM7Oy.js"),__vite__mapDeps([22,17]),import.meta.url).then(l=>l.sightingMessages_es),it:()=>F(()=>import("./SightingMessages_it-BhDmZn6p.js"),__vite__mapDeps([23,19]),import.meta.url).then(l=>l.sightingMessages_it)},AH=$t.catalog(O5),L5={en:()=>F(()=>import("./CaseMessages_en-BC0lku35.js"),[],import.meta.url).then(l=>l.caseMessages_en),fr:()=>F(()=>import("./CaseMessages_fr-D_6J6ONO.js"),[],import.meta.url).then(l=>l.caseMessages_fr),es:()=>F(()=>import("./CaseMessages_es-Cbktn5vj.js"),[],import.meta.url).then(l=>l.caseMessages_es),it:()=>F(()=>import("./CaseMessages_it-CYyww4oG.js"),[],import.meta.url).then(l=>l.caseMessages_it)},P5=$t.catalog(L5);function TH(l){return P5.load(l)}const N5={en:()=>F(()=>import("./ShareMessages_en-B43x8LgJ.js"),[],import.meta.url).then(l=>l.shareMessages_en),fr:()=>F(()=>import("./ShareMessages_fr-CzZyVbbX.js"),[],import.meta.url).then(l=>l.shareMessages_fr),es:()=>F(()=>import("./ShareMessages_es-DZCJojSc.js"),[],import.meta.url).then(l=>l.shareMessages_es),it:()=>F(()=>import("./ShareMessages_it-C_Z6eDQK.js"),[],import.meta.url).then(l=>l.shareMessages_it)},F5=$t.catalog(N5);function U5(l){switch(l){case"fr":return F(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr);case"es":return F(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(e=>e.tagNames_es);case"it":return F(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(e=>e.tagNames_it);default:return Promise.resolve({})}}const B5={en:()=>F(()=>import("./BodyEditorMessages_en-CckxSS1L.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_en),fr:()=>F(()=>import("./BodyEditorMessages_fr-638ypdqf.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_fr),es:()=>F(()=>import("./BodyEditorMessages_es-B8GlFFBo.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_es),it:()=>F(()=>import("./BodyEditorMessages_it-SKpMkHFI.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_it)},z5={en:()=>F(()=>import("./CaseEditorMessages_en-pog3M_U6.js"),[],import.meta.url).then(l=>l.caseEditorMessages_en),fr:()=>F(()=>import("./CaseEditorMessages_fr-BOKVeIXM.js"),[],import.meta.url).then(l=>l.caseEditorMessages_fr),es:()=>F(()=>import("./CaseEditorMessages_es-Dz1N0VpM.js"),[],import.meta.url).then(l=>l.caseEditorMessages_es),it:()=>F(()=>import("./CaseEditorMessages_it-BKAkbKq-.js"),[],import.meta.url).then(l=>l.caseEditorMessages_it)},H5={en:()=>F(()=>import("./ReadingSensitivityMessages_en-ChQHFyxb.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_en),fr:()=>F(()=>import("./ReadingSensitivityMessages_fr-Dl4a8udu.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_fr),es:()=>F(()=>import("./ReadingSensitivityMessages_es-BbFqHsvR.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_es),it:()=>F(()=>import("./ReadingSensitivityMessages_it-CwiJfUo_.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_it)},n3=$t.catalog(H5),G5={en:()=>F(()=>import("./HvsMessages_en-BiLhEAxJ.js"),[],import.meta.url).then(l=>l.hvsMessages_en),fr:()=>F(()=>import("./HvsMessages_fr-DkvE2qm1.js"),[],import.meta.url).then(l=>l.hvsMessages_fr),es:()=>F(()=>import("./HvsMessages_es-Cbj_6eFs.js"),[],import.meta.url).then(l=>l.hvsMessages_es),it:()=>F(()=>import("./HvsMessages_it-BIJ87Uyb.js"),[],import.meta.url).then(l=>l.hvsMessages_it)},V5=$t.catalog(G5),W5={en:()=>F(()=>import("./ScenarioSweepMessages_en-Bf4BscDU.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_en),fr:()=>F(()=>import("./ScenarioSweepMessages_fr-DlPsO6oI.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_fr),es:()=>F(()=>import("./ScenarioSweepMessages_es-CBHQfuRB.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_es),it:()=>F(()=>import("./ScenarioSweepMessages_it-DANW3_la.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_it)},Hx=$t.catalog(W5),$5={en:()=>F(()=>import("./CaseExportMessages_en-jHlu58Y7.js"),[],import.meta.url).then(l=>l.caseExportMessages_en),fr:()=>F(()=>import("./CaseExportMessages_fr-sDfEgjWg.js"),[],import.meta.url).then(l=>l.caseExportMessages_fr),es:()=>F(()=>import("./CaseExportMessages_es-dCQQFgjq.js"),[],import.meta.url).then(l=>l.caseExportMessages_es),it:()=>F(()=>import("./CaseExportMessages_it-BJaglZtP.js"),[],import.meta.url).then(l=>l.caseExportMessages_it)},K5=$t.catalog($5),X5={en:()=>F(()=>import("./InterviewMessages_en-Ikx6GjEd.js"),[],import.meta.url).then(l=>l.interviewMessages_en),fr:()=>F(()=>import("./InterviewMessages_fr-DT0gXAKD.js"),[],import.meta.url).then(l=>l.interviewMessages_fr),es:()=>F(()=>import("./InterviewMessages_es-DKWWyrnb.js"),[],import.meta.url).then(l=>l.interviewMessages_es),it:()=>F(()=>import("./InterviewMessages_it-CF_9MYPt.js"),[],import.meta.url).then(l=>l.interviewMessages_it)},IH=$t.catalog(X5),Y5=$t.catalog(z5),_H=$t.catalog(B5),q5=$t.catalog({en:()=>F(()=>import("./SceneNames_en-CTJiUG-r.js"),[],import.meta.url).then(l=>l.sceneNames_en),fr:()=>F(()=>import("./SceneNames_fr-C36uyjbM.js"),[],import.meta.url).then(l=>l.sceneNames_fr),es:()=>F(()=>import("./SceneNames_es-DHZMjSqb.js"),[],import.meta.url).then(l=>l.sceneNames_es),it:()=>F(()=>import("./SceneNames_it-BQJQm2rT.js"),[],import.meta.url).then(l=>l.sceneNames_it)});function r3(l){return q5.load(l)}const j5=$t.catalog({en:()=>F(()=>import("./CloudEditorMessages_en-SmcRKW1O.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_en),fr:()=>F(()=>import("./CloudEditorMessages_fr-SvL-CR04.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_fr),es:()=>F(()=>import("./CloudEditorMessages_es-DFCuS9Qg.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_es),it:()=>F(()=>import("./CloudEditorMessages_it-BvfiHWV9.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_it)}),Z5=`
|
|
244
|
+
`;static MIN_PX=200;static OTHER_MIN_PX=320;label(e){this.grip.title=e,this.grip.setAttribute("aria-label",e)}set(e){const t=this.host;if(e===void 0)t.style.removeProperty(this.property);else{const i=Math.max(this.minPx,t.getBoundingClientRect().width-io.OTHER_MIN_PX);t.style.setProperty(this.property,`${Math.round(Math.min(i,Math.max(this.minPx,e)))}px`)}try{e===void 0?localStorage.removeItem(this.key):localStorage.setItem(this.key,t.style.getPropertyValue(this.property))}catch{}}}class si{static NAMES=["weather","place","lightPollution","decor"];static KEYS={weather:["weatherTrack","weatherSource"],place:["place"],lightPollution:["lightPollution"],decor:["decor"]};static annexName(e,t){return`${e}.${t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}.json`}static taken(e,t){const i={};if(e==="decor")return Array.isArray(t.decor)&&(i.decor=t.decor.filter(si.surveyed)),i;for(const s of si.KEYS[e])t[s]!==void 0&&(i[s]=t[s]);return i}static strip(e,t){if(e==="decor"){const i=Array.isArray(t.decor)?t.decor.filter(s=>!si.surveyed(s)):[];i.length>0?t.decor=i:delete t.decor;return}for(const i of si.KEYS[e])delete t[i]}static put(e,t,i){if(e==="decor"){if(!Array.isArray(i.decor))return;const s=Array.isArray(t.decor)?t.decor.filter(n=>!si.surveyed(n)):[];t.decor=[...s,...i.decor];return}for(const s of si.KEYS[e])i[s]!==void 0&&(t[s]=i[s])}static surveyed(e){return typeof e=="object"&&e!==null&&typeof e.origin=="string"}static fromFile(e,t){return e?.[t]!==void 0&&e[t].live!==!0}}class ms{static NAMES=["relief","imagery","roads","water","railways","upperAir","map"];static TERRAIN=["relief","imagery","roads","water","railways"];static held(e,t){if(!e||e.live)return;const i=e[t];return i&&!i.live&&!i.refresh&&i.src!==void 0?i:void 0}static isLive(e,t){return e?.live===!0||e?.[t]?.live===!0}static annexName(e,t){const i=t==="relief"||t==="imagery"||t==="map"?"zip":"json",s=t.replace(/[A-Z]/g,n=>`-${n.toLowerCase()}`);return`${e}.${s}.${i}`}static isEmpty(e){return!e||!e.live&&ms.NAMES.every(t=>!e[t])&&si.NAMES.every(t=>!e[t])}}class ys{static files=new Map;static hold(e){for(const[t,i]of e)ys.files.set(ys.key(t),i)}static releaseCopies(){for(const[e,t]of ys.files)t.local||ys.files.delete(e)}static clear(){ys.files.clear()}static localBase(){return new URL(`local/${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}/`,location.href).href}static read(e){const t=ys.files.get(ys.key(e));return t===void 0?void 0:structuredClone(t.json)}static changed(...e){return e.some(t=>t!==void 0&&ys.files.get(ys.key(t))?.changed===!0)}static local(e){return e!==void 0&&ys.files.get(ys.key(e))?.local===!0}static key(e){const t=new URL(e,location.href);return t.hash="",t.href}}class il extends Error{constructor(e,t,i){super(`${e}: ${t}${i===void 0?"":` (HTTP ${i})`}`),this.kind=e,this.url=t,this.status=i,this.name="SightingFetchError"}}class aa{static async recording(e){const t=ys.read(e);if(t!==void 0)return t;const i=await aa.json(e);for(const s of si.NAMES){const n=i?.snapshots?.[s];if(!(!n?.src||n.live))try{const r=Tn.recording(await aa.json(new URL(n.src,new URL(e,location.href)).href));si.put(s,i,r)}catch{}}return i}static async json(e){const t=new URL(e,location.href),i=ys.read(t.href);if(i!==void 0)return i;if(location.protocol==="https:"&&t.protocol==="http:")throw new il("mixed-content",e);let s;try{s=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!s.ok)throw new il("status",e,s.status);try{return await s.json()}catch{throw new il("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new il("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new il("cors",e)}catch{return new il("unreachable",e)}}}const k5=Object.freeze(Object.defineProperty({__proto__:null,SightingFetch:aa,SightingFetchError:il},Symbol.toStringTag,{value:"Module"}));class _o{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(e,t,i){const s=new URL(`${e}.mjs`,t);return s.href.startsWith(`${_o.CDN}/`)?`${i}/lib/${e}.mjs`:(s.pathname=s.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),s.href)}static VERSION_PARAMETER="v";static pinnable(e){return e in _o.DIRECTORIES}static pinnedLink(e,t){const i=new URL(e);return i.searchParams.set(_o.VERSION_PARAMETER,t),i.href}static pinned(e,t){return`${_o.CDN}/${_o.PACKAGE}@${t}/${_o.DIRECTORIES[e]}/${e}.mjs`}}class $h{static PRODUCTION="https://ufoathome.org";static home(){try{const e=new URL(import.meta.url),t=new URL(location.href);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]"||t.hostname.endsWith(".localhost"))&&e.origin===t.origin?t.origin:$h.PRODUCTION}catch{return $h.PRODUCTION}}}const Gr=["en","fr","es","it"],D5={en:()=>F(()=>import("./UfoMessages_en-DdCKc-Ez.js"),[],import.meta.url).then(l=>l.ufoMessages_en),fr:()=>F(()=>import("./UfoMessages_fr-CGkQBn5r.js"),[],import.meta.url).then(l=>l.ufoMessages_fr),es:()=>F(()=>import("./UfoMessages_es-CO-v8Jl6.js"),[],import.meta.url).then(l=>l.ufoMessages_es),it:()=>F(()=>import("./UfoMessages_it-BScqxIaH.js"),[],import.meta.url).then(l=>l.ufoMessages_it)},R5=$t.catalog(D5),C5={en:()=>F(()=>import("./SightingEditorMessages_en-CS2iXwDm.js"),__vite__mapDeps([12,13]),import.meta.url).then(l=>l.sightingEditorMessages_en),fr:()=>F(()=>import("./SightingEditorMessages_fr-AYgrnKFD.js"),__vite__mapDeps([14,15]),import.meta.url).then(l=>l.sightingEditorMessages_fr),es:()=>F(()=>import("./SightingEditorMessages_es-C8Vw_4b_.js"),__vite__mapDeps([16,17]),import.meta.url).then(l=>l.sightingEditorMessages_es),it:()=>F(()=>import("./SightingEditorMessages_it-DZyzwScx.js"),__vite__mapDeps([18,19]),import.meta.url).then(l=>l.sightingEditorMessages_it)},eM=$t.catalog(C5);function SH(l){return eM.load(l)}const O5={en:()=>F(()=>import("./SightingMessages_en-D90vDTQ7.js"),__vite__mapDeps([20,13]),import.meta.url).then(l=>l.sightingMessages_en),fr:()=>F(()=>import("./SightingMessages_fr-Gq3IMFTE.js"),__vite__mapDeps([21,15]),import.meta.url).then(l=>l.sightingMessages_fr),es:()=>F(()=>import("./SightingMessages_es-D8laK6OY.js"),__vite__mapDeps([22,17]),import.meta.url).then(l=>l.sightingMessages_es),it:()=>F(()=>import("./SightingMessages_it-BXDxv-lE.js"),__vite__mapDeps([23,19]),import.meta.url).then(l=>l.sightingMessages_it)},AH=$t.catalog(O5),L5={en:()=>F(()=>import("./CaseMessages_en-BC0lku35.js"),[],import.meta.url).then(l=>l.caseMessages_en),fr:()=>F(()=>import("./CaseMessages_fr-D_6J6ONO.js"),[],import.meta.url).then(l=>l.caseMessages_fr),es:()=>F(()=>import("./CaseMessages_es-Cbktn5vj.js"),[],import.meta.url).then(l=>l.caseMessages_es),it:()=>F(()=>import("./CaseMessages_it-CYyww4oG.js"),[],import.meta.url).then(l=>l.caseMessages_it)},P5=$t.catalog(L5);function TH(l){return P5.load(l)}const N5={en:()=>F(()=>import("./ShareMessages_en-B43x8LgJ.js"),[],import.meta.url).then(l=>l.shareMessages_en),fr:()=>F(()=>import("./ShareMessages_fr-CzZyVbbX.js"),[],import.meta.url).then(l=>l.shareMessages_fr),es:()=>F(()=>import("./ShareMessages_es-DZCJojSc.js"),[],import.meta.url).then(l=>l.shareMessages_es),it:()=>F(()=>import("./ShareMessages_it-C_Z6eDQK.js"),[],import.meta.url).then(l=>l.shareMessages_it)},F5=$t.catalog(N5);function U5(l){switch(l){case"fr":return F(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr);case"es":return F(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(e=>e.tagNames_es);case"it":return F(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(e=>e.tagNames_it);default:return Promise.resolve({})}}const B5={en:()=>F(()=>import("./BodyEditorMessages_en-CckxSS1L.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_en),fr:()=>F(()=>import("./BodyEditorMessages_fr-638ypdqf.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_fr),es:()=>F(()=>import("./BodyEditorMessages_es-B8GlFFBo.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_es),it:()=>F(()=>import("./BodyEditorMessages_it-SKpMkHFI.js"),[],import.meta.url).then(l=>l.bodyEditorMessages_it)},z5={en:()=>F(()=>import("./CaseEditorMessages_en-pog3M_U6.js"),[],import.meta.url).then(l=>l.caseEditorMessages_en),fr:()=>F(()=>import("./CaseEditorMessages_fr-BOKVeIXM.js"),[],import.meta.url).then(l=>l.caseEditorMessages_fr),es:()=>F(()=>import("./CaseEditorMessages_es-Dz1N0VpM.js"),[],import.meta.url).then(l=>l.caseEditorMessages_es),it:()=>F(()=>import("./CaseEditorMessages_it-BKAkbKq-.js"),[],import.meta.url).then(l=>l.caseEditorMessages_it)},H5={en:()=>F(()=>import("./ReadingSensitivityMessages_en-ChQHFyxb.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_en),fr:()=>F(()=>import("./ReadingSensitivityMessages_fr-Dl4a8udu.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_fr),es:()=>F(()=>import("./ReadingSensitivityMessages_es-BbFqHsvR.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_es),it:()=>F(()=>import("./ReadingSensitivityMessages_it-CwiJfUo_.js"),[],import.meta.url).then(l=>l.readingSensitivityMessages_it)},n3=$t.catalog(H5),G5={en:()=>F(()=>import("./HvsMessages_en-BiLhEAxJ.js"),[],import.meta.url).then(l=>l.hvsMessages_en),fr:()=>F(()=>import("./HvsMessages_fr-DkvE2qm1.js"),[],import.meta.url).then(l=>l.hvsMessages_fr),es:()=>F(()=>import("./HvsMessages_es-Cbj_6eFs.js"),[],import.meta.url).then(l=>l.hvsMessages_es),it:()=>F(()=>import("./HvsMessages_it-BIJ87Uyb.js"),[],import.meta.url).then(l=>l.hvsMessages_it)},V5=$t.catalog(G5),W5={en:()=>F(()=>import("./ScenarioSweepMessages_en-Bf4BscDU.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_en),fr:()=>F(()=>import("./ScenarioSweepMessages_fr-DlPsO6oI.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_fr),es:()=>F(()=>import("./ScenarioSweepMessages_es-CBHQfuRB.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_es),it:()=>F(()=>import("./ScenarioSweepMessages_it-DANW3_la.js"),[],import.meta.url).then(l=>l.scenarioSweepMessages_it)},Hx=$t.catalog(W5),$5={en:()=>F(()=>import("./CaseExportMessages_en-jHlu58Y7.js"),[],import.meta.url).then(l=>l.caseExportMessages_en),fr:()=>F(()=>import("./CaseExportMessages_fr-sDfEgjWg.js"),[],import.meta.url).then(l=>l.caseExportMessages_fr),es:()=>F(()=>import("./CaseExportMessages_es-dCQQFgjq.js"),[],import.meta.url).then(l=>l.caseExportMessages_es),it:()=>F(()=>import("./CaseExportMessages_it-BJaglZtP.js"),[],import.meta.url).then(l=>l.caseExportMessages_it)},K5=$t.catalog($5),X5={en:()=>F(()=>import("./InterviewMessages_en-Ikx6GjEd.js"),[],import.meta.url).then(l=>l.interviewMessages_en),fr:()=>F(()=>import("./InterviewMessages_fr-DT0gXAKD.js"),[],import.meta.url).then(l=>l.interviewMessages_fr),es:()=>F(()=>import("./InterviewMessages_es-DKWWyrnb.js"),[],import.meta.url).then(l=>l.interviewMessages_es),it:()=>F(()=>import("./InterviewMessages_it-CF_9MYPt.js"),[],import.meta.url).then(l=>l.interviewMessages_it)},IH=$t.catalog(X5),Y5=$t.catalog(z5),_H=$t.catalog(B5),q5=$t.catalog({en:()=>F(()=>import("./SceneNames_en-CTJiUG-r.js"),[],import.meta.url).then(l=>l.sceneNames_en),fr:()=>F(()=>import("./SceneNames_fr-C36uyjbM.js"),[],import.meta.url).then(l=>l.sceneNames_fr),es:()=>F(()=>import("./SceneNames_es-DHZMjSqb.js"),[],import.meta.url).then(l=>l.sceneNames_es),it:()=>F(()=>import("./SceneNames_it-BQJQm2rT.js"),[],import.meta.url).then(l=>l.sceneNames_it)});function r3(l){return q5.load(l)}const j5=$t.catalog({en:()=>F(()=>import("./CloudEditorMessages_en-SmcRKW1O.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_en),fr:()=>F(()=>import("./CloudEditorMessages_fr-SvL-CR04.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_fr),es:()=>F(()=>import("./CloudEditorMessages_es-DFCuS9Qg.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_es),it:()=>F(()=>import("./CloudEditorMessages_it-BvfiHWV9.js"),[],import.meta.url).then(l=>l.cloudEditorMessages_it)}),Z5=`
|
|
245
245
|
<style>
|
|
246
246
|
/* What the dialog is drawn with: light by default, and the dark set when the system asks for it, as the player and the editors
|
|
247
247
|
are. The form controls follow through color-scheme. Defined here and not by the host, so that any element can hold this dialog;
|
|
@@ -467,8 +467,8 @@ button.event-mark:focus-visible { outline: 2px solid var(--tl-sky); outline-offs
|
|
|
467
467
|
<button id="copy" class="share-copy" type="button"></button>
|
|
468
468
|
</div>
|
|
469
469
|
</dialog>
|
|
470
|
-
`;class vu extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(vu.TAG)||customElements.define(vu.TAG,vu)}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=Z5;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 F5.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?_o.pinnedLink(e.link(),"0.204.
|
|
471
|
-
${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.204.1")),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??=F(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([24,25]),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 Wr extends Error{}class Av{constructor(e){this.name=e}validate(e){return!0}}class a3 extends Av{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new Wr(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new Wr(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class zi{name;min;max;duration;subUnit;validator;constructor(e,t,i,s,n=new a3(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 tM{millisecond;second;minute;hour;day;month;year}class J5 extends tM{}class o3 extends J5{millisecond=new zi("millisecond",0,999,void 0);second=new zi("second",0,59,this.millisecond);minute=new zi("minute",0,59,this.second);hour=new zi("hour",0,23,this.minute);day=new zi("day",1,31,this.hour);month=new zi("month",1,12,this.day);year=new zi("year",0,9999,this.month)}const vt=new o3;class c3 extends a3{constructor(e=1,t=12){super("month",e,t)}}class qd extends zi{static Month28=new qd(28);static Month29=new qd(29);static ThirtyDays=new qd(30);static ThirtyOneDays=new qd(31);constructor(e,t=new c3(1,e)){super("month",1,e,vt.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 Wr("Unsupported month",e,t)}}}class Fo{static instance=new Fo;render(e){return e.value.toString()}}class er{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 Av(`${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=Fo.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class ze{static#e=new Map;static register(e,t){ze.#e.set(e,t)}static get(e){const t=ze.#e.get(e);if(!t)throw new Wr(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Ou extends er{constructor(e=new Date().getFullYear(),t=vt.year){super(e,t)}static fromString(e,t=ze.get(Ou)){return new Ou(t.parse(e))}}class jo extends Fo{static default=new jo("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Lu extends er{constructor(e=new Date().getMonth()+1,t=vt.month){super(e,t)}static fromString(e,t=ze.get(Lu)){return new Lu(t.parse(e))}toString(e=jo.default){return super.toString(e)}}class Pu extends er{constructor(e=new Date().getDate(),t=vt.day){super(e,t)}static fromString(e,t=ze.get(Pu)){const i=t.parse(e);return new Pu(i)}toString(e=jo.default){return super.toString(e)}}class Nu extends er{constructor(e=new Date().getHours(),t=vt.hour){super(e,t)}static fromString(e,t=ze.get(Nu)){return new Nu(t.parse(e))}toString(e=jo.default){return super.toString(e)}}class Fu extends er{constructor(e=new Date().getMinutes(),t=vt.minute){super(e,t)}static fromString(e,t=ze.get(Fu)){return new Fu(t.parse(e))}toString(e=jo.default){return super.toString(e)}}class Uu extends er{constructor(e=new Date().getSeconds(),t=vt.second){super(e,t)}static fromString(e,t=ze.get(Uu)){return new Uu(t.parse(e),vt.second)}toString(e=jo.default){return super.toString(e)}}class Kl extends er{static renderer=new jo("0",3);constructor(e,t=vt.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=Kl.renderer){return super.toString(e)}}class Q5{render(e){return e.toString()}}class ek extends Q5{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 Ul{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=ze.get(Ul),i=void 0){const s=t.parse(e,i);return new Ul(s)}toString(e=new ek){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Kn{static timeshift(e,t){return e+(Kn.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=Kn.rule(t);if(!r)return!1;const a=Kn.rank(i,s,n);return a>=Kn.rank(r.start.month,r.start.day,2)&&a<Kn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:Kn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:Kn.sunday(e,3,2)},end:{month:11,day:Kn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:Kn.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:Kn.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,Kn.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 tk={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},ik={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},sk={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},nk={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},rk={name:"PT",timeshift:l=>Kn.timeshift(-480,l),title:"Pacific Time (US)"},ak={name:"MT",timeshift:l=>Kn.timeshift(-420,l),title:"Mountain Time (US)"},ok={name:"CT",timeshift:l=>Kn.timeshift(-360,l),title:"Central Time (US)"},ck={name:"ET",timeshift:l=>Kn.timeshift(-300,l),title:"Eastern Time (US)"},lk={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},hk={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},dk={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},uk={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},pk={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},fk={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},mk={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},gk={name:"Z",timeshift:"Z",title:"UTC"},vk={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},bk={name:"BST",timeshift:"+01",title:"British Summer Time"},yk={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},wk={name:"CET",timeshift:"+01",title:"Central European Time"},Mk={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},xk={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},Ek={name:"BJT",timeshift:"+08",title:"Beijing Time"},Sk={name:"CST",timeshift:"-06",title:"Central Standard Time"},Ak={name:"JST",timeshift:"+09",title:"Japan Standard Time"},Tk={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},Ik={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},_k={name:"LST",timeshift:"?",title:"Local Sideral Time"},Gx=[fk,Tk,pk,Ek,bk,Sk,hk,wk,yk,ok,lk,uk,dk,ck,vk,xk,Ak,_k,sk,Mk,nk,ak,Ik,ik,tk,rk,mk,gk];class Tv{static instance=new Tv;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 lh extends Wr{constructor(e="method is abstract"){super(e)}}class iM{units;constructor(e){this.units=e}newYear(e){throw new lh}newMonth(e){throw new lh}newDay(e){throw new lh}newHour(e){throw new lh}newMinute(e){throw new lh}newSecond(e){throw new lh}}class kk extends tM{millisecond=new zi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new zi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new zi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new zi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new zi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new zi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new zi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const um=new kk;class Iv{static instance=new Iv;render(e){const t=Qa.toSpec(e);let i="P";const s=t.years;s&&(i+=s.toString()+"Y");const n=t.months;n&&(i+=n.toString(Fo.instance)+"MM");const r=t.days;r&&(i+=r.toString(Fo.instance)+"D");const a=t.hours;a&&(i+=a.toString(Fo.instance)+"H");const o=t.minutes;o&&(i+=o.toString(Fo.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(Fo.instance)+"S"),i}}class Qa extends er{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*vt.year.duration:0)+(e.months?e.months*vt.month.duration:0)+(e.days?e.days*vt.day.duration:0)+(e.hours?e.hours*vt.hour.duration:0)+(e.minutes?e.minutes*vt.minute.duration:0)+(e.seconds?e.seconds*vt.second.duration:0)},new zi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=Rk){let i=typeof e=="number"?e:e.value;const s=i>0?1:-1;i=Math.abs(i);const n={},r=i/vt.year.duration,a=Math.floor(r);a>0&&(n.years=t.newYear(s*a),i-=a*vt.year.duration);const o=i/vt.month.duration,c=Math.floor(o);c>0&&(n.months=t.newMonth(s*c),i-=c*vt.month.duration);const h=i/vt.day.duration,d=Math.floor(h);d>0&&(n.days=t.newDay(s*d),i-=d*vt.day.duration);const u=i/vt.hour.duration,p=Math.floor(u);p>0&&(n.hours=t.newHour(s*p),i-=p*vt.hour.duration);const f=i/vt.minute.duration,m=Math.floor(f);m>0&&(n.minutes=t.newMinute(s*m),i-=m*vt.minute.duration);const g=i/vt.second.duration,v=Math.floor(s*g);return v>0&&(n.seconds=t.newSecond(v)),n}static fromString(e,t=ze.get(Qa)){return new Qa(t.parse(e))}static between(e,t){const i=t.getTime(),s=e.getTime();return new Qa(i-s)}toSpec(){return Qa.toSpec(this)}toString(e=Iv.instance){return e.render(this)}}class l3 extends iM{constructor(e){super(e)}newYear(e){return new Ou(e,this.units.year)}newMonth(e){return new Lu(e,this.units.month)}newDay(e){return new Pu(e,this.units.day)}newHour(e){return new Nu(e,this.units.hour)}newMinute(e){return new Fu(e,this.units.minute)}newSecond(e){return new Uu(e,this.units.second)}newMillisecond(e){return new Kl(e,this.units.millisecond)}newTimeshift(e){return new Ul(typeof e=="number"?e:e.value)}}const Dk=new l3(vt),Rk=new l3(um);class Sn{#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:Sn.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 er?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 er?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 er?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 er?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 er?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 er?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 er)?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 Ul)?this.factory.newTimeshift(e):e}get factory(){return Dk}static fromString(e,t=ze.get(Sn)){const{year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:c,timeshift:h}=t.parse(e);return new Sn({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 Sn({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sn.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Sn.fromString(i)}#c(e){if(this.constructor.name!==e.constructor.name)throw new Av(`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 Qa(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 Sn(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=Tv.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 sM{static instance=new sM;render(e){return(e.start?e.start.toString():"")+"/"+(e.end?e.end.toString():"")}}class bf{constructor(e,t){this.start=e,this.end=t}_start;get start(){return this._start}set start(e){if(typeof e=="string"&&(e=Sn.fromString(e)),e&&!(e instanceof Sn)&&!(e instanceof Qa))throw new Wr("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=Sn.fromString(e)),e&&!(e instanceof Sn)&&!(e instanceof Qa))throw new Wr("Interval end is not a level 0 date or duration: "+e);this._end=e}static fromString(e,t=ze.get(bf)){const{start:i,end:s}=t.parse(e);return new bf(i,s)}toString(e=sM.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 pm extends Fo{static instance=new pm(jo.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 Xo extends er{#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=pm.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class h3 extends o3{year=new zi("year",-9999,9999,this.month);yearExtended=new zi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const ig=new h3;class Ml extends Xo{constructor(e,t=ig.year){super(e,t)}static fromString(e,t=ig.year,i=ze.get(Ml)){const s=i.parse(e),n=s.value.start;if(e.startsWith("Y")&&(t=ig.yearExtended),n!==void 0){const r=new Ml(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Ml(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new Ml(s,t)}}class d3 extends Av{monthValidator=new c3;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class xl extends Xo{constructor(e,t=new zi(vt.month.name,1,24,vt.day,new d3)){super(e,t)}static fromString(e,t=ze.get(xl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=vt.month;const r=new xl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new xl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new xl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class El extends Xo{constructor(e,t=vt.day){super(e,t)}static fromString(e,t=ze.get(El)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=vt.day;const r=new El(Object.assign({...i},{value:Math.max(s,n.min)})),a=new El(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new El(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Sl extends Xo{constructor(e,t=vt.hour){super(e,t)}static fromString(e,t=ze.get(Sl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=vt.hour;const r=new Sl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Sl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Sl(i)}}class Al extends Xo{constructor(e,t=vt.minute){super(e,t)}static fromString(e,t=ze.get(Al)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.minute,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)}toString(e=pm.instance){return super.toString(e)}}class Tl extends Xo{constructor(e,t=vt.second){super(e,t)}static fromString(e,t=ze.get(Tl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.second,r=new Tl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Tl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Tl(i)}}class Kh extends Ul{static fromString(e,t=ze.get(Kh),i=void 0){return new Kh(t.parse(e,i))}}class u3 extends iM{constructor(e){super(e)}newYear(e){return new Ml(e,this.units.year)}newMonth(e){return new xl(e,this.units.month)}newDay(e){return new El(e,this.units.day)}newHour(e){return new Sl(e,this.units.hour)}newMinute(e){return new Al(e,this.units.minute)}newSecond(e){return new Tl(e,this.units.second)}newMillisecond(e){return new Kl(e,this.units.millisecond)}newTimeshift(e){return new Kh(typeof e=="number"?e:e.value)}}const Ck=new u3(ig),Ok=new u3(um);class zr extends Sn{constructor(e){super(e)}get factory(){return Ck}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 zr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sn.timeshiftOf(e)})}static fromString(e,t=ze.get(zr)){const i=t.parse(e);return new zr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return zr.fromString(i)}clone(){return new zr(this.toSpec())}}const rn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class _v extends Iv{static instance=new _v;render(e){return super.render(e)}}class Qs extends Xo{constructor(e){super(typeof e=="number"||e.hasOwnProperty("value")?e:{value:Qs.getValue(e,rn.year)+Qs.getValue(e,rn.month)+Qs.getValue(e,rn.day)+Qs.getValue(e,rn.hour)+Qs.getValue(e,rn.minute)+Qs.getValue(e,rn.second),uncertain:Qs.getBoolean(e,rn.uncertain),approximate:Qs.getBoolean(e,"approximate")},um.millisecond)}static getBoolean(e,t){return e[t]||e[rn.year+"s"]?.[t]||e[rn.month+"s"]?.[t]||e[rn.day+"s"]?.[t]||e[rn.hour+"s"]?.[t]||e[rn.minute+"s"]?.[t]||e[rn.second+"s"]?.[t]||!1}static getValue(e,t){let i=0,s=e[t+"s"];if(s instanceof Xo?s=s.value:typeof e=="number"&&(s=e),s){const n=vt[t];i=s*n.duration}return i}static toSpec(e,t=Ok){return{...Qa.toSpec(e,t),uncertain:e.uncertain||!1,approximate:e.approximate||!1}}static fromString(e,t=ze.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)}toString(e=_v.instance){return super.toString(e)}toSpec(){return Qs.toSpec(this)}}class yf extends bf{constructor(e,t){super(e,t)}get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=zr.fromString(e)),e&&!(e instanceof zr)&&!(e instanceof Qs))throw new Wr("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=zr.fromString(e)),e&&!(e instanceof zr)&&!(e instanceof Qs))throw new Wr("Interval end is not a level 1 date or duration: "+e);this._end=e}static fromString(e,t=ze.get(yf)){const{start:i,end:s}=t.parse(e);return new yf(i,s)}}class Zu extends Xo{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 Lk extends h3{year=new zi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const r1=new Lk;class Mc extends Zu{constructor(e,t=r1.year){super(e,t)}static fromString(e,t=r1.year,i=ze.get(Mc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new Mc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Mc(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 Mc(s)}}class Pk extends d3{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 xc extends Zu{constructor(e,t=new zi(vt.month.name,1,41,vt.day,new Pk)){super(e,t)}static fromString(e,t=ze.get(xc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.month,r=new xc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new xc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new xc(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Ec extends Zu{constructor(e,t=vt.day){super(e,t)}static fromString(e,t=ze.get(Ec)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.day,r=new Ec(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Ec(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Ec(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Sc extends Zu{constructor(e,t=vt.hour){super(e,t)}static fromString(e,t=ze.get(Sc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.hour,r=new Sc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Sc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Sc(i)}}class Ac extends Zu{constructor(e,t=vt.minute){super(e,t)}static fromString(e,t=ze.get(Ac)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.minute,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)}}class Tc extends Zu{constructor(e,t=vt.second){super(e,t)}static fromString(e,t=vt.second,i=ze.get(Tc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new Tc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Tc(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new Tc(s,t)}}class p3 extends Kh{}class Nk extends pm{qualifier(){return""}}class sl extends Tv{static instance=new sl;static valueRenderer=new Nk(jo.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=sl.names.slice(sl.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),n=sl.qualifier(i.uncertainComponent,i.approximateComponent),r=sl.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!s.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!s.some(a=>a.approximate));return n+i.toString(sl.valueRenderer)+r}}class f3 extends iM{constructor(e){super(e)}newYear(e){return new Mc(e,this.units.year)}newMonth(e){return new xc(e,this.units.month)}newDay(e){return new Ec(e,this.units.day)}newHour(e){return new Sc(e,this.units.hour)}newMinute(e){return new Ac(e,this.units.minute)}newSecond(e){return new Tc(e,this.units.second)}newMillisecond(e){return new Kl(e,this.units.millisecond)}newTimeshift(e){return new p3(typeof e=="number"?e:e.value)}}const Fk=new f3(r1),Uk=new f3(um);class wr extends zr{constructor(e){super(e)}toString(e=sl.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 Fk}static fromDate(e){return new wr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sn.timeshiftOf(e)})}static fromString(e,t=ze.get(wr)){const i=t.parse(e);return new wr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return wr.fromString(i)}clone(){return new wr(this.toSpec())}}class Bc{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new Wr(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new lh(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class jd extends _v{static instance=new jd;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=jd.qualifier(e.uncertainDuration,e.approximateDuration);if(!e.hasQualifiedComponent)return t+super.render(e);let i=t+"P";for(const[s,n]of jd.designators){const r=e.components[s];r&&(i+=jd.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+n)}return i}}class js extends Qs{#e;constructor(e){if(super(typeof e=="number"?e:{value:js.valueFromSpec(e),uncertain:e.uncertain===!0,approximate:e.approximate===!0},um.millisecond),typeof e!="number"){const t={};for(const i of js.componentNames)e[i]instanceof Xo&&(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 js.getValue(e,rn.year)+js.getValue(e,rn.month)+js.getValue(e,rn.day)+js.getValue(e,rn.hour)+js.getValue(e,rn.minute)+js.getValue(e,rn.second)}static toSpec(e,t=Uk){const i=Qs.toSpec(e,t);if(e instanceof js&&e.hasQualifiedComponent)for(const s of js.componentNames)delete i[s],e.components[s]&&(i[s]=e.components[s]);return i}static fromString(e,t=ze.get(js)){const i=t.parse(e);return new js(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new js(i-s)}toSpec(){return js.toSpec(this)}toString(e=jd.instance){return super.toString(e)}}class wf extends yf{get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=wr.fromString(e)),e&&!(e instanceof wr)&&!(e instanceof js))throw new Wr("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=wr.fromString(e)),e&&!(e instanceof wr)&&!(e instanceof js))throw new Wr("Interval end is not a level 2 date or duration: "+e);this._end=e}static fromString(e,t=ze.get(wf)){const{start:i,end:s}=t.parse(e);return new wf(i,s)}}class Eg 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=ze.get(Eg)){const{exclusive:i,values:s}=t.parse(e);return new Eg(s,i)}}class zc extends Bc{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return zc.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new Wr(`${this.name} cannot be negative`);return super.parse(e)}}class B{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 B.optional(B.group(e,...t))}static optionalNonCapturingGroup(...e){return B.optional(B.nonCapturingGroup(...e))}static numberGroup(e,t,i,s="\\d"){return B.group(e,`${i||""}[${s}]${t}`)}}const Vx="yearValue";class Mf extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Vx),"{4}",void 0)}constructor(){super(Vx,Mf.format())}}const Wx="monthValue";class xf extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Wx),"{1,2}",void 0)}constructor(){super(Wx,xf.format())}}const $x="dayValue";class bu extends zc{static format(e=""){return B.numberGroup(B.groupName(e,$x),"{1,2}",void 0)}constructor(){super($x,bu.format())}}const Kx="hourValue";class yu extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Kx),"{1,2}",void 0)}constructor(){super(Kx,yu.format())}}const Xx="minuteValue";class Ef extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Xx),"{1,2}",void 0)}constructor(){super(Xx,Ef.format())}}const Yx="secondValue";class Sf extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Yx),"{1,2}",void 0)}constructor(){super(Yx,Sf.format())}}const qx="timeshiftValue",jx="shiftHour",Zx="shiftMinute";class Bu extends Bc{static format(e=""){return Gx.map(t=>t.name).join("|")+"|"+B.nonCapturingGroup(B.group(e+jx,B.numberGroup(B.groupName(e,qx),"{2}","[+-]")),B.optionalNonCapturingGroup(":?",B.numberGroup(B.groupName(e,Zx),"{2}",void 0)))}constructor(){super(qx,Bu.format())}parse(e,t){let i=0;const s=Gx.find(n=>n.name===e);if(s){if(typeof s.timeshift=="function")try{return s.timeshift(t??{})}catch(n){throw new Wr(`The time zone ${e} depends on the date: ${n.message}`)}e=s.timeshift}if(e!=="Z"){const n=this.regexGroups(e),r=n[jx];r&&(i+=parseInt(r,10)*60);const a=n[Zx];a&&(i+=parseInt(a,10))}return i}}const Jx="year",Qx="month",eE="day",tE="hour",iE="minute",sE="second",nE="millisecond",rE="timeshift";class yh extends Bc{static format(e=""){return B.group(B.groupName(e,Jx),Mf.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,Qx),xf.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,eE),bu.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,tE),yu.format(e)),":?",B.group(B.groupName(e,iE),Ef.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,sE),Sf.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,nE),"\\d+"))),"\\s*",B.optionalGroup(B.groupName(e,rE),Bu.format(e)))))}constructor(){super("date",yh.format())}parse(e){const t=this.regexGroups(e),i=t[Jx],s=t[Qx],n=t[eE],r=t[tE],a=t[iE],o=t[sE],c=t[nE],h=t[rE],d=i?new Ou(Mf.read(i)):void 0,u=s?xf.read(s):void 0;return{year:d,month:u?new Lu(u,qd.create(u.value,d?.value)):void 0,day:n?new Pu(bu.read(n)):void 0,hour:r?new Nu(yu.read(r)):void 0,minute:a?new Fu(Ef.read(a)):void 0,second:o?new Uu(Sf.read(o)):void 0,millisecond:c?Kl.parseFraction(c):void 0,timeshift:h?Ul.fromString(h,new Bu,{year:d?.value,month:u?.value,day:n?bu.read(n).value:void 0,hour:r?yu.read(r).value:void 0}):void 0}}}const aE="years",ib="months",Bk="days",oE="hours",cE="minutes",lE="seconds";class nM extends Bc{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,aE),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,ib),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Bk),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,oE),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,cE),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,lE),"+",void 0,"\\d"),"S")}constructor(){super("duration",nM.format())}parseGroups(e){return{years:e[aE],months:e[ib],days:e[ib],hours:e[oE],minutes:e[cE],seconds:e[lE]}}}const sb="start",nb="end";class rM extends Bc{static format=B.group(sb,yh.format(sb))+"/"+B.group(nb,yh.format(nb));constructor(){super("interval",rM.format)}parse(e){const t=this.regexGroups(e),i=t[sb],s=t[nb];return{start:i?Sn.fromString(i,new yh):void 0,end:s?Sn.fromString(s,new yh):void 0}}}ze.register(Sn,()=>new yh);ze.register(Pu,()=>new bu);ze.register(Qa,()=>new nM);ze.register(Nu,()=>new yu);ze.register(bf,()=>new rM);ze.register(Fu,()=>new Ef);ze.register(Lu,()=>new xf);ze.register(Uu,()=>new Sf);ze.register(Ul,()=>new Bu);ze.register(Ou,()=>new Mf);class Qi extends zc{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Qi.uncertainGroup+Qi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return B.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(B.groupName(Qi.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(Qi.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(Qi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return B.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[B.groupName(Qi.uncertainAndApproximateGroup,this.name)],a=e[B.groupName(Qi.approximateGroup,this.name)]||r,o=e[B.groupName(Qi.uncertainGroup,this.name)]||r;return{value:s,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const hE="yearValue";class Af extends Qi{constructor(){super(hE,Af.format())}static format(e=""){return"Y?"+Qi.numberFormat(B.groupName(e,hE),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const dE="monthValue";class Tf extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,dE),"{1,2}",void 0)}constructor(){super(dE,Tf.format())}}const uE="dayValue";class If extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,uE),"{1,2}",void 0)}constructor(){super(uE,If.format())}}const pE="hourValue";class _f extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,pE),"{1,2}",void 0)}constructor(){super(pE,_f.format())}}const fE="minuteValue";class kf extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,fE),"{1,2}",void 0)}constructor(){super(fE,kf.format())}}const mE="secondValue";class Df extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,mE),"{1,2}",void 0)}constructor(){super(mE,Df.format())}}class Rf extends Bu{}class hs extends Bc{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=hs.format()){super("date",e)}static format(e=""){return B.group(B.groupName(e,hs.yearGroup),Af.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.monthGroup),Tf.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.dayGroup),If.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,hs.hourGroup),_f.format(e)),":",B.group(B.groupName(e,hs.minuteGroup),kf.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,hs.secondGroup),Df.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,hs.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,hs.timeshiftGroup),Rf.format(e)))))}parseGroups(e){const t=e[hs.millisecondGroup],i=t?Kl.parseFraction(t):void 0,s=e[hs.secondGroup],n=s?Tl.fromString(s,new Df):void 0,r=e[hs.minuteGroup];let a;r&&(a=Al.fromString(r,new kf),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[hs.hourGroup];let c;o&&(c=Sl.fromString(o,new _f),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[hs.dayGroup];let d;h&&(d=El.fromString(h,new If),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[hs.monthGroup];let p;u&&(p=xl.fromString(u,new Tf),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[hs.yearGroup];let m;f&&(m=Ml.fromString(f,void 0,new Af),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[hs.timeshiftGroup],v=g?Kh.fromString(g,new Rf,{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 gE="years",vE="months",bE="days",yE="hours",wE="minutes",ME="seconds";class wh extends Qi{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,gE),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,vE),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,bE),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,yE),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,wE),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,ME),"+",void 0,"\\d"),"S")+this.formatSuffix(e)}constructor(){super("duration",wh.format())}parseGroups(e){return{years:e[gE],months:e[vE],days:e[bE],hours:e[yE],minutes:e[wE],seconds:e[ME],uncertain:!!e[Qi.uncertainGroup],approximate:!!e[Qi.approximateGroup]}}}const zk="dates",rb="start",ab="end",xE="durations",ob="durationMin",cb="durationMax";class aM extends Bc{static format=B.group(zk,B.optionalGroup(rb,B.group("openStart","\\.\\.")+"|"+hs.format(rb))+"/"+B.optionalGroup(ab,B.group("openEnd","\\.\\.")+"|"+hs.format(ab)))+"|"+B.group(xE,B.group(ob,wh.format(ob))+"/"+B.group(cb,wh.format(cb)));constructor(e="interval",t=aM.format){super(e,t)}parseGroups(e){let t,i;if(e[xE]){const n=e[ob];t=Qs.fromString(n,new wh);const r=e[cb];i=Qs.fromString(r,new wh)}else{const n=e[rb];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=zr.fromString(n,new hs)}const r=e[ab];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=zr.fromString(r,new hs)}}return{start:t,end:i}}}ze.register(zr,()=>new hs);ze.register(El,()=>new If);ze.register(Qs,()=>new wh);ze.register(Sl,()=>new _f);ze.register(yf,()=>new aM);ze.register(Al,()=>new kf);ze.register(xl,()=>new Tf);ze.register(Tl,()=>new Df);ze.register(Kh,()=>new Rf);ze.register(Ml,()=>new Af);class hi extends Qi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=hi.uncertainGroup+hi.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(B.groupName(hi.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(hi.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(hi.uncertainAndApproximateGroup,e),"%")+Qi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[B.groupName(hi.uncertainAndApproximateGroup,this.name)];return(e[B.groupName(hi.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[B.groupName(hi.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const sp="yearValue",EE="exp",SE="signif";class Cf extends hi{constructor(){super(sp,Cf.format())}static format(e=""){return"Y?"+B.nonCapturingGroup(B.group(B.groupName(e,EE),"[-]?\\d+E\\d+")+"|"+hi.numberFormat(B.groupName(e,sp),"+","[-]?")+B.optionalGroup(B.groupName(e,SE),"S\\d+"))}parseGroups(e){const t=e[EE];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[sp]=c.toString()}const i=e[SE],s=e[sp];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[sp]=(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 AE="monthValue";class Of extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,AE),"{1,2}",void 0)}constructor(){super(AE,Of.format())}}const TE="dayValue";class Lf extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,TE),"{1,2}",void 0)}constructor(){super(TE,Lf.format())}}const IE="hourValue";class Pf extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,IE),"{1,2}",void 0)}constructor(){super(IE,Pf.format())}}const _E="secondValue";class Nf extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,_E),"{1,2}",void 0)}constructor(){super(_E,Nf.format())}}const kE="minuteValue";class Ff extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,kE),"{1,2}",void 0)}constructor(){super(kE,Ff.format())}}class Hk extends Rf{}class mi extends Bc{static yearGroup=hs.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",mi.format())}static format(e=""){return B.group(B.groupName(e,mi.yearGroup),Cf.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,mi.monthGroup),Of.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,mi.dayGroup),Lf.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,mi.hourGroup),Pf.format(e)),":",B.group(B.groupName(e,mi.minuteGroup),Ff.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,mi.secondGroup),Nf.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,mi.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,mi.timeshiftGroup),Hk.format(e)))))}parseGroups(e){const t=e[mi.millisecondGroup],i=t?Kl.parseFraction(t):void 0,s=e[mi.secondGroup];let n;s&&(n=Tc.fromString(s,void 0,new Nf),n.uncertain=n?.uncertain||!1,n.approximate=n?.approximate||!1);const r=e[mi.minuteGroup];let a;r&&(a=Ac.fromString(r,new Ff),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[mi.hourGroup];let c;o&&(c=Sc.fromString(o,new Pf),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[mi.dayGroup];let d;h&&(d=Ec.fromString(h,new Lf),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[mi.monthGroup];let p;u&&(p=xc.fromString(u,new Of),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[mi.yearGroup];let m;f&&(m=Mc.fromString(f,void 0,new Cf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[mi.timeshiftGroup],v=g?p3.fromString(g,new Rf,{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 DE="durationValue";class oM extends hi{static format(e=""){return"^"+hi.numberFormat(B.groupName(e,DE),"+",void 0)}constructor(){super(DE,oM.format())}}class Gk extends tM{millisecond=new zi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new zi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new zi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new zi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new zi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new zi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new zi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const rd=new Gk;class ht extends hi{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 oM;static componentFormat(e,t,i,s,n=""){const r=B.group(B.groupName(e,ht.quantityGroup(t)),hi.numberFormat(B.groupName(e,i),"+",void 0,"\\d"));return B.group(B.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=B.groupName(e,ht.durationGroup);return this.qualifierFormat(B.groupName(hi.uncertainGroup,t),"?")+this.qualifierFormat(B.groupName(hi.approximateGroup,t),"~")+this.qualifierFormat(B.groupName(hi.uncertainAndApproximateGroup,t),"%")+"P"+B.optional(ht.componentFormat(e,ht.yearsGroup,mi.yearGroup,"Y"))+B.optionalNonCapturingGroup(ht.componentFormat(e,ht.monthsGroup,mi.monthGroup,"MM")+"|"+ht.componentFormat(e,ht.isoMonthsGroup,"isoMonth","M",ht.isoMonthsLookahead))+B.optional(ht.componentFormat(e,ht.daysGroup,mi.dayGroup,"D"))+"T?"+B.optional(ht.componentFormat(e,ht.hoursGroup,mi.hourGroup,"H"))+B.optional(ht.componentFormat(e,ht.minutesGroup,mi.minuteGroup,"M"))+B.optional(ht.componentFormat(e,ht.secondsGroup,mi.secondGroup,"S"))+B.optionalGroup(B.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,Tc,rd.second),i.uncertain=!!e[B.groupName(hi.uncertainGroup,ht.secondsGroup)]||!1,i.approximate=!!e[B.groupName(hi.approximateGroup,ht.secondsGroup)]||!1);const s=e[ht.quantityGroup(ht.minutesGroup)];let n;s&&(n=ht.parseComponent(s,Ac,rd.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,Sc,rd.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,Ec,rd.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,xc,rd.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,Mc,rd.year),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ht.suffixGroup],m=!!e[B.groupName(hi.uncertainAndApproximateGroup,ht.durationGroup)]||f==="%",g=m||!!e[B.groupName(hi.uncertainGroup,ht.durationGroup)]||f==="?",v=m||!!e[B.groupName(hi.approximateGroup,ht.durationGroup)]||f==="~";return{years:p,months:d,days:c,hours:a,minutes:n,seconds:i,uncertain:g,approximate:v}}}const Vk="dates",lb="start",hb="end",RE="durations",db="durationMin",ub="durationMax";class kv extends Bc{static format=B.group(Vk,B.optionalGroup(lb,B.group("openStart","\\.\\.")+"|"+mi.format(lb))+"/"+B.optionalGroup(hb,B.group("openEnd","\\.\\.")+"|"+mi.format(hb)))+"|"+B.group(RE,B.group(db,ht.format(db))+"/"+B.group(ub,ht.format(ub)));constructor(e="interval",t=kv.format){super(e,t)}parseGroups(e){let t,i;if(e[RE]){const n=e[db];t=js.fromString(n,new ht);const r=e[ub];i=js.fromString(r,new ht)}else{const n=e[lb];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=wr.fromString(n,new mi)}const r=e[hb];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=wr.fromString(r,new mi)}}return{start:t,end:i}}}class Wk{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=wf.fromString(r.replace("..","/"),new kv):a=wr.fromString(r,new mi),n.push(a)}return{values:n,exclusive:t}}}ze.register(wr,()=>new mi);ze.register(Ec,()=>new Lf);ze.register(js,()=>new ht);ze.register(Sc,()=>new Pf);ze.register(wf,()=>new kv);ze.register(Ac,()=>new Ff);ze.register(xc,()=>new Of);ze.register(Tc,()=>new Nf);ze.register(Eg,()=>new Wk);ze.register(Mc,()=>new Cf);class ws{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[ws.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>ws.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(ws.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=>ws.base(c)===ws.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]}}ws.any=new ws([]);var CE;(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"})(CE||(CE={}));var OE;(function(l){l.neutral="neutral",l.male="male",l.female="female"})(OE||(OE={}));class $k extends Error{constructor(e,t){super(e),this.cause=t}}class cM extends $k{constructor(e=cM.defaultMessage,t){super(e,t)}}cM.defaultMessage="Assertion failed";var LE;(function(l){l.country="country",l.region="region",l.department="department",l.city="city",l.company="company"})(LE||(LE={}));var PE;(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"})(PE||(PE={}));class Kk{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"}}/**
|
|
470
|
+
`;class vu extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(vu.TAG)||customElements.define(vu.TAG,vu)}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=Z5;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 F5.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?_o.pinnedLink(e.link(),"0.204.2"):e.link(),this.fitLink();const s=`<script type="module" src="${t?_o.pinned(e.module,"0.204.2"):_o.current(e.module,import.meta.url,$h.home())}"><\/script>
|
|
471
|
+
${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.204.2")),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??=F(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([24,25]),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 Wr extends Error{}class Av{constructor(e){this.name=e}validate(e){return!0}}class a3 extends Av{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new Wr(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new Wr(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class zi{name;min;max;duration;subUnit;validator;constructor(e,t,i,s,n=new a3(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 tM{millisecond;second;minute;hour;day;month;year}class J5 extends tM{}class o3 extends J5{millisecond=new zi("millisecond",0,999,void 0);second=new zi("second",0,59,this.millisecond);minute=new zi("minute",0,59,this.second);hour=new zi("hour",0,23,this.minute);day=new zi("day",1,31,this.hour);month=new zi("month",1,12,this.day);year=new zi("year",0,9999,this.month)}const vt=new o3;class c3 extends a3{constructor(e=1,t=12){super("month",e,t)}}class qd extends zi{static Month28=new qd(28);static Month29=new qd(29);static ThirtyDays=new qd(30);static ThirtyOneDays=new qd(31);constructor(e,t=new c3(1,e)){super("month",1,e,vt.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 Wr("Unsupported month",e,t)}}}class Fo{static instance=new Fo;render(e){return e.value.toString()}}class er{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 Av(`${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=Fo.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class ze{static#e=new Map;static register(e,t){ze.#e.set(e,t)}static get(e){const t=ze.#e.get(e);if(!t)throw new Wr(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Ou extends er{constructor(e=new Date().getFullYear(),t=vt.year){super(e,t)}static fromString(e,t=ze.get(Ou)){return new Ou(t.parse(e))}}class jo extends Fo{static default=new jo("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Lu extends er{constructor(e=new Date().getMonth()+1,t=vt.month){super(e,t)}static fromString(e,t=ze.get(Lu)){return new Lu(t.parse(e))}toString(e=jo.default){return super.toString(e)}}class Pu extends er{constructor(e=new Date().getDate(),t=vt.day){super(e,t)}static fromString(e,t=ze.get(Pu)){const i=t.parse(e);return new Pu(i)}toString(e=jo.default){return super.toString(e)}}class Nu extends er{constructor(e=new Date().getHours(),t=vt.hour){super(e,t)}static fromString(e,t=ze.get(Nu)){return new Nu(t.parse(e))}toString(e=jo.default){return super.toString(e)}}class Fu extends er{constructor(e=new Date().getMinutes(),t=vt.minute){super(e,t)}static fromString(e,t=ze.get(Fu)){return new Fu(t.parse(e))}toString(e=jo.default){return super.toString(e)}}class Uu extends er{constructor(e=new Date().getSeconds(),t=vt.second){super(e,t)}static fromString(e,t=ze.get(Uu)){return new Uu(t.parse(e),vt.second)}toString(e=jo.default){return super.toString(e)}}class Kl extends er{static renderer=new jo("0",3);constructor(e,t=vt.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=Kl.renderer){return super.toString(e)}}class Q5{render(e){return e.toString()}}class ek extends Q5{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 Ul{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=ze.get(Ul),i=void 0){const s=t.parse(e,i);return new Ul(s)}toString(e=new ek){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Kn{static timeshift(e,t){return e+(Kn.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=Kn.rule(t);if(!r)return!1;const a=Kn.rank(i,s,n);return a>=Kn.rank(r.start.month,r.start.day,2)&&a<Kn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:Kn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:Kn.sunday(e,3,2)},end:{month:11,day:Kn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:Kn.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:Kn.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,Kn.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 tk={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},ik={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},sk={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},nk={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},rk={name:"PT",timeshift:l=>Kn.timeshift(-480,l),title:"Pacific Time (US)"},ak={name:"MT",timeshift:l=>Kn.timeshift(-420,l),title:"Mountain Time (US)"},ok={name:"CT",timeshift:l=>Kn.timeshift(-360,l),title:"Central Time (US)"},ck={name:"ET",timeshift:l=>Kn.timeshift(-300,l),title:"Eastern Time (US)"},lk={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},hk={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},dk={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},uk={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},pk={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},fk={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},mk={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},gk={name:"Z",timeshift:"Z",title:"UTC"},vk={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},bk={name:"BST",timeshift:"+01",title:"British Summer Time"},yk={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},wk={name:"CET",timeshift:"+01",title:"Central European Time"},Mk={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},xk={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},Ek={name:"BJT",timeshift:"+08",title:"Beijing Time"},Sk={name:"CST",timeshift:"-06",title:"Central Standard Time"},Ak={name:"JST",timeshift:"+09",title:"Japan Standard Time"},Tk={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},Ik={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},_k={name:"LST",timeshift:"?",title:"Local Sideral Time"},Gx=[fk,Tk,pk,Ek,bk,Sk,hk,wk,yk,ok,lk,uk,dk,ck,vk,xk,Ak,_k,sk,Mk,nk,ak,Ik,ik,tk,rk,mk,gk];class Tv{static instance=new Tv;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 lh extends Wr{constructor(e="method is abstract"){super(e)}}class iM{units;constructor(e){this.units=e}newYear(e){throw new lh}newMonth(e){throw new lh}newDay(e){throw new lh}newHour(e){throw new lh}newMinute(e){throw new lh}newSecond(e){throw new lh}}class kk extends tM{millisecond=new zi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new zi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new zi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new zi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new zi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new zi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new zi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const um=new kk;class Iv{static instance=new Iv;render(e){const t=Qa.toSpec(e);let i="P";const s=t.years;s&&(i+=s.toString()+"Y");const n=t.months;n&&(i+=n.toString(Fo.instance)+"MM");const r=t.days;r&&(i+=r.toString(Fo.instance)+"D");const a=t.hours;a&&(i+=a.toString(Fo.instance)+"H");const o=t.minutes;o&&(i+=o.toString(Fo.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(Fo.instance)+"S"),i}}class Qa extends er{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*vt.year.duration:0)+(e.months?e.months*vt.month.duration:0)+(e.days?e.days*vt.day.duration:0)+(e.hours?e.hours*vt.hour.duration:0)+(e.minutes?e.minutes*vt.minute.duration:0)+(e.seconds?e.seconds*vt.second.duration:0)},new zi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=Rk){let i=typeof e=="number"?e:e.value;const s=i>0?1:-1;i=Math.abs(i);const n={},r=i/vt.year.duration,a=Math.floor(r);a>0&&(n.years=t.newYear(s*a),i-=a*vt.year.duration);const o=i/vt.month.duration,c=Math.floor(o);c>0&&(n.months=t.newMonth(s*c),i-=c*vt.month.duration);const h=i/vt.day.duration,d=Math.floor(h);d>0&&(n.days=t.newDay(s*d),i-=d*vt.day.duration);const u=i/vt.hour.duration,p=Math.floor(u);p>0&&(n.hours=t.newHour(s*p),i-=p*vt.hour.duration);const f=i/vt.minute.duration,m=Math.floor(f);m>0&&(n.minutes=t.newMinute(s*m),i-=m*vt.minute.duration);const g=i/vt.second.duration,v=Math.floor(s*g);return v>0&&(n.seconds=t.newSecond(v)),n}static fromString(e,t=ze.get(Qa)){return new Qa(t.parse(e))}static between(e,t){const i=t.getTime(),s=e.getTime();return new Qa(i-s)}toSpec(){return Qa.toSpec(this)}toString(e=Iv.instance){return e.render(this)}}class l3 extends iM{constructor(e){super(e)}newYear(e){return new Ou(e,this.units.year)}newMonth(e){return new Lu(e,this.units.month)}newDay(e){return new Pu(e,this.units.day)}newHour(e){return new Nu(e,this.units.hour)}newMinute(e){return new Fu(e,this.units.minute)}newSecond(e){return new Uu(e,this.units.second)}newMillisecond(e){return new Kl(e,this.units.millisecond)}newTimeshift(e){return new Ul(typeof e=="number"?e:e.value)}}const Dk=new l3(vt),Rk=new l3(um);class Sn{#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:Sn.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 er?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 er?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 er?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 er?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 er?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 er?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 er)?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 Ul)?this.factory.newTimeshift(e):e}get factory(){return Dk}static fromString(e,t=ze.get(Sn)){const{year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:c,timeshift:h}=t.parse(e);return new Sn({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 Sn({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sn.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Sn.fromString(i)}#c(e){if(this.constructor.name!==e.constructor.name)throw new Av(`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 Qa(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 Sn(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=Tv.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 sM{static instance=new sM;render(e){return(e.start?e.start.toString():"")+"/"+(e.end?e.end.toString():"")}}class bf{constructor(e,t){this.start=e,this.end=t}_start;get start(){return this._start}set start(e){if(typeof e=="string"&&(e=Sn.fromString(e)),e&&!(e instanceof Sn)&&!(e instanceof Qa))throw new Wr("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=Sn.fromString(e)),e&&!(e instanceof Sn)&&!(e instanceof Qa))throw new Wr("Interval end is not a level 0 date or duration: "+e);this._end=e}static fromString(e,t=ze.get(bf)){const{start:i,end:s}=t.parse(e);return new bf(i,s)}toString(e=sM.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 pm extends Fo{static instance=new pm(jo.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 Xo extends er{#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=pm.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class h3 extends o3{year=new zi("year",-9999,9999,this.month);yearExtended=new zi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const ig=new h3;class Ml extends Xo{constructor(e,t=ig.year){super(e,t)}static fromString(e,t=ig.year,i=ze.get(Ml)){const s=i.parse(e),n=s.value.start;if(e.startsWith("Y")&&(t=ig.yearExtended),n!==void 0){const r=new Ml(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Ml(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new Ml(s,t)}}class d3 extends Av{monthValidator=new c3;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class xl extends Xo{constructor(e,t=new zi(vt.month.name,1,24,vt.day,new d3)){super(e,t)}static fromString(e,t=ze.get(xl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=vt.month;const r=new xl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new xl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new xl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class El extends Xo{constructor(e,t=vt.day){super(e,t)}static fromString(e,t=ze.get(El)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=vt.day;const r=new El(Object.assign({...i},{value:Math.max(s,n.min)})),a=new El(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new El(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Sl extends Xo{constructor(e,t=vt.hour){super(e,t)}static fromString(e,t=ze.get(Sl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=vt.hour;const r=new Sl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Sl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Sl(i)}}class Al extends Xo{constructor(e,t=vt.minute){super(e,t)}static fromString(e,t=ze.get(Al)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.minute,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)}toString(e=pm.instance){return super.toString(e)}}class Tl extends Xo{constructor(e,t=vt.second){super(e,t)}static fromString(e,t=ze.get(Tl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.second,r=new Tl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Tl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Tl(i)}}class Kh extends Ul{static fromString(e,t=ze.get(Kh),i=void 0){return new Kh(t.parse(e,i))}}class u3 extends iM{constructor(e){super(e)}newYear(e){return new Ml(e,this.units.year)}newMonth(e){return new xl(e,this.units.month)}newDay(e){return new El(e,this.units.day)}newHour(e){return new Sl(e,this.units.hour)}newMinute(e){return new Al(e,this.units.minute)}newSecond(e){return new Tl(e,this.units.second)}newMillisecond(e){return new Kl(e,this.units.millisecond)}newTimeshift(e){return new Kh(typeof e=="number"?e:e.value)}}const Ck=new u3(ig),Ok=new u3(um);class zr extends Sn{constructor(e){super(e)}get factory(){return Ck}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 zr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sn.timeshiftOf(e)})}static fromString(e,t=ze.get(zr)){const i=t.parse(e);return new zr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return zr.fromString(i)}clone(){return new zr(this.toSpec())}}const rn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class _v extends Iv{static instance=new _v;render(e){return super.render(e)}}class Qs extends Xo{constructor(e){super(typeof e=="number"||e.hasOwnProperty("value")?e:{value:Qs.getValue(e,rn.year)+Qs.getValue(e,rn.month)+Qs.getValue(e,rn.day)+Qs.getValue(e,rn.hour)+Qs.getValue(e,rn.minute)+Qs.getValue(e,rn.second),uncertain:Qs.getBoolean(e,rn.uncertain),approximate:Qs.getBoolean(e,"approximate")},um.millisecond)}static getBoolean(e,t){return e[t]||e[rn.year+"s"]?.[t]||e[rn.month+"s"]?.[t]||e[rn.day+"s"]?.[t]||e[rn.hour+"s"]?.[t]||e[rn.minute+"s"]?.[t]||e[rn.second+"s"]?.[t]||!1}static getValue(e,t){let i=0,s=e[t+"s"];if(s instanceof Xo?s=s.value:typeof e=="number"&&(s=e),s){const n=vt[t];i=s*n.duration}return i}static toSpec(e,t=Ok){return{...Qa.toSpec(e,t),uncertain:e.uncertain||!1,approximate:e.approximate||!1}}static fromString(e,t=ze.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)}toString(e=_v.instance){return super.toString(e)}toSpec(){return Qs.toSpec(this)}}class yf extends bf{constructor(e,t){super(e,t)}get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=zr.fromString(e)),e&&!(e instanceof zr)&&!(e instanceof Qs))throw new Wr("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=zr.fromString(e)),e&&!(e instanceof zr)&&!(e instanceof Qs))throw new Wr("Interval end is not a level 1 date or duration: "+e);this._end=e}static fromString(e,t=ze.get(yf)){const{start:i,end:s}=t.parse(e);return new yf(i,s)}}class Zu extends Xo{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 Lk extends h3{year=new zi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const r1=new Lk;class Mc extends Zu{constructor(e,t=r1.year){super(e,t)}static fromString(e,t=r1.year,i=ze.get(Mc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new Mc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Mc(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 Mc(s)}}class Pk extends d3{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 xc extends Zu{constructor(e,t=new zi(vt.month.name,1,41,vt.day,new Pk)){super(e,t)}static fromString(e,t=ze.get(xc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.month,r=new xc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new xc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new xc(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Ec extends Zu{constructor(e,t=vt.day){super(e,t)}static fromString(e,t=ze.get(Ec)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.day,r=new Ec(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Ec(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Ec(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Sc extends Zu{constructor(e,t=vt.hour){super(e,t)}static fromString(e,t=ze.get(Sc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.hour,r=new Sc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Sc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Sc(i)}}class Ac extends Zu{constructor(e,t=vt.minute){super(e,t)}static fromString(e,t=ze.get(Ac)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=vt.minute,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)}}class Tc extends Zu{constructor(e,t=vt.second){super(e,t)}static fromString(e,t=vt.second,i=ze.get(Tc)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new Tc(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Tc(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new Tc(s,t)}}class p3 extends Kh{}class Nk extends pm{qualifier(){return""}}class sl extends Tv{static instance=new sl;static valueRenderer=new Nk(jo.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=sl.names.slice(sl.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),n=sl.qualifier(i.uncertainComponent,i.approximateComponent),r=sl.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!s.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!s.some(a=>a.approximate));return n+i.toString(sl.valueRenderer)+r}}class f3 extends iM{constructor(e){super(e)}newYear(e){return new Mc(e,this.units.year)}newMonth(e){return new xc(e,this.units.month)}newDay(e){return new Ec(e,this.units.day)}newHour(e){return new Sc(e,this.units.hour)}newMinute(e){return new Ac(e,this.units.minute)}newSecond(e){return new Tc(e,this.units.second)}newMillisecond(e){return new Kl(e,this.units.millisecond)}newTimeshift(e){return new p3(typeof e=="number"?e:e.value)}}const Fk=new f3(r1),Uk=new f3(um);class wr extends zr{constructor(e){super(e)}toString(e=sl.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 Fk}static fromDate(e){return new wr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Sn.timeshiftOf(e)})}static fromString(e,t=ze.get(wr)){const i=t.parse(e);return new wr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return wr.fromString(i)}clone(){return new wr(this.toSpec())}}class Bc{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new Wr(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new lh(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class jd extends _v{static instance=new jd;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=jd.qualifier(e.uncertainDuration,e.approximateDuration);if(!e.hasQualifiedComponent)return t+super.render(e);let i=t+"P";for(const[s,n]of jd.designators){const r=e.components[s];r&&(i+=jd.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+n)}return i}}class js extends Qs{#e;constructor(e){if(super(typeof e=="number"?e:{value:js.valueFromSpec(e),uncertain:e.uncertain===!0,approximate:e.approximate===!0},um.millisecond),typeof e!="number"){const t={};for(const i of js.componentNames)e[i]instanceof Xo&&(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 js.getValue(e,rn.year)+js.getValue(e,rn.month)+js.getValue(e,rn.day)+js.getValue(e,rn.hour)+js.getValue(e,rn.minute)+js.getValue(e,rn.second)}static toSpec(e,t=Uk){const i=Qs.toSpec(e,t);if(e instanceof js&&e.hasQualifiedComponent)for(const s of js.componentNames)delete i[s],e.components[s]&&(i[s]=e.components[s]);return i}static fromString(e,t=ze.get(js)){const i=t.parse(e);return new js(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new js(i-s)}toSpec(){return js.toSpec(this)}toString(e=jd.instance){return super.toString(e)}}class wf extends yf{get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=wr.fromString(e)),e&&!(e instanceof wr)&&!(e instanceof js))throw new Wr("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=wr.fromString(e)),e&&!(e instanceof wr)&&!(e instanceof js))throw new Wr("Interval end is not a level 2 date or duration: "+e);this._end=e}static fromString(e,t=ze.get(wf)){const{start:i,end:s}=t.parse(e);return new wf(i,s)}}class Eg 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=ze.get(Eg)){const{exclusive:i,values:s}=t.parse(e);return new Eg(s,i)}}class zc extends Bc{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return zc.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new Wr(`${this.name} cannot be negative`);return super.parse(e)}}class B{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 B.optional(B.group(e,...t))}static optionalNonCapturingGroup(...e){return B.optional(B.nonCapturingGroup(...e))}static numberGroup(e,t,i,s="\\d"){return B.group(e,`${i||""}[${s}]${t}`)}}const Vx="yearValue";class Mf extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Vx),"{4}",void 0)}constructor(){super(Vx,Mf.format())}}const Wx="monthValue";class xf extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Wx),"{1,2}",void 0)}constructor(){super(Wx,xf.format())}}const $x="dayValue";class bu extends zc{static format(e=""){return B.numberGroup(B.groupName(e,$x),"{1,2}",void 0)}constructor(){super($x,bu.format())}}const Kx="hourValue";class yu extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Kx),"{1,2}",void 0)}constructor(){super(Kx,yu.format())}}const Xx="minuteValue";class Ef extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Xx),"{1,2}",void 0)}constructor(){super(Xx,Ef.format())}}const Yx="secondValue";class Sf extends zc{static format(e=""){return B.numberGroup(B.groupName(e,Yx),"{1,2}",void 0)}constructor(){super(Yx,Sf.format())}}const qx="timeshiftValue",jx="shiftHour",Zx="shiftMinute";class Bu extends Bc{static format(e=""){return Gx.map(t=>t.name).join("|")+"|"+B.nonCapturingGroup(B.group(e+jx,B.numberGroup(B.groupName(e,qx),"{2}","[+-]")),B.optionalNonCapturingGroup(":?",B.numberGroup(B.groupName(e,Zx),"{2}",void 0)))}constructor(){super(qx,Bu.format())}parse(e,t){let i=0;const s=Gx.find(n=>n.name===e);if(s){if(typeof s.timeshift=="function")try{return s.timeshift(t??{})}catch(n){throw new Wr(`The time zone ${e} depends on the date: ${n.message}`)}e=s.timeshift}if(e!=="Z"){const n=this.regexGroups(e),r=n[jx];r&&(i+=parseInt(r,10)*60);const a=n[Zx];a&&(i+=parseInt(a,10))}return i}}const Jx="year",Qx="month",eE="day",tE="hour",iE="minute",sE="second",nE="millisecond",rE="timeshift";class yh extends Bc{static format(e=""){return B.group(B.groupName(e,Jx),Mf.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,Qx),xf.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,eE),bu.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,tE),yu.format(e)),":?",B.group(B.groupName(e,iE),Ef.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,sE),Sf.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,nE),"\\d+"))),"\\s*",B.optionalGroup(B.groupName(e,rE),Bu.format(e)))))}constructor(){super("date",yh.format())}parse(e){const t=this.regexGroups(e),i=t[Jx],s=t[Qx],n=t[eE],r=t[tE],a=t[iE],o=t[sE],c=t[nE],h=t[rE],d=i?new Ou(Mf.read(i)):void 0,u=s?xf.read(s):void 0;return{year:d,month:u?new Lu(u,qd.create(u.value,d?.value)):void 0,day:n?new Pu(bu.read(n)):void 0,hour:r?new Nu(yu.read(r)):void 0,minute:a?new Fu(Ef.read(a)):void 0,second:o?new Uu(Sf.read(o)):void 0,millisecond:c?Kl.parseFraction(c):void 0,timeshift:h?Ul.fromString(h,new Bu,{year:d?.value,month:u?.value,day:n?bu.read(n).value:void 0,hour:r?yu.read(r).value:void 0}):void 0}}}const aE="years",ib="months",Bk="days",oE="hours",cE="minutes",lE="seconds";class nM extends Bc{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,aE),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,ib),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Bk),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,oE),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,cE),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,lE),"+",void 0,"\\d"),"S")}constructor(){super("duration",nM.format())}parseGroups(e){return{years:e[aE],months:e[ib],days:e[ib],hours:e[oE],minutes:e[cE],seconds:e[lE]}}}const sb="start",nb="end";class rM extends Bc{static format=B.group(sb,yh.format(sb))+"/"+B.group(nb,yh.format(nb));constructor(){super("interval",rM.format)}parse(e){const t=this.regexGroups(e),i=t[sb],s=t[nb];return{start:i?Sn.fromString(i,new yh):void 0,end:s?Sn.fromString(s,new yh):void 0}}}ze.register(Sn,()=>new yh);ze.register(Pu,()=>new bu);ze.register(Qa,()=>new nM);ze.register(Nu,()=>new yu);ze.register(bf,()=>new rM);ze.register(Fu,()=>new Ef);ze.register(Lu,()=>new xf);ze.register(Uu,()=>new Sf);ze.register(Ul,()=>new Bu);ze.register(Ou,()=>new Mf);class Qi extends zc{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Qi.uncertainGroup+Qi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return B.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(B.groupName(Qi.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(Qi.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(Qi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return B.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[B.groupName(Qi.uncertainAndApproximateGroup,this.name)],a=e[B.groupName(Qi.approximateGroup,this.name)]||r,o=e[B.groupName(Qi.uncertainGroup,this.name)]||r;return{value:s,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const hE="yearValue";class Af extends Qi{constructor(){super(hE,Af.format())}static format(e=""){return"Y?"+Qi.numberFormat(B.groupName(e,hE),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const dE="monthValue";class Tf extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,dE),"{1,2}",void 0)}constructor(){super(dE,Tf.format())}}const uE="dayValue";class If extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,uE),"{1,2}",void 0)}constructor(){super(uE,If.format())}}const pE="hourValue";class _f extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,pE),"{1,2}",void 0)}constructor(){super(pE,_f.format())}}const fE="minuteValue";class kf extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,fE),"{1,2}",void 0)}constructor(){super(fE,kf.format())}}const mE="secondValue";class Df extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,mE),"{1,2}",void 0)}constructor(){super(mE,Df.format())}}class Rf extends Bu{}class hs extends Bc{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=hs.format()){super("date",e)}static format(e=""){return B.group(B.groupName(e,hs.yearGroup),Af.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.monthGroup),Tf.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.dayGroup),If.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,hs.hourGroup),_f.format(e)),":",B.group(B.groupName(e,hs.minuteGroup),kf.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,hs.secondGroup),Df.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,hs.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,hs.timeshiftGroup),Rf.format(e)))))}parseGroups(e){const t=e[hs.millisecondGroup],i=t?Kl.parseFraction(t):void 0,s=e[hs.secondGroup],n=s?Tl.fromString(s,new Df):void 0,r=e[hs.minuteGroup];let a;r&&(a=Al.fromString(r,new kf),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[hs.hourGroup];let c;o&&(c=Sl.fromString(o,new _f),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[hs.dayGroup];let d;h&&(d=El.fromString(h,new If),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[hs.monthGroup];let p;u&&(p=xl.fromString(u,new Tf),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[hs.yearGroup];let m;f&&(m=Ml.fromString(f,void 0,new Af),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[hs.timeshiftGroup],v=g?Kh.fromString(g,new Rf,{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 gE="years",vE="months",bE="days",yE="hours",wE="minutes",ME="seconds";class wh extends Qi{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,gE),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,vE),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,bE),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,yE),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,wE),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,ME),"+",void 0,"\\d"),"S")+this.formatSuffix(e)}constructor(){super("duration",wh.format())}parseGroups(e){return{years:e[gE],months:e[vE],days:e[bE],hours:e[yE],minutes:e[wE],seconds:e[ME],uncertain:!!e[Qi.uncertainGroup],approximate:!!e[Qi.approximateGroup]}}}const zk="dates",rb="start",ab="end",xE="durations",ob="durationMin",cb="durationMax";class aM extends Bc{static format=B.group(zk,B.optionalGroup(rb,B.group("openStart","\\.\\.")+"|"+hs.format(rb))+"/"+B.optionalGroup(ab,B.group("openEnd","\\.\\.")+"|"+hs.format(ab)))+"|"+B.group(xE,B.group(ob,wh.format(ob))+"/"+B.group(cb,wh.format(cb)));constructor(e="interval",t=aM.format){super(e,t)}parseGroups(e){let t,i;if(e[xE]){const n=e[ob];t=Qs.fromString(n,new wh);const r=e[cb];i=Qs.fromString(r,new wh)}else{const n=e[rb];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=zr.fromString(n,new hs)}const r=e[ab];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=zr.fromString(r,new hs)}}return{start:t,end:i}}}ze.register(zr,()=>new hs);ze.register(El,()=>new If);ze.register(Qs,()=>new wh);ze.register(Sl,()=>new _f);ze.register(yf,()=>new aM);ze.register(Al,()=>new kf);ze.register(xl,()=>new Tf);ze.register(Tl,()=>new Df);ze.register(Kh,()=>new Rf);ze.register(Ml,()=>new Af);class hi extends Qi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=hi.uncertainGroup+hi.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(B.groupName(hi.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(hi.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(hi.uncertainAndApproximateGroup,e),"%")+Qi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[B.groupName(hi.uncertainAndApproximateGroup,this.name)];return(e[B.groupName(hi.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[B.groupName(hi.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const sp="yearValue",EE="exp",SE="signif";class Cf extends hi{constructor(){super(sp,Cf.format())}static format(e=""){return"Y?"+B.nonCapturingGroup(B.group(B.groupName(e,EE),"[-]?\\d+E\\d+")+"|"+hi.numberFormat(B.groupName(e,sp),"+","[-]?")+B.optionalGroup(B.groupName(e,SE),"S\\d+"))}parseGroups(e){const t=e[EE];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[sp]=c.toString()}const i=e[SE],s=e[sp];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[sp]=(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 AE="monthValue";class Of extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,AE),"{1,2}",void 0)}constructor(){super(AE,Of.format())}}const TE="dayValue";class Lf extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,TE),"{1,2}",void 0)}constructor(){super(TE,Lf.format())}}const IE="hourValue";class Pf extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,IE),"{1,2}",void 0)}constructor(){super(IE,Pf.format())}}const _E="secondValue";class Nf extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,_E),"{1,2}",void 0)}constructor(){super(_E,Nf.format())}}const kE="minuteValue";class Ff extends hi{static format(e=""){return hi.numberFormat(B.groupName(e,kE),"{1,2}",void 0)}constructor(){super(kE,Ff.format())}}class Hk extends Rf{}class mi extends Bc{static yearGroup=hs.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",mi.format())}static format(e=""){return B.group(B.groupName(e,mi.yearGroup),Cf.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,mi.monthGroup),Of.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,mi.dayGroup),Lf.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,mi.hourGroup),Pf.format(e)),":",B.group(B.groupName(e,mi.minuteGroup),Ff.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,mi.secondGroup),Nf.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,mi.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,mi.timeshiftGroup),Hk.format(e)))))}parseGroups(e){const t=e[mi.millisecondGroup],i=t?Kl.parseFraction(t):void 0,s=e[mi.secondGroup];let n;s&&(n=Tc.fromString(s,void 0,new Nf),n.uncertain=n?.uncertain||!1,n.approximate=n?.approximate||!1);const r=e[mi.minuteGroup];let a;r&&(a=Ac.fromString(r,new Ff),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[mi.hourGroup];let c;o&&(c=Sc.fromString(o,new Pf),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[mi.dayGroup];let d;h&&(d=Ec.fromString(h,new Lf),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[mi.monthGroup];let p;u&&(p=xc.fromString(u,new Of),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[mi.yearGroup];let m;f&&(m=Mc.fromString(f,void 0,new Cf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[mi.timeshiftGroup],v=g?p3.fromString(g,new Rf,{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 DE="durationValue";class oM extends hi{static format(e=""){return"^"+hi.numberFormat(B.groupName(e,DE),"+",void 0)}constructor(){super(DE,oM.format())}}class Gk extends tM{millisecond=new zi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new zi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new zi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new zi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new zi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new zi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new zi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const rd=new Gk;class ht extends hi{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 oM;static componentFormat(e,t,i,s,n=""){const r=B.group(B.groupName(e,ht.quantityGroup(t)),hi.numberFormat(B.groupName(e,i),"+",void 0,"\\d"));return B.group(B.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=B.groupName(e,ht.durationGroup);return this.qualifierFormat(B.groupName(hi.uncertainGroup,t),"?")+this.qualifierFormat(B.groupName(hi.approximateGroup,t),"~")+this.qualifierFormat(B.groupName(hi.uncertainAndApproximateGroup,t),"%")+"P"+B.optional(ht.componentFormat(e,ht.yearsGroup,mi.yearGroup,"Y"))+B.optionalNonCapturingGroup(ht.componentFormat(e,ht.monthsGroup,mi.monthGroup,"MM")+"|"+ht.componentFormat(e,ht.isoMonthsGroup,"isoMonth","M",ht.isoMonthsLookahead))+B.optional(ht.componentFormat(e,ht.daysGroup,mi.dayGroup,"D"))+"T?"+B.optional(ht.componentFormat(e,ht.hoursGroup,mi.hourGroup,"H"))+B.optional(ht.componentFormat(e,ht.minutesGroup,mi.minuteGroup,"M"))+B.optional(ht.componentFormat(e,ht.secondsGroup,mi.secondGroup,"S"))+B.optionalGroup(B.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,Tc,rd.second),i.uncertain=!!e[B.groupName(hi.uncertainGroup,ht.secondsGroup)]||!1,i.approximate=!!e[B.groupName(hi.approximateGroup,ht.secondsGroup)]||!1);const s=e[ht.quantityGroup(ht.minutesGroup)];let n;s&&(n=ht.parseComponent(s,Ac,rd.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,Sc,rd.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,Ec,rd.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,xc,rd.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,Mc,rd.year),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ht.suffixGroup],m=!!e[B.groupName(hi.uncertainAndApproximateGroup,ht.durationGroup)]||f==="%",g=m||!!e[B.groupName(hi.uncertainGroup,ht.durationGroup)]||f==="?",v=m||!!e[B.groupName(hi.approximateGroup,ht.durationGroup)]||f==="~";return{years:p,months:d,days:c,hours:a,minutes:n,seconds:i,uncertain:g,approximate:v}}}const Vk="dates",lb="start",hb="end",RE="durations",db="durationMin",ub="durationMax";class kv extends Bc{static format=B.group(Vk,B.optionalGroup(lb,B.group("openStart","\\.\\.")+"|"+mi.format(lb))+"/"+B.optionalGroup(hb,B.group("openEnd","\\.\\.")+"|"+mi.format(hb)))+"|"+B.group(RE,B.group(db,ht.format(db))+"/"+B.group(ub,ht.format(ub)));constructor(e="interval",t=kv.format){super(e,t)}parseGroups(e){let t,i;if(e[RE]){const n=e[db];t=js.fromString(n,new ht);const r=e[ub];i=js.fromString(r,new ht)}else{const n=e[lb];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=wr.fromString(n,new mi)}const r=e[hb];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=wr.fromString(r,new mi)}}return{start:t,end:i}}}class Wk{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=wf.fromString(r.replace("..","/"),new kv):a=wr.fromString(r,new mi),n.push(a)}return{values:n,exclusive:t}}}ze.register(wr,()=>new mi);ze.register(Ec,()=>new Lf);ze.register(js,()=>new ht);ze.register(Sc,()=>new Pf);ze.register(wf,()=>new kv);ze.register(Ac,()=>new Ff);ze.register(xc,()=>new Of);ze.register(Tc,()=>new Nf);ze.register(Eg,()=>new Wk);ze.register(Mc,()=>new Cf);class ws{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[ws.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>ws.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(ws.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=>ws.base(c)===ws.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]}}ws.any=new ws([]);var CE;(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"})(CE||(CE={}));var OE;(function(l){l.neutral="neutral",l.male="male",l.female="female"})(OE||(OE={}));class $k extends Error{constructor(e,t){super(e),this.cause=t}}class cM extends $k{constructor(e=cM.defaultMessage,t){super(e,t)}}cM.defaultMessage="Assertion failed";var LE;(function(l){l.country="country",l.region="region",l.department="department",l.city="city",l.company="company"})(LE||(LE={}));var PE;(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"})(PE||(PE={}));class Kk{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"}}/**
|
|
472
472
|
@preserve
|
|
473
473
|
|
|
474
474
|
Astronomy library for JavaScript (browser and Node.js).
|
|
@@ -4692,7 +4692,7 @@ button.link { padding: 0; border: 0; background: none; color: inherit; font: inh
|
|
|
4692
4692
|
.choose label { display: block; white-space: nowrap; }
|
|
4693
4693
|
.choose .actions { margin-top: 6px; display: flex; gap: 8px; }
|
|
4694
4694
|
${ns.CSS}
|
|
4695
|
-
`;frame;frameWatch;watchFrame(){this.frameWatch||!this.frame||(this.frameWatch=new MutationObserver(()=>{this.frame?.section.hasAttribute("data-unfolded")&&this.loaded.size===0&&this.loadRecordings()}),this.frameWatch.observe(this.frame.section,{attributes:!0,attributeFilter:["data-unfolded"]}))}messages;language="en";said=new ws(["en"]);input;opened=!1;loaded=new Map;static register(){customElements.get(Zr.TAG)||customElements.define(Zr.TAG,Zr)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}show(e){this.input=e,this.loaded.clear(),this.loadingNow=void 0,this.draw(),this.opened&&this.loadRecordings()}redraw(){this.draw()}async loadLocale(){const e=xs.preferencesFor(this),t=da(e,Gr);this.messages=await V5.load(t),this.language=t,this.said=new ws(e),this.draw()}static accounts(e){return(e.events??[]).filter(t=>t.eventType===xi.SIGHTING_EVENT&&t.interpretationOf===void 0&&t.id!==void 0)}static readingEvents(e,t){return(e.events??[]).filter(i=>i.eventType===xi.SIGHTING_EVENT&&i.id!==void 0&&[i.interpretationOf].flat().includes(t))}async weigh(){const e=this.input;if(!e?.account||(e.caseJson().hvs?.hypotheses??[]).length===0||(await this.loadRecordings(),this.input!==e||!this.loaded.has(e.account)))return;const t=e.caseJson(),i=new Map((t.hvs?.hypotheses??[]).map(s=>[s.id,this.titleOf(s)]));return{result:this.resultOf(t,e.account),title:s=>i.get(s)??s}}loadingNow;loadRecordings(){if(this.loadingNow)return this.loadingNow;const e=this.loadOnce().finally(()=>{this.loadingNow===e&&(this.loadingNow=void 0)});return this.loadingNow=e,e}async loadOnce(){const e=this.input;if(!e||this.loaded.size>0)return;const t=e.caseJson(),i=e.account!==void 0?[e.account]:Zr.accounts(t).map(n=>n.id),s=to.kinds();for(const n of i){const r=await e.recording(n),a=[];for(const o of Zr.readingEvents(t,n)){const c=await e.recording(o.id);if(!c)continue;const h=xt.strip(c).recording.interpretation;await Wt.load(h,s);const d=Wt.expand(h,s),u=r?Yn.resultOf(r,Wt.computes(h,s)?{...c,interpretation:d}:c):void 0;a.push({id:o.id,label:this.said.read(o.title)??o.id,phenomena:Wt.phenomena(h,s),...u?{outcomes:u.outcomes}:{}})}if(this.input!==e)return;this.loaded.set(n,{...r?{account:r}:{},readings:a})}this.draw()}draw(){const e=this.messages,t=this.input?.caseJson(),i=t?.elements??[],s=t?.hvs?.hypotheses??[];if(this.hidden=!t||i.length===0&&s.length===0,this.frame&&(this.frame.section.hidden=this.hidden),!e||!t||this.hidden){this.shadowRoot.replaceChildren();return}const n=document.createElement("style");if(n.textContent=Zr.CSS,this.frame){this.frame.title.replaceChildren(e.heading,ns.of(this.input?.account===void 0?e.hintCase:e.hint)),this.watchFrame(),this.loaded.size===0&&this.frame.section.hasAttribute("data-unfolded")&&this.loadRecordings();const o=document.createElement("div");o.append(...this.loaded.size===0?[this.paragraph(e.loading,"note")]:this.input.account!==void 0?this.observation(t,this.input.account,e):this.caseLines(t,e),this.credit(t,e)),this.shadowRoot.replaceChildren(n,o);return}const r=document.createElement("details");r.open=this.opened,r.addEventListener("toggle",()=>{this.opened=r.open,r.open&&this.loadRecordings()});const a=document.createElement("summary");if(a.append(e.heading,ns.of(this.input?.account===void 0?e.hintCase:e.hint)),r.append(a),this.opened){const o=this.loaded.size>0;r.append(...o?this.input.account!==void 0?this.observation(t,this.input.account,e):this.caseLines(t,e):[this.paragraph(e.loading,"note")]),r.append(this.credit(t,e))}this.shadowRoot.replaceChildren(n,r)}resultOf(e,t){const i=Zr.accounts(e).length<=1;return $n.of(e.elements??[],e.hvs,t,this.loaded.get(t)?.readings??[],i)}observation(e,t,i){const s=Zr.accounts(e).length<=1,n=$n.elementsOf(e.elements??[],t,s),r=e.hvs?.hypotheses??[],a=this.resultOf(e,t),o=this.loaded.get(t),c=(e.events??[]).some(u=>u.eventType===xi.INTERVIEW_EVENT&&[u.interviewOf].flat().includes(t)),h=[this.heading(i.iqi.heading),this.iqiList(Eo.of(e.hvs?.observations?.[t]?.iqi,o?.account?[o.account]:[],c),i)];h.push(this.heading(i.elements.heading)),n.length===0?h.push(this.paragraph(i.noElements,"note")):(e.elementsSealed||h.push(this.paragraph(i.notSealed,"note warn")),h.push(this.elementsTable(n,r,a,i)));const d=$n.unassigned(e.elements??[],s);return d.length>0&&h.push(this.paragraph(i.unassigned.replace("{ids}",d.map(u=>u.id).join(", ")),"note warn")),h.push(this.heading(i.hypotheses.heading)),h.push(r.length===0?this.paragraph(i.noHypotheses,"note"):this.hypothesesTable(r,a,o?.readings??[],i)),h}caseLines(e,t){const i=e.hvs?.hypotheses??[],s=document.createElement("ul");s.className="observations";for(const n of Zr.accounts(e)){const r=this.resultOf(e,n.id),a=document.createElement("li"),o=this.said.read(n.title)??n.id;if(this.input?.open){const g=document.createElement("button");g.type="button",g.className="link",g.textContent=o,g.addEventListener("click",()=>this.input?.open?.(n.id)),a.append(g)}else a.append(o);const c=r.hypotheses.find(g=>g.dominant),h=c?i.find(g=>g.id===c.id):void 0,d=new Intl.NumberFormat(this.language,{minimumFractionDigits:2,maximumFractionDigits:2}),u=!c||!h?t.caseLine.none:t.caseLine.dominant.replace("{hypothesis}",h.code?`${h.code} ${this.titleOf(h)}`:this.titleOf(h)).replace("{hvs}",c.hvs?d.format(c.hvs.preferred):"–"),[p,f=""]=t.caseLine.item.replace("{verdict}",u).split("{observation}"),m=a.firstChild;a.replaceChildren(p,m,f),s.append(a)}return[this.paragraph(t.caseLine.intro,"note"),s]}credit(e,t){const i=document.createElement("p");return i.className="credit",i.append(t.credit.replace("{protocol}",e.hvs?.protocol??""),e.hvs?.taxonomy?` · ${t.taxonomy.replace("{taxonomy}",e.hvs.taxonomy)}`:""),i}iqiList(e,t){const i=document.createElement("ul");i.className="iqi";for(const n of e){const r=document.createElement("li"),a=document.createElement("span");a.className="level",a.textContent=n.level?t.iqi.levels[n.level]:t.iqi.unrated,n.suggested&&(r.dataset.suggested="",a.title=t.iqi.suggested);const[o,c=""]=t.iqi.item.replace("{group}",t.iqi.groups[n.group]).split("{level}");r.append(o,a,c),i.append(r)}const s=Eo.total(e);if(s.of>0){const n=document.createElement("li"),r=new Intl.NumberFormat(this.language,{maximumFractionDigits:1});n.textContent=`IQI ${t.iqi.total.replace("{sum}",r.format(s.sum)).replace("{of}",String(s.of))}`,i.append(n)}return i}elementsTable(e,t,i,s){const n=s.elements,r=document.createElement("table");r.className="elements";const a=r.createTHead().insertRow();for(const c of[n.id,n.element,n.status,...t.map(h=>h.code??this.titleOf(h))]){const h=document.createElement("th");h.scope="col",h.textContent=c,a.append(h)}const o=r.createTBody();for(const c of e){const h=o.insertRow(),d=i.counted.includes(c.id);h.dataset.counted=String(d),i.discriminating.includes(c.id)&&(h.dataset.discriminating="",h.title=n.discriminating),h.insertCell().textContent=c.id,h.insertCell().textContent=this.said.read(c.title)??"",h.insertCell().textContent=n.statuses[c.status];for(const u of i.hypotheses){const p=h.insertCell();p.className="mark";const f=u.explanations[c.id];if(!f)continue;p.dataset.explained=String(f.explained),p.dataset.by=f.by,p.textContent=f.explained?"✓":"✗";const m=f.by==="confrontation"?f.explained?n.explainedByReading:n.notExplainedByReading:f.explained?n.explainedDeclared:n.notExplainedDeclared;p.title=f.readings?`${m} · ${n.variants.replace("{n}",String(f.readings))}`:m}}return this.scrolling(r)}hypothesesTable(e,t,i,s){const n=s.hypotheses,r=document.createElement("table");r.className="hypotheses";const a=r.createTHead().insertRow();for(const c of[n.code,n.hypothesis,n.readings,n.csRaw,n.csDiscriminating,n.ps,n.hvs,n.standing]){const h=document.createElement("th");h.scope="col",h.textContent=c,c===n.standing&&(h.title=n.admissibleHint),a.append(h)}const o=r.createTBody();return e.forEach((c,h)=>{const d=t.hypotheses[h],u=o.insertRow();d.dominant&&(u.dataset.dominant=""),u.insertCell().textContent=c.code??"",u.insertCell().textContent=this.titleOf(c),this.readingsCell(u.insertCell(),c,d,i,s),this.scoreCell(u,d.csRaw,s),this.scoreCell(u,d.csDiscriminating,s);const p=this.scoreCell(u,d.ps,s),f=[...d.geometric?[n.geometric]:[],...d.missing?[n.missing.replace("{names}",d.missing.map(g=>n.ratings[g]??g).join(", "))]:[]];f.length&&(p.title=f.join(" · ")),this.scoreCell(u,d.hvs,s);const m=u.insertCell();m.textContent=this.standingOf(d,s),m.title=n.admissibleHint}),this.scrolling(r)}readingsCell(e,t,i,s,n){const r=n.hypotheses;e.className="readings";const a=i.readings.map(v=>s.find(b=>b.id===v)?.label??v);e.append(a.length>0?a.join(", "):r.noReading);const o=document.createElement("div");o.className="how";const c=[t.phenomenon??[]].flat();o.textContent=i.linkedBy==="chosen"?r.chosen:c.length>0?r.byPhenomenon.replace("{phenomenon}",c.join(" + ")):r.noPhenomenon,e.append(o);const h=this.input?.choose;if(!h||s.length===0)return;const d=document.createElement("span");d.className="choose";const u=document.createElement("button");u.type="button",u.className="link",u.textContent=r.choose;const p=document.createElement("div");p.popover="auto";const f=s.map(v=>{const b=document.createElement("label"),w=document.createElement("input");return w.type="checkbox",w.value=v.id,w.checked=i.readings.includes(v.id),b.append(w," ",v.label),p.append(b),w}),m=document.createElement("div");m.className="actions";const g=document.createElement("button");if(g.type="button",g.textContent=r.keepChoice,g.addEventListener("click",()=>{p.hidePopover(),h(t.id,f.filter(v=>v.checked).map(v=>v.value))}),m.append(g),t.readings!==void 0){const v=document.createElement("button");v.type="button",v.textContent=r.automatic,v.addEventListener("click",()=>{p.hidePopover(),h(t.id,void 0)}),m.append(v)}p.append(m),u.addEventListener("click",()=>p.togglePopover()),d.append(u,p),e.append(d)}scoreCell(e,t,i){const s=e.insertCell();if(s.className="number",!t)return s.textContent="–",s;const n=new Intl.NumberFormat(this.language,{minimumFractionDigits:2,maximumFractionDigits:2}),[r,a]=t.envelope;return s.textContent=r===a&&r===t.preferred?n.format(t.preferred):i.hypotheses.score.replace("{preferred}",n.format(t.preferred)).replace("{low}",n.format(r)).replace("{high}",n.format(a)),s}standingOf(e,t){const i=t.hypotheses,s=[e.admissible?i.admissible:i.notAdmissible];return e.dominant&&s.push(i.dominant),e.milestone&&s.push(i[e.milestone]),s.join(", ")}titleOf(e){return this.said.read(e.title)??e.id}heading(e){const t=document.createElement("h4");return t.textContent=e,t}paragraph(e,t){const i=document.createElement("p");return i.className=t,i.textContent=e,i}scrolling(e){const t=document.createElement("div");return t.className="scroll",t.append(e),t}}class R2{constructor(e,t,i){this.m=e,this.placeName=t,this.language=i}robustness(e){switch(e.robustness){case"robust-plausible":return this.m.robustPlausible;case"robust-exclusion":return this.m.robustExclusion;case"conditional":return this.m.conditional.replace("{where}",this.where(e.onlyIf))}}evolution(e){const t=e.asWritten==="plausible"?this.m.asWrittenPlausible:this.m.asWrittenExcluded;if(e.independent)return`${t}, ${this.m.independent}`;const i=e.asWritten==="plausible"?{"robust-plausible":this.m.becomesRobust,"robust-exclusion":this.m.excludedEverywhere,conditional:this.m.becomesConditional}[e.robustness]:{"robust-plausible":this.m.plausibleEverywhere,"robust-exclusion":this.m.becomesRobustExclusion,conditional:this.m.plausibleOnlyIf}[e.robustness];return`${t}, ${i}`}sentence(e){const t=e.independent?"":` (${this.m.holdsIn.replace("{holds}",String(e.holds)).replace("{played}",String(e.played))})`;return`${this.robustness(e)}${this.m.colon}${this.evolution(e)}${t}`}where(e){return e?.places?e.places.map(t=>t==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t))).join(this.m.or):e?.dates?e.dates.map(t=>this.m.onDates.replace("{dates}",this.date(t))).join(this.m.or):(e?.scenarios??[]).map(t=>this.m.inScenarios.replace("{scenarios}",this.scenarioId(t))).join(this.m.or)}static grouped(e){const t=new Map;for(const s of e){const n=`${s.candidate}|${s.robustness}|${JSON.stringify(s.onlyIf??{})}`,r=t.get(n)??{...s,accounts:[]};s.eventId&&r.accounts.push(s.eventId),t.set(n,r)}const i={"robust-plausible":0,conditional:1,"robust-exclusion":2};return[...t.values()].sort((s,n)=>i[s.robustness]-i[n.robustness])}alert(e){return(e.robustness==="robust-exclusion"?this.m.alertExcluded:e.robustness==="robust-plausible"?this.m.alertPlausible:this.m.alertConditional).replace("{name}",e.label).replace("{where}",this.where(e.onlyIf))}scenario(e){return`${this.placeName(e.placeId)}, ${this.instant(e.local)}`}scenarioId(e){const[t,i]=e.split("@");return`${this.placeName(t)}, ${this.instant(i)}`}title(e,t){const i=t.placeId==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t.placeId));return this.m.scenarioTitle.replace("{title}",e).replace("{place}",i).replace("{date}",this.instant(t.local))}date(e){return new Date(`${e}T12:00Z`).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"})}instant(e){return new Date(`${e.slice(0,16)}Z`).toLocaleString(this.language,{day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC"})}}class su extends HTMLElement{static TAG="rr0-scenario-sweep";static CSS=`
|
|
4695
|
+
`;frame;frameWatch;watchFrame(){this.frameWatch||!this.frame||(this.frameWatch=new MutationObserver(()=>{this.frame?.section.hasAttribute("data-unfolded")&&this.loaded.size===0&&this.loadRecordings()}),this.frameWatch.observe(this.frame.section,{attributes:!0,attributeFilter:["data-unfolded"]}))}messages;language="en";said=new ws(["en"]);input;opened=!1;onDemand=!1;asked=!1;unfold(){this.asked=!0,this.opened=!0,this.draw(),this.loadRecordings(),this.scrollIntoView({block:"nearest",behavior:"smooth"})}loaded=new Map;static register(){customElements.get(Zr.TAG)||customElements.define(Zr.TAG,Zr)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}show(e){this.input=e,this.loaded.clear(),this.loadingNow=void 0,this.draw(),this.opened&&this.loadRecordings()}redraw(){this.draw()}async loadLocale(){const e=xs.preferencesFor(this),t=da(e,Gr);this.messages=await V5.load(t),this.language=t,this.said=new ws(e),this.draw()}static accounts(e){return(e.events??[]).filter(t=>t.eventType===xi.SIGHTING_EVENT&&t.interpretationOf===void 0&&t.id!==void 0)}static readingEvents(e,t){return(e.events??[]).filter(i=>i.eventType===xi.SIGHTING_EVENT&&i.id!==void 0&&[i.interpretationOf].flat().includes(t))}async weigh(){const e=this.input;if(!e?.account||(e.caseJson().hvs?.hypotheses??[]).length===0||(await this.loadRecordings(),this.input!==e||!this.loaded.has(e.account)))return;const t=e.caseJson(),i=new Map((t.hvs?.hypotheses??[]).map(s=>[s.id,this.titleOf(s)]));return{result:this.resultOf(t,e.account),title:s=>i.get(s)??s}}loadingNow;loadRecordings(){if(this.loadingNow)return this.loadingNow;const e=this.loadOnce().finally(()=>{this.loadingNow===e&&(this.loadingNow=void 0)});return this.loadingNow=e,e}async loadOnce(){const e=this.input;if(!e||this.loaded.size>0)return;const t=e.caseJson(),i=e.account!==void 0?[e.account]:Zr.accounts(t).map(n=>n.id),s=to.kinds();for(const n of i){const r=await e.recording(n),a=[];for(const o of Zr.readingEvents(t,n)){const c=await e.recording(o.id);if(!c)continue;const h=xt.strip(c).recording.interpretation;await Wt.load(h,s);const d=Wt.expand(h,s),u=r?Yn.resultOf(r,Wt.computes(h,s)?{...c,interpretation:d}:c):void 0;a.push({id:o.id,label:this.said.read(o.title)??o.id,phenomena:Wt.phenomena(h,s),...u?{outcomes:u.outcomes}:{}})}if(this.input!==e)return;this.loaded.set(n,{...r?{account:r}:{},readings:a})}this.draw()}draw(){const e=this.messages,t=this.input?.caseJson(),i=t?.elements??[],s=t?.hvs?.hypotheses??[];if(this.hidden=!t||i.length===0&&s.length===0||this.onDemand&&!this.asked,this.frame&&(this.frame.section.hidden=this.hidden),!e||!t||this.hidden){this.shadowRoot.replaceChildren();return}const n=document.createElement("style");if(n.textContent=Zr.CSS,this.frame){this.frame.title.replaceChildren(e.heading,ns.of(this.input?.account===void 0?e.hintCase:e.hint)),this.watchFrame(),this.loaded.size===0&&this.frame.section.hasAttribute("data-unfolded")&&this.loadRecordings();const o=document.createElement("div");o.append(...this.loaded.size===0?[this.paragraph(e.loading,"note")]:this.input.account!==void 0?this.observation(t,this.input.account,e):this.caseLines(t,e),this.credit(t,e)),this.shadowRoot.replaceChildren(n,o);return}const r=document.createElement("details");r.open=this.opened,r.addEventListener("toggle",()=>{this.opened!==r.open&&(this.opened=r.open,!r.open&&this.onDemand&&(this.asked=!1),this.draw(),r.open&&this.loadRecordings())});const a=document.createElement("summary");if(a.append(e.heading,ns.of(this.input?.account===void 0?e.hintCase:e.hint)),r.append(a),this.opened){const o=this.loaded.size>0;r.append(...o?this.input.account!==void 0?this.observation(t,this.input.account,e):this.caseLines(t,e):[this.paragraph(e.loading,"note")]),r.append(this.credit(t,e))}this.shadowRoot.replaceChildren(n,r)}resultOf(e,t){const i=Zr.accounts(e).length<=1;return $n.of(e.elements??[],e.hvs,t,this.loaded.get(t)?.readings??[],i)}observation(e,t,i){const s=Zr.accounts(e).length<=1,n=$n.elementsOf(e.elements??[],t,s),r=e.hvs?.hypotheses??[],a=this.resultOf(e,t),o=this.loaded.get(t),c=(e.events??[]).some(u=>u.eventType===xi.INTERVIEW_EVENT&&[u.interviewOf].flat().includes(t)),h=[this.heading(i.iqi.heading),this.iqiList(Eo.of(e.hvs?.observations?.[t]?.iqi,o?.account?[o.account]:[],c),i)];h.push(this.heading(i.elements.heading)),n.length===0?h.push(this.paragraph(i.noElements,"note")):(e.elementsSealed||h.push(this.paragraph(i.notSealed,"note warn")),h.push(this.elementsTable(n,r,a,i)));const d=$n.unassigned(e.elements??[],s);return d.length>0&&h.push(this.paragraph(i.unassigned.replace("{ids}",d.map(u=>u.id).join(", ")),"note warn")),h.push(this.heading(i.hypotheses.heading)),h.push(r.length===0?this.paragraph(i.noHypotheses,"note"):this.hypothesesTable(r,a,o?.readings??[],i)),h}caseLines(e,t){const i=e.hvs?.hypotheses??[],s=document.createElement("ul");s.className="observations";for(const n of Zr.accounts(e)){const r=this.resultOf(e,n.id),a=document.createElement("li"),o=this.said.read(n.title)??n.id;if(this.input?.open){const g=document.createElement("button");g.type="button",g.className="link",g.textContent=o,g.addEventListener("click",()=>this.input?.open?.(n.id)),a.append(g)}else a.append(o);const c=r.hypotheses.find(g=>g.dominant),h=c?i.find(g=>g.id===c.id):void 0,d=new Intl.NumberFormat(this.language,{minimumFractionDigits:2,maximumFractionDigits:2}),u=!c||!h?t.caseLine.none:t.caseLine.dominant.replace("{hypothesis}",h.code?`${h.code} ${this.titleOf(h)}`:this.titleOf(h)).replace("{hvs}",c.hvs?d.format(c.hvs.preferred):"–"),[p,f=""]=t.caseLine.item.replace("{verdict}",u).split("{observation}"),m=a.firstChild;a.replaceChildren(p,m,f),s.append(a)}return[this.paragraph(t.caseLine.intro,"note"),s]}credit(e,t){const i=document.createElement("p");return i.className="credit",i.append(t.credit.replace("{protocol}",e.hvs?.protocol??""),e.hvs?.taxonomy?` · ${t.taxonomy.replace("{taxonomy}",e.hvs.taxonomy)}`:""),i}iqiList(e,t){const i=document.createElement("ul");i.className="iqi";for(const n of e){const r=document.createElement("li"),a=document.createElement("span");a.className="level",a.textContent=n.level?t.iqi.levels[n.level]:t.iqi.unrated,n.suggested&&(r.dataset.suggested="",a.title=t.iqi.suggested);const[o,c=""]=t.iqi.item.replace("{group}",t.iqi.groups[n.group]).split("{level}");r.append(o,a,c),i.append(r)}const s=Eo.total(e);if(s.of>0){const n=document.createElement("li"),r=new Intl.NumberFormat(this.language,{maximumFractionDigits:1});n.textContent=`IQI ${t.iqi.total.replace("{sum}",r.format(s.sum)).replace("{of}",String(s.of))}`,i.append(n)}return i}elementsTable(e,t,i,s){const n=s.elements,r=document.createElement("table");r.className="elements";const a=r.createTHead().insertRow();for(const c of[n.id,n.element,n.status,...t.map(h=>h.code??this.titleOf(h))]){const h=document.createElement("th");h.scope="col",h.textContent=c,a.append(h)}const o=r.createTBody();for(const c of e){const h=o.insertRow(),d=i.counted.includes(c.id);h.dataset.counted=String(d),i.discriminating.includes(c.id)&&(h.dataset.discriminating="",h.title=n.discriminating),h.insertCell().textContent=c.id,h.insertCell().textContent=this.said.read(c.title)??"",h.insertCell().textContent=n.statuses[c.status];for(const u of i.hypotheses){const p=h.insertCell();p.className="mark";const f=u.explanations[c.id];if(!f)continue;p.dataset.explained=String(f.explained),p.dataset.by=f.by,p.textContent=f.explained?"✓":"✗";const m=f.by==="confrontation"?f.explained?n.explainedByReading:n.notExplainedByReading:f.explained?n.explainedDeclared:n.notExplainedDeclared;p.title=f.readings?`${m} · ${n.variants.replace("{n}",String(f.readings))}`:m}}return this.scrolling(r)}hypothesesTable(e,t,i,s){const n=s.hypotheses,r=document.createElement("table");r.className="hypotheses";const a=r.createTHead().insertRow();for(const c of[n.code,n.hypothesis,n.readings,n.csRaw,n.csDiscriminating,n.ps,n.hvs,n.standing]){const h=document.createElement("th");h.scope="col",h.textContent=c,c===n.standing&&(h.title=n.admissibleHint),a.append(h)}const o=r.createTBody();return e.forEach((c,h)=>{const d=t.hypotheses[h],u=o.insertRow();d.dominant&&(u.dataset.dominant=""),u.insertCell().textContent=c.code??"",u.insertCell().textContent=this.titleOf(c),this.readingsCell(u.insertCell(),c,d,i,s),this.scoreCell(u,d.csRaw,s),this.scoreCell(u,d.csDiscriminating,s);const p=this.scoreCell(u,d.ps,s),f=[...d.geometric?[n.geometric]:[],...d.missing?[n.missing.replace("{names}",d.missing.map(g=>n.ratings[g]??g).join(", "))]:[]];f.length&&(p.title=f.join(" · ")),this.scoreCell(u,d.hvs,s);const m=u.insertCell();m.textContent=this.standingOf(d,s),m.title=n.admissibleHint}),this.scrolling(r)}readingsCell(e,t,i,s,n){const r=n.hypotheses;e.className="readings";const a=i.readings.map(v=>s.find(b=>b.id===v)?.label??v);e.append(a.length>0?a.join(", "):r.noReading);const o=document.createElement("div");o.className="how";const c=[t.phenomenon??[]].flat();o.textContent=i.linkedBy==="chosen"?r.chosen:c.length>0?r.byPhenomenon.replace("{phenomenon}",c.join(" + ")):r.noPhenomenon,e.append(o);const h=this.input?.choose;if(!h||s.length===0)return;const d=document.createElement("span");d.className="choose";const u=document.createElement("button");u.type="button",u.className="link",u.textContent=r.choose;const p=document.createElement("div");p.popover="auto";const f=s.map(v=>{const b=document.createElement("label"),w=document.createElement("input");return w.type="checkbox",w.value=v.id,w.checked=i.readings.includes(v.id),b.append(w," ",v.label),p.append(b),w}),m=document.createElement("div");m.className="actions";const g=document.createElement("button");if(g.type="button",g.textContent=r.keepChoice,g.addEventListener("click",()=>{p.hidePopover(),h(t.id,f.filter(v=>v.checked).map(v=>v.value))}),m.append(g),t.readings!==void 0){const v=document.createElement("button");v.type="button",v.textContent=r.automatic,v.addEventListener("click",()=>{p.hidePopover(),h(t.id,void 0)}),m.append(v)}p.append(m),u.addEventListener("click",()=>p.togglePopover()),d.append(u,p),e.append(d)}scoreCell(e,t,i){const s=e.insertCell();if(s.className="number",!t)return s.textContent="–",s;const n=new Intl.NumberFormat(this.language,{minimumFractionDigits:2,maximumFractionDigits:2}),[r,a]=t.envelope;return s.textContent=r===a&&r===t.preferred?n.format(t.preferred):i.hypotheses.score.replace("{preferred}",n.format(t.preferred)).replace("{low}",n.format(r)).replace("{high}",n.format(a)),s}standingOf(e,t){const i=t.hypotheses,s=[e.admissible?i.admissible:i.notAdmissible];return e.dominant&&s.push(i.dominant),e.milestone&&s.push(i[e.milestone]),s.join(", ")}titleOf(e){return this.said.read(e.title)??e.id}heading(e){const t=document.createElement("h4");return t.textContent=e,t}paragraph(e,t){const i=document.createElement("p");return i.className=t,i.textContent=e,i}scrolling(e){const t=document.createElement("div");return t.className="scroll",t.append(e),t}}class R2{constructor(e,t,i){this.m=e,this.placeName=t,this.language=i}robustness(e){switch(e.robustness){case"robust-plausible":return this.m.robustPlausible;case"robust-exclusion":return this.m.robustExclusion;case"conditional":return this.m.conditional.replace("{where}",this.where(e.onlyIf))}}evolution(e){const t=e.asWritten==="plausible"?this.m.asWrittenPlausible:this.m.asWrittenExcluded;if(e.independent)return`${t}, ${this.m.independent}`;const i=e.asWritten==="plausible"?{"robust-plausible":this.m.becomesRobust,"robust-exclusion":this.m.excludedEverywhere,conditional:this.m.becomesConditional}[e.robustness]:{"robust-plausible":this.m.plausibleEverywhere,"robust-exclusion":this.m.becomesRobustExclusion,conditional:this.m.plausibleOnlyIf}[e.robustness];return`${t}, ${i}`}sentence(e){const t=e.independent?"":` (${this.m.holdsIn.replace("{holds}",String(e.holds)).replace("{played}",String(e.played))})`;return`${this.robustness(e)}${this.m.colon}${this.evolution(e)}${t}`}where(e){return e?.places?e.places.map(t=>t==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t))).join(this.m.or):e?.dates?e.dates.map(t=>this.m.onDates.replace("{dates}",this.date(t))).join(this.m.or):(e?.scenarios??[]).map(t=>this.m.inScenarios.replace("{scenarios}",this.scenarioId(t))).join(this.m.or)}static grouped(e){const t=new Map;for(const s of e){const n=`${s.candidate}|${s.robustness}|${JSON.stringify(s.onlyIf??{})}`,r=t.get(n)??{...s,accounts:[]};s.eventId&&r.accounts.push(s.eventId),t.set(n,r)}const i={"robust-plausible":0,conditional:1,"robust-exclusion":2};return[...t.values()].sort((s,n)=>i[s.robustness]-i[n.robustness])}alert(e){return(e.robustness==="robust-exclusion"?this.m.alertExcluded:e.robustness==="robust-plausible"?this.m.alertPlausible:this.m.alertConditional).replace("{name}",e.label).replace("{where}",this.where(e.onlyIf))}scenario(e){return`${this.placeName(e.placeId)}, ${this.instant(e.local)}`}scenarioId(e){const[t,i]=e.split("@");return`${this.placeName(t)}, ${this.instant(i)}`}title(e,t){const i=t.placeId==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t.placeId));return this.m.scenarioTitle.replace("{title}",e).replace("{place}",i).replace("{date}",this.instant(t.local))}date(e){return new Date(`${e}T12:00Z`).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"})}instant(e){return new Date(`${e.slice(0,16)}Z`).toLocaleString(this.language,{day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC"})}}class su extends HTMLElement{static TAG="rr0-scenario-sweep";static CSS=`
|
|
4696
4696
|
:host { display: block; font-size: 13px; line-height: 1.4; margin-top: 14px; }
|
|
4697
4697
|
:host([hidden]) { display: none; }
|
|
4698
4698
|
summary { cursor: pointer; list-style-position: inside; font: 600 12px/1.4 var(--rr0-sans, system-ui, sans-serif); letter-spacing: .08em; text-transform: uppercase; opacity: .8; }
|
|
@@ -4731,7 +4731,7 @@ button.open { display: inline-flex; align-items: center; gap: 6px; cursor: point
|
|
|
4731
4731
|
.option input { margin: 2px 0 0; }
|
|
4732
4732
|
${tn.css(".menu")}
|
|
4733
4733
|
.menu:popover-open { position-area: bottom span-left; margin: .35em 0 0; }
|
|
4734
|
-
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(uh.TAG)||customElements.define(uh.TAG,uh)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=xs.preferencesFor(this),this.language=da([...this.preferences],Gr),this.messages=await K5.load(this.language),this.draw()}draw(){const e=this.messages,t=document.createElement("style");t.textContent=uh.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=uh.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"),tn.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",()=>tn.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([F(()=>import("./CaseReportExport-
|
|
4734
|
+
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(uh.TAG)||customElements.define(uh.TAG,uh)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=xs.preferencesFor(this),this.language=da([...this.preferences],Gr),this.messages=await K5.load(this.language),this.draw()}draw(){const e=this.messages,t=document.createElement("style");t.textContent=uh.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=uh.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"),tn.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",()=>tn.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([F(()=>import("./CaseReportExport-C7dPT0eH.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,tn.show(t,!1)}catch{this.status.textContent=i.failed}}}}const F8=$t.catalog({en:()=>F(()=>import("./ReadingCheckTexts_en-C5qzU8K7.js"),[],import.meta.url).then(l=>l.readingCheckTexts_en),fr:()=>F(()=>import("./ReadingCheckTexts_fr-COtovvqc.js"),[],import.meta.url).then(l=>l.readingCheckTexts_fr),es:()=>F(()=>import("./ReadingCheckTexts_es-DdhtmSew.js"),[],import.meta.url).then(l=>l.readingCheckTexts_es),it:()=>F(()=>import("./ReadingCheckTexts_it-Bz32XGh6.js"),[],import.meta.url).then(l=>l.readingCheckTexts_it)});class Sa{static given=new Map;static add(e,t){const i=decodeURIComponent(t.replace(/[?#].*$/,"").replace(/^.*\//,"")).replace(/\.json$/i,"")||"interview",s=e.name.replace(/[\\/:*?"<>|#%]+/g,"_").trim()||"file";let n=`${i}-files/${s}`;for(let r=2;Sa.given.has(new URL(encodeURI(n),t).href);r++)n=`${i}-files/${s.replace(/(\.[^.]*)?$/,`-${r}$1`)}`;return Sa.given.set(new URL(encodeURI(n),t).href,{blob:e}),{src:n,name:e.name,...e.type?{type:e.type}:{}}}static shown(e,t){const i=Sa.url(e,t),s=Sa.given.get(i);return s?(s.shown??=URL.createObjectURL(s.blob),s.shown):i}static fileName(e){return e.name??(decodeURIComponent(e.src.replace(/[?#].*$/,"").replace(/\/+$/,"").replace(/^.*\//,""))||e.src)}static isImage(e){return(e.type??"").startsWith("image/")||/\.(png|jpe?g|gif|webp|avif|svg)$/i.test(Sa.fileName(e))}static url(e,t){try{return new URL(/^[a-z][a-z0-9+.-]*:/i.test(e.src)?e.src:encodeURI(e.src),t??(typeof location>"u"?void 0:location.href)).href}catch{return e.src}}static blob(e){return Sa.given.get(e)?.blob}static clear(){for(const{shown:e}of Sa.given.values())e&&URL.revokeObjectURL(e);Sa.given.clear()}}class Zs{static withImages(e,t){const i=s=>s?.forEach(n=>{n.src=t(n.src)});for(const s of e.sections){i(s.images);for(const n of s.fields)i(n.images)}return e}static added=new Map;static ids(){return[...Zs.added.keys()]}static add(e){Zs.added.set(e.id,e)}static fetched=new Map;static async load(e){const t=Zs.added.get(e);if(t||!/[/:]|\.json$/i.test(e))return t;let i=Zs.fetched.get(e);return i||(i=fetch(e).then(s=>s.ok?s.json():void 0).then(s=>{if(!(!s||typeof s.id!="string"||!Array.isArray(s.sections)))return Zs.add(Zs.withImages(s,n=>new URL(n,e).href)),s}).catch(()=>{}),Zs.fetched.set(e,i)),i}static fields(e){return e.sections.flatMap(t=>t.fields)}static field(e,t){return Zs.fields(e).find(i=>i.id===t)}static text(e,t){if(e===void 0)return"";if(typeof e=="string")return e;const i=e;return(t&&i[t])??Object.values(i)[0]??""}static interview(e,t={},i){const s=t.witnesses?.length===1?t.witnesses[0]:void 0;return{version:1,...e.language?{language:e.language}:{},title:e.title,medium:"questionnaire",questionnaire:{id:e.id,...e.version?{version:e.version}:{},...i?{recipient:i}:{}},...s?{interviewOf:s.id}:{},speakers:{interviewer:{role:"interviewer",...t.by?.[0]!==void 0?{by:{people:t.by[0]}}:{}},witness:{role:"witness",...s?{title:s.label,of:s.id}:{}}},transcription:{method:"manual"},proofreading:{interviewer:{status:"pending"},witness:{status:"pending"}},segments:Zs.fields(e).map(n=>({speaker:"interviewer",field:n.id,text:Zs.text(n.question,e.language)}))}}static answerOf(e,t){return Zs.answerTurn(e,t)?.text}static filesOf(e,t){return Zs.answerTurn(e,t)?.files??[]}static answerTurn(e,t){return e.segments.find(i=>i.field===t&&e.speakers[i.speaker]?.role==="witness")}static fileName(e){return Sa.fileName(e)}static answerFiles(e,t,i,s){Zs.answer(e,t,i.map(n=>Zs.fileName(n)).join("; "),s,void 0,i)}static answer(e,t,i,s,n,r){const a=Object.entries(e.speakers).find(([,u])=>u.role==="witness")?.[0]??"witness";e.speakers[a]||(e.speakers[a]={role:"witness"});const o=e.segments.findIndex(u=>u.field===t&&e.speakers[u.speaker]?.role==="witness"),c=i.trim(),h=u=>{const{text:p,redacted:f,files:m,...g}=u;return n?{...g,redacted:n}:{...g,text:c,...r?.length?{files:r}:{}}};if(o>=0){c===""?e.segments.splice(o,1):e.segments[o]=h(e.segments[o]);return}if(c==="")return;let d=e.segments.findIndex(u=>u.field===t&&e.speakers[u.speaker]?.role!=="witness");if(d<0){const u=Object.entries(e.speakers).find(([,p])=>p.role==="interviewer")?.[0]??"interviewer";e.speakers[u]||(e.speakers[u]={role:"interviewer"}),e.segments.push({speaker:u,field:t,text:s??t}),d=e.segments.length-1}e.segments.splice(d+1,0,h({speaker:a,field:t}))}}const C2=Object.freeze(Object.defineProperty({__proto__:null,QuestionnaireTemplates:Zs},Symbol.toStringTag,{value:"Module"}));class gr{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===xi.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:xi.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new gr(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===xi.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:xi.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}addQuestionnaire(e,t,i,s){const n=this.addInterview(e,t,i.title,void 0,"questionnaire");n.url=`${n.id}.json`;const r=[n.interviewOf].flat().filter(o=>typeof o=="string"),a=Zs.interview(i,{witnesses:r.map(o=>({id:o,label:o}))},s);return delete a.speakers.witness.title,this.keepTranscript(n,`${JSON.stringify({...a,id:n.id,time:t},null,2)}
|
|
4735
4735
|
`),n}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&&gr.sealed(e.event)||(t=Tn.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===xi.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===xi.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=a=>typeof a=="string"?a:a&&typeof a=="object"?Object.values(a).find(o=>typeof o=="string"):void 0,s=t(e.recording?.observer?.id)||t(i(e.event.title))||t(i(e.recording?.observer?.title))||t(e.recording?.observer?.lastName),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===xi.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(!gr.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 xi.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(gr.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"||gr.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)+`
|
|
4736
4736
|
`})),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)+`
|
|
4737
4737
|
`},...n,...a]}attachments(){const e=this.url.replace(/[^/]*$/,""),t=new Map;for(const[i,s]of this.transcripts){if(i.url===void 0)continue;let n;try{n=JSON.parse(s.text)}catch{continue}const r=new URL(i.url,this.url).href;for(const a of(n.segments??[]).flatMap(o=>o.files??[])){const o=Sa.url(a,r),c=Sa.blob(o);c&&o.startsWith(e)&&t.set(decodeURIComponent(o.slice(e.length)),c)}}return[...t].map(([i,s])=>({path:i,blob:s}))}}class sm{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=`
|
|
@@ -5220,7 +5220,7 @@ ${e.ask}`,"Answer by calling draft_recording."),t.join(`
|
|
|
5220
5220
|
|
|
5221
5221
|
`)}static imageBlock(e){return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}}}async clientFor(e,t){if(!e)throw new qr("credential");const i=`${e}\0${t??""}`;if(this.client&&this.clientFor_===i)return this.client;const{default:s}=await F(async()=>{const{default:n}=await import("./index-DQDuRMiM.js").then(r=>r.i);return{default:n}},[],import.meta.url);return this.client=new s({apiKey:e,...t?{defaultHeaders:{"anthropic-workspace-id":t}}:{},dangerouslyAllowBrowser:!0,maxRetries:1}),this.clientFor_=i,this.client}static read(e){if(e.stop_reason==="refusal")throw new qr("refused");const t=e.content.find(s=>s.type==="tool_use"&&s.name===j2.name);if(!t||t.type!=="tool_use")throw new qr("malformed");const i=t.input;if(typeof i?.recording!="object"||i.recording===null||Array.isArray(i.recording))throw new qr("malformed");return{recording:i.recording,claims:Array.isArray(i.claims)?i.claims.flatMap(s=>{const{path:n,basis:r,rationale:a}=s??{};return typeof n!="string"||typeof a!="string"?[]:[{path:n,basis:r==="derived"||r==="assumed"?r:"stated",rationale:a}]}):[],gaps:Array.isArray(i.gaps)?i.gaps.filter(s=>typeof s=="string"):[]}}static async diagnose(e,t){if(e instanceof qr)return e;if(t?.aborted)return new qr("cancelled",e);const{default:i}=await F(async()=>{const{default:s}=await import("./index-DQDuRMiM.js").then(n=>n.i);return{default:s}},[],import.meta.url);return e instanceof i.AuthenticationError||e instanceof i.PermissionDeniedError?new qr("credential",e):e instanceof i.RateLimitError?new qr("rate-limited",e):e instanceof i.BadRequestError||e instanceof i.NotFoundError?new qr("rejected",e.message,e):e instanceof i.APIConnectionError?new qr("unreachable",e):new qr("malformed",e)}}const v0=Xe.point("narrative").provide(Xe.BUILT_IN,[{id:"claude",name:"Claude",credit:"Anthropic",creditUrl:"https://www.anthropic.com/legal/consumer-terms",create:()=>new cl}]),M9=Xe.point("assessment").provide(Xe.BUILT_IN,[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async l=>{const{CoverageAssessor:e}=await F(async()=>{const{CoverageAssessor:t}=await import("./CoverageAssessor-CcVuVsG0.js");return{CoverageAssessor:t}},[],import.meta.url);return new e().assess(l)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async l=>{const{HynekAssessor:e}=await F(async()=>{const{HynekAssessor:t}=await import("./HynekAssessor-B4ej1xgG.js");return{HynekAssessor:t}},__vite__mapDeps([41,42]),import.meta.url);return new e().assess(l)}})},{id:"ballester-guasp",name:"Ballester-Guasp",credit:"V.-J. Ballester-Olmos & M. Guasp",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Ballester-Guasp.html",create:()=>({about:"observer",assess:async l=>{const{BallesterGuaspAssessor:e}=await F(async()=>{const{BallesterGuaspAssessor:t}=await import("./BallesterGuaspAssessor-DEJId5n8.js");return{BallesterGuaspAssessor:t}},__vite__mapDeps([43,42,44]),import.meta.url);return new e().assess(l)}})},{id:"poher",name:"Poher",credit:"Claude Poher",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Poher-Criteres.html",create:()=>({about:"shape",assess:async l=>{const{PoherAssessor:e}=await F(async()=>{const{PoherAssessor:t}=await import("./PoherAssessor-yWlnEcoZ.js");return{PoherAssessor:t}},[],import.meta.url);return new e().assess(l)}})}]);class ZM{constructor(e){this.labels=e}async read(e){const t=[],i=new Set;for(const s of M9){let n;try{n=await s.create().assess(e)}catch{continue}for(const a of n.criteria)a.basis===void 0&&!a.unsupported&&i.add(a.id);const r=n.score===void 0?n.verdict===void 0?"":this.verdictName(s.id,n.verdict):`${Math.round(n.score*100)}%`;r!==""&&t.push({group:"assessment",field:s.id,label:this.labels.assessmentNames[s.id]??s.name,value:r,unit:"",fromSource:!1,about:s.create().about,...n.factors?{detail:ZM.factorsText(n.factors)}:{}})}return{entries:t,unanswered:i}}static factorsText(e){const t={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(e).map(([i,s])=>`${t[i]??i} ${s.toFixed(2)}`).join(" × ")}verdictName(e,t){return this.labels.assessmentVerdicts[`${e}.${t}`]??t.toUpperCase()}}class Za{constructor(e,t){this.labels=e,this.number=new Intl.NumberFormat(t,{minimumFractionDigits:2,maximumFractionDigits:2}),this.percent=new Intl.NumberFormat(t,{style:"percent",maximumFractionDigits:0})}static CANDIDATES_SECTION="candidates-section";static HVS_SECTION="hvs-section";static matrices=new Map;async poherOf(e,t){const[{PoherAnswers:i,PoherMatrix:s},{PoherAccountFacts:n},{WitnessError:r},{SightingFetch:a}]=await Promise.all([F(()=>Promise.resolve().then(()=>Z8),void 0,import.meta.url),F(()=>Promise.resolve().then(()=>J8),void 0,import.meta.url),F(()=>Promise.resolve().then(()=>N8),void 0,import.meta.url),F(()=>Promise.resolve().then(()=>k5),void 0,import.meta.url)]),o=s.chosenVersion(),c=`${o}/${t}`;let h=Za.matrices.get(c);h||(h=s.load(o,t,f=>a.json(f)),h.catch(()=>Za.matrices.delete(c)),Za.matrices.set(c,h));const{matrix:d,labels:u}=await h,p=new i(r.MODELS[0],e.account?.conditions).of(n.of(e)).filter(f=>d.has(f.question));return this.poher(d.rank(p),p.length,u,o)}number;percent;poher(e,t,i,s){if(e.length===0||t===0)return;const n=this.labels.hypotheses,r=e.filter(p=>p.excludedBy.length===0),a=e.filter(p=>p.excludedBy.length>0),o=p=>i[p.phenomenon]??p.phenomenon,c=r[0];let h=n.allExcluded,d;if(c){const p=r.filter(f=>Math.abs(f.mean-c.mean)<1e-9).length-1;h=p>0?n.tied.replace("{name}",o(c)).replace("{n}",String(p)):o(c),d=n.poherDetail.replace("{mean}",this.percent.format(c.mean)).replace("{possible}",String(r.length)).replace("{of}",String(e.length))}const u=[...r.length>0?[n.possible.replace("{n}",String(r.length)).replace("{of}",String(e.length)),...r.map(p=>`${o(p)} ${this.percent.format(p.mean)}`)]:[],...a.length>0?[...r.length>0?[""]:[],n.excluded.replace("{n}",String(a.length)),a.map(o).join(", ")]:[]].join(`
|
|
5222
5222
|
`);return this.entry(Za.CANDIDATES_SECTION,n.poher[s],h,d,e.length>1?u:void 0)}hvs(e,t){if(e.hypotheses.length===0)return;const i=this.labels.hypotheses,s=e.hypotheses.find(o=>o.dominant),n=s?[t(s.id),s.hvs?this.number.format(s.hvs.preferred):void 0].filter(Boolean).join(" "):i.noDominant,r=o=>o.hvs?.preferred??-1,a=[...e.hypotheses].sort((o,c)=>r(c)-r(o)).map(o=>{const c=this.number.format((o.csDiscriminating??o.csRaw).preferred),h=o.hvs&&o.ps?i.hvsLine.replace("{hvs}",this.number.format(o.hvs.preferred)).replace("{cs}",c).replace("{ps}",this.number.format(o.ps.preferred)):i.hvsLineNoPs.replace("{cs}",c),d=[o.admissible?i.admissible:i.notAdmissible,...o.dominant?[i.dominant]:[]].join(", ");return`${t(o.id)} — ${h} (${d})`}).join(`
|
|
5223
|
-
`);return this.entry(Za.HVS_SECTION,i.hvs,n,s?this.hvsDetail(s):void 0,e.hypotheses.length>1?a:void 0)}hvsDetail(e){const t=e.csDiscriminating??e.csRaw;if(!e.hvs||!e.ps)return;const i=s=>this.number.format(s.preferred);return this.labels.hypotheses.hvsDetail.replace("{hvs}",i(e.hvs)).replace("{cs}",i(t)).replace("{ps}",i(e.ps))}entry(e,t,i,s,n){return{group:"hypothesis",field:e,label:t,value:n?`${i}…`:i,unit:"",fromSource:!1,about:"observation",...s?{detail:s}:{},...n?{expandable:n}:{}}}static fold(e,t,i,s){const
|
|
5223
|
+
`);return this.entry(Za.HVS_SECTION,i.hvs,n,s?this.hvsDetail(s):void 0,e.hypotheses.length>1?a:void 0)}hvsDetail(e){const t=e.csDiscriminating??e.csRaw;if(!e.hvs||!e.ps)return;const i=s=>this.number.format(s.preferred);return this.labels.hypotheses.hvsDetail.replace("{hvs}",i(e.hvs)).replace("{cs}",i(t)).replace("{ps}",i(e.ps))}entry(e,t,i,s,n){return{group:"hypothesis",field:e,label:t,value:n?`${i}…`:i,unit:"",fromSource:!1,about:"observation",...s?{detail:s}:{},...n?{expandable:n}:{}}}static fold(e,t,i,s,n){const r=i.expandable;if(r===void 0)return;const a=n?document.createElement("button"):void 0;a&&n&&(a.type="button",a.className="chip-more",a.textContent=n.label,a.addEventListener("click",h=>{h.stopPropagation(),n.open()}),a.addEventListener("keydown",h=>h.stopPropagation()));const o=()=>{const h=s.has(i.field);e.toggleAttribute("data-expanded",h),e.setAttribute("aria-expanded",String(h)),t.textContent=h?r:i.value,a&&(h?e.append(a):a.remove())},c=h=>{h.stopPropagation(),s.delete(i.field)||s.add(i.field),o()};e.classList.add("expandable"),e.tagName!=="BUTTON"&&(e.tabIndex=0,e.setAttribute("role","button"),e.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),c(h))})),e.addEventListener("click",c),o()}static CSS=`
|
|
5224
5224
|
.param-chip.expandable, .param-label.expandable {
|
|
5225
5225
|
cursor: pointer;
|
|
5226
5226
|
}
|
|
@@ -5236,6 +5236,10 @@ ${e.ask}`,"Answer by calling draft_recording."),t.join(`
|
|
|
5236
5236
|
font-weight: normal;
|
|
5237
5237
|
margin-top: 0.2em;
|
|
5238
5238
|
}
|
|
5239
|
+
.param-chip .chip-more, .param-label .chip-more {
|
|
5240
|
+
display: block; margin-top: 0.35em; padding: 0; border: 0; background: none; color: inherit; font: inherit;
|
|
5241
|
+
text-decoration: underline; text-underline-offset: 2px; cursor: pointer;
|
|
5242
|
+
}
|
|
5239
5243
|
`}class So{static stated(e){return So.statedIn(e,[])}static apply(e,t,i){const s=structuredClone(e);for(const n of i){const r=n.split("."),a=So.read(t,r);a!==void 0&&So.write(s,r,structuredClone(a))}return s}static statedIn(e,t){const i=[];for(const[s,n]of Object.entries(e)){if(n===void 0)continue;const r=[...t,s];So.isPlainObject(n)?i.push(...So.statedIn(n,r)):i.push(r.join("."))}return i}static isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static read(e,t){let i=e;for(const s of t){if(!So.isPlainObject(i))return;i=i[s]}return i}static write(e,t,i){let s=e;for(const n of t.slice(0,-1)){const r=s[n];So.isPlainObject(r)||(s[n]={}),s=s[n]}s[t[t.length-1]]=i}}const x9={x:Ut.CANVAS_WIDTH_PX/2,y:Ut.CANVAS_HEIGHT_PX/2,width:1,height:1};class ev{static loadable(e){const t=e.decor?{decor:e.decor.map((s,n)=>ev.decor(s,n))}:{},i=e.timeline?.keyframes;return i?{...e,...t,timeline:{...e.timeline,keyframes:i.map(s=>({t:s.t??0,shapes:(s.shapes??[]).map(n=>({sourceId:n.sourceId,shape:ev.shape(n.shape)}))}))}}:{...e,...t}}static decor(e,t){const i=e.kind??"vehicle";return{...Wv(i)?{windows:zI(i)}:{},...i==="building"?{floors:Ku}:{},...e,id:e.id??`decor-${t+1}`,kind:i,eastM:e.eastM??0,northM:e.northM??0}}static shape(e){const t=e?.kind==="polygon"?"polygon":"oval";return{...t==="polygon"?{points:[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}]}:{},...e,kind:t,bounds:{...x9},color:typeof e?.color=="string"?e.color:"#e8e6df",angle:0,transparency:0,haloScale:0,selected:!1}}}class n_{static sync(e,t,i,s,n){if(e.querySelector(".param-description")?.remove(),t===void 0){e.removeAttribute("data-describing");return}const r=document.createElement("div");r.className="param-description";const a=document.createElement("div");a.className="param-description-head";const o=document.createElement("span");o.className="param-nest-label",o.textContent=i;const c=document.createElement("button");c.type="button",c.className="param-description-close",c.textContent="×",c.title=s,c.setAttribute("aria-label",s),c.addEventListener("click",n),a.append(o,c);const h=document.createElement("p");h.className="param-description-text",h.textContent=t,r.append(a,h),r.addEventListener("keydown",d=>{d.key==="Escape"&&n()}),e.setAttribute("data-describing",""),e.append(r),c.focus({preventScroll:!0})}static CSS=`
|
|
5240
5244
|
.param-summary[data-describing] > :not(.param-description) {
|
|
5241
5245
|
display: none;
|
|
@@ -9119,9 +9123,9 @@ canvas[data-cursor="rotate"] {
|
|
|
9119
9123
|
`;class Uh{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 Uh(t)}static TRAVEL_M=50;get travels(){return this.spanM>Uh.TRAVEL_M}get moved(){return this.spanM>Uh.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(ot(t,e.east,t,e.west).x),Math.abs(ot(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:xr(0,-n,i,s).lat,south:xr(0,n,i,s).lat,east:xr(n,0,i,s).lng,west:xr(-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 ya{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,t=0){const i=e.instrumentAt(t);if(i.mounted)return;const s=e.event.tags?.includes("paralysis")||(e.exposureAt(t)??0)>ya.HAND_HELD_S,n=e.sway??(s?0:1);if(n>0)return new ya(Math.max(1-(i.stabilization??0),ya.GAZE_DRIFT_SHARE),n)}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]=ya.HZ;return{eastM:i*ya.SWAY_M*(.7*s(n,.3)+.3*s(o,1.9)),northM:i*ya.SWAY_M*(.6*s(a,2.2)+.4*s(c,.8)),upM:i*ya.BREATH_M*s(r,0),yawDeg:i*this.rotationPassed*ya.DRIFT_YAW_DEG*(.6*s(h,1.1)+.4*s(o,2.7)),pitchDeg:i*this.rotationPassed*ya.DRIFT_PITCH_DEG*(.5*s(r,1.6)+.5*s(a,.4)),rollDeg:i*this.rotationPassed*ya.DRIFT_ROLL_DEG*s(n,2.9)}}}class Di{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,t=0){const i=Uh.of(e);if(!i||i.points.length<2)return;const s=[];let n=0;for(let r=1;r<i.points.length;r++){const a=i.points[r-1],o=i.points[r],c=(o.t-a.t)/1e3;if(c<=0)continue;const h=ot(o.lat,o.lng,a.lat,a.lng),d=h.x,u=-h.z,p=Math.hypot(d,u),f=p/c,m=Di.stepHzFor(f);s.push({startMs:a.t,endMs:o.t,speedMPerS:f,eastUnit:p>0?d/p:0,northUnit:p>0?u/p:0,stepHz:m,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=m*c}for(let r=0;r<s.length;r++){const a=s[r-1],o=s[r+1];s[r].rampsIn=a===void 0||a.stepHz===0,s[r].rampsOut=o===void 0||o.stepHz===0}if(s.some(r=>r.stepHz>0))return new Di(s,1-(e.instrumentAt(t).stabilization??0))}static bodyAt(e,t,i=!1){const s=Di.of(e,t)?.offsetAt(t)??Di.STILL;return i?s:Di.add(s,ya.of(e,t)?.offsetAt(t))}static stepHzFor(e){return e<Di.SLOWEST_WALK_M_PER_S||e>Di.FASTEST_WALK_M_PER_S?0:Di.REFERENCE_STEP_HZ*Math.pow(e/Di.REFERENCE_SPEED_M_PER_S,Di.CADENCE_EXPONENT)}offsetAt(e){return Di.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/Di.REFERENCE_SPEED_M_PER_S,s=(a,o,c,h)=>{if(a<0||a>Di.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/Di.JOLT_DECAY_S)*Math.sin(2*Math.PI*Di.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,Di.STOP_LURCH_M,Di.STOP_PITCH_DEG,1):void 0;if(n)return n;const r=t.rampsIn?s(e-t.startMs,Di.START_LURCH_M,Di.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 Di.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,s=2*Math.PI*i,n=this.amplitudeAt(t,e),r=Di.SWAY_M*n*Math.cos(s/2),a=n*this.rotationPassed*t.speedMPerS/Di.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:Di.RISE_M_PER_M_PER_S*t.speedMPerS*n*Math.cos(s),rollDeg:Di.HEAD_ROLL_DEG*a*Math.cos(s/2),pitchDeg:-1.25*a*Math.cos(s),yawDeg:Di.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 I9{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 ua{static sessionDeclared=!1;static isLive(e){return e!==void 0&&typeof AudioContext<"u"&&e instanceof AudioContext}static unlock(e){if(ua.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(!(ua.sessionDeclared||typeof navigator>"u")){ua.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const Z2=.05,J2=.08,Q2=2,eA=3,_9=14,k9=.02;class tA{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}}ua.isLive(this.context)&&ua.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(),ua.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,Z2);for(const{param:n,ratio:r}of e.pitch)n.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),s,Z2)}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*Q2),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*Q2),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*eA),e.sampleRate),i=t.getChannelData(0),s=Math.max(1,Math.floor(k9*e.sampleRate)),n=Math.round(eA*_9);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,J2/3);const s=i+J2;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 rm{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=rm.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=>` ${rm.text(s)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
9120
9124
|
${i.join(`
|
|
9121
9125
|
`)}`)}}class wa{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,s){if(!wa.isObject(e)){s.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:wa.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(wa.isStated(e)){this.range(e.range,`${i}.range`,s),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):wa.isObject(e)||s.push({kind:"wrong-type",path:i,expected:"object",found:wa.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((n,r)=>{const a=wa.isStated(n)?n.value:n;this.object(a,t.fields,`${i}.${r}`,s)}):s.push({kind:"wrong-type",path:i,expected:"array",found:wa.typeOf(e)});return;default:typeof e!==t.type?s.push({kind:"wrong-type",path:i,expected:t.type,found:wa.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)})}}range(e,t,i){if(e===void 0||typeof e=="string")return;const s=n=>n===null||typeof n=="number"&&Number.isFinite(n);!Array.isArray(e)||e.length!==2||!e.every(s)||e[0]===null&&e[1]===null?i.push({kind:"wrong-type",path:t,expected:"[least, greatest], null for an open side, or an EDTF interval",found:JSON.stringify(e)}):e[0]!==null&&e[1]!==null&&e[0]>e[1]&&i.push({kind:"out-of-range",path:t,expected:"least ≤ greatest",found:JSON.stringify(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 wa.isObject(e)&&"value"in e&&Object.keys(e).every(t=>wa.STATED_KEYS.has(t))}static typeOf(e){return Array.isArray(e)?"array":e===null?"null":typeof e}}class qn{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?qn.travelDegOver(e,t,i,i+s*1e3)/n/qn.PIXELS_PER_INSTANT:0,a=qn.flashesOver(e,s)*qn.INSTANTS_PER_FLASH,o=Math.ceil(Math.max(r,a));return o<2?1:Math.min(qn.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=qn.directionAt(r,t,i),o=qn.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=la(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=qn.bodyAt(o,i),h=qn.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/qn.PIXELS_PER_INSTANT);return a<2?1:Math.min(qn.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 r_=Math.PI/180,D9=180/Math.PI,R9=256,a_=19,C9=1.25;function o_(l,e){return 156543.03392*Math.cos(l*r_)/2**e}function c_(l,e){return o_(l,e)*R9}function O9(l,e){let t=0;for(;t<a_&&c_(l,t+1)>=e;)t++;return t}function JM(l,e){return c_(l,e)}function l_(l,e){const t=e*C9;let i=0;for(;i<a_&&o_(l,i)>t;)i++;return i}function ug(l){const e=l*r_;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function h_(l,e,t){const i=2**t;return{x:(l+180)/360*i,y:ug(e)*i}}function d_(l,e,t){const i=ug(l.north),s=ug(l.south);return{x:(e-l.west)/(l.east-l.west),y:(ug(t)-i)/(s-i)}}function L9(l,e,t){const{x:i,y:s}=h_(l,e,t);return{x:Math.floor(i),y:Math.floor(s),z:t}}function P9(l){const e=2**l.z,t=l.x/e*360-180,i=(l.x+1)/e*360-180,s=iA(l.y,e);return{south:iA(l.y+1,e),north:s,west:t,east:i}}function iA(l,e){const t=l/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*D9}function u_(l,e,t,i){const s=L9(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(P9),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 N9="#2ec4ff";class fh{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=d_(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??N9;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:fh.MARKER_RADIUS_PX}),t.beginPath(),t.arc(s.x,s.y,fh.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=ot(r.lat,r.lng,t.lat,t.lng);return Math.hypot(a.x,a.z)<=fh.ON_MARKER_M});i.beginPath(),i.arc(s.x,s.y,n?fh.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(ot(r,e.east,r,e.west).x)/this.width,c=fh.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 Mi{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 Mi.including(e.boundsAround(Mi.MIN_SPAN_M,Mi.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(Mi.MAX_ZOOM,Math.max(Mi.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=Mi.mercatorY01(t.north),n=Mi.mercatorY01(t.south),r=Mi.mercatorY01(i.north),a=Mi.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=Mi.mercatorY01(s.north),r=Mi.mercatorY01(s.south),a=(t.lng-s.west)/(s.east-s.west),o=(Mi.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=Mi.mercatorY01(e.north),s=Mi.mercatorY01(e.south),n=e.east-e.west;return{west:e.west+(this.centerX-t)*n,east:e.west+(this.centerX+t)*n,north:Mi.latitudeAt(i+(this.centerY-t)*(s-i)),south:Mi.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=ot(s,e.east,s,n).x;let a=r;for(const o of t){const{x:c,z:h}=ot(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:xr(0,-a,s,n).lat,south:xr(0,a,s,n).lat,east:xr(a,0,s,n).lng,west:xr(-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=Mi.mercatorY01(e.north),n=Mi.mercatorY01(e.south);return{lat:Mi.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 va=256,F9=3,U9=129,B9=7,z9=32768;class p_{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(ot(i,e.east,i,e.west).x),r=Math.abs(ot(e.north,s,e.south,s).z),a=Math.max(n,r);let o=O9(i,a),c=F9;if(t.width>=U9){const m=v=>2*Math.ceil((a/JM(i,v)+1)/2)+1;let g=l_(i,a/(t.width-1)/2);for(;g>o&&m(g)>B9;)g--;g>o&&(o=g,c=m(g))}const{tiles:h}=u_(s,i,o,c),d=c*va,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=va,o.height=va;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,va,va),d=(e.x-t.x)*va,u=(e.y-t.y)*va;for(let p=0;p<va;p++)for(let f=0;f<va;f++){const m=(p*va+f)*4,g=h[m]*256+h[m+1]+h[m+2]/256-z9,v=d+f,b=u+p;i[b*s+v]=g}}sampleAt(e,t,i,s,n,r){const{x:a,y:o}=h_(t,e,i),c=(a-s.x)*va,h=(o-s.y)*va,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 Xv{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 Xv(o,c,h,u?new Float32Array(m.buffer):m)}}class H9{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 Ce{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)*Ce.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180),north:(s-t.lat)*Ce.METRES_PER_DEGREE}}static path(e,t){return e.geometry.type!=="LineString"?[]:e.geometry.coordinates.map(i=>Ce.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:Ce.path(o,t),properties:o.properties})),r=(e.elevatedRailways??[]).map(o=>Ce.path(o,t)),a=[];for(const o of Ce.joined(e.bridges.map(c=>Ce.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<Ce.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||Ce.carriesRailway(c,h,r))continue;const[p,f]=Ce.deckReach(c,h,s);a.push({eastM:Ce.tenth((p.east+f.east)/2),northM:Ce.tenth((p.north+f.north)/2),lengthM:Ce.tenth(Math.hypot(f.east-p.east,f.north-p.north)),widthM:Ce.roadOf(u,n).width,heightM:Ce.tenth(Ce.deckHeight(c,h,s)),headingDeg:Ce.tenth(Ce.bearing(c,h)%180),...Ce.roadOf(u,n).name?{name:Ce.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=Ce.bearing(e,t)%180;for(const r of i)for(let a=0;a+1<r.length;a++){if(Ce.distanceToSegment(s,r[a],r[a+1])>Ce.RAIL_MATCH_M)continue;const o=Math.abs(Ce.bearing(r[a],r[a+1])%180-n);if(Math.min(o,180-o)<=Ce.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=Ce.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)>Ce.JOIN_M)continue;const a=Math.abs(Ce.bearing(i[0],n)-Ce.bearing(r,s[s.length-1]));if(Math.min(a,360-a)<=Ce.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=Ce.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>Ce.ROAD_MATCH_M)return{width:Ce.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?Ce.tenth(n+Ce.DECK_MARGIN_M):i.properties.nature==="Sentier"?Ce.FOOTBRIDGE_DECK_M:Ce.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)>=Ce.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+Ce.DECK_REACH_M;m+=Ce.DECK_STEP_M)if(a(u*m))p=m;else if(p!==void 0&&m-p>Ce.DECK_GAP_M)break;if(p===void 0)return s/2;let f=p;for(;f-p<Ce.DECK_REACH_M&&o(u*(f+Ce.DECK_STEP_M))>=Ce.DECK_MEETS_M;)f+=Ce.DECK_STEP_M;return Math.max(s/2,f+Ce.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 Ce.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?Ce.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=Ce.kilovolts(a);if(o===void 0)continue;const c=Ce.BY_VOLTAGE.find(d=>o<=d.upToKv)??Ce.BY_VOLTAGE[Ce.BY_VOLTAGE.length-1],h=Ce.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>Ce.MAX_SPAN_M||Ce.distanceToSegment({east:0,north:0},u,p)>i)continue;const m=Ce.poleHeight(u,p,s)??c.poleM;n.push({eastM:Ce.tenth((u.east+p.east)/2),northM:Ce.tenth((u.north+p.north)/2),lengthM:Ce.tenth(f),headingDeg:Ce.tenth(Ce.bearing(u,p)),heightM:Ce.tenth(Math.max(4,m-c.dropM)),poleHeightM:Ce.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,Ce.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>=Ce.MIN_POLE_M&&n<=Ce.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 ei{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??ei.WMS,this.wfs=e.wfsEndpoint??ei.WFS}static radius(e){return Math.min(e,ei.MAX_RADIUS_M)}static lidarRadius(e){return Math.min(e,ei.MAX_LIDAR_RADIUS_M)}async lidar(e,t){const i=ei.lidarRadius(t),s=Math.ceil(2*i/ei.METRES_PER_PIXEL),[n,r]=await Promise.all([this.raster(e,i,s,ei.HEIGHT_LAYER),this.raster(e,i,s,ei.CLASS_LAYER)]);if(n.samples!==1||r.samples<3)throw new za("unreachable","The survey answered in a layout this does not read");const a=n.values;if(a.every(d=>d===ei.NO_DATA))throw new za("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 H9(a,o,c,s,h)}}async laserDate(e){return ei.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",e))}async photoDate(e){return ei.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=ei.radius(t),s=Math.min(ei.MAX_PHOTO_PIXELS,Math.ceil(2*i/ei.METRES_PER_PIXEL)),n=await this.raster(e,i,s,ei.PHOTO_LAYER);if(n.samples<3)throw new za("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=ei.radius(t),n=s/ei.METRES_PER_DEGREE,r=s/(ei.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,ei.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:ei.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=ei.MAX_WHOLE_M/ei.METRES_PER_DEGREE;let c;for(const d of e){if(d.properties.categorie!=="Religieux")continue;const[u,p,f,m]=ei.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')`,ei.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/ei.METRES_PER_DEGREE,r=t/(ei.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 za("unreachable",c instanceof Error?c.message:String(c))}if(!o.ok)throw new za("unreachable",`The survey answered ${o.status}`);try{return Xv.parse(await o.arrayBuffer())}catch(c){throw new za("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 za("unreachable",o instanceof Error?o.message:String(o))}if(!r.ok)throw new za("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class ll{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=>ot(a.lat,a.lng,i.lat,i.lng)),n=e.map(a=>ot(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/ll.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=ll.nearest(s,o.x+(c.x-o.x)*f,o.z+(c.z-o.z)*f);m.distanceM>ll.NEAR_M||ll.angleBetween(u,m.heading)<=ll.ALIGNED_DEG&&(r+=h/d)}}return r>=ll.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 Gt{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??Gt.WMS,this.timeoutMs=e.timeoutMs??Gt.DEFAULT_TIMEOUT_MS,this.maxWindowM=e.maxWindowM??Gt.MAX_WINDOW_M,this.geoplatform=new ei({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(!ei.covers(s.lat,s.lng))throw new Error("The IGN's relief covers France only");const n=Math.abs(ot(s.lat,e.east,s.lat,e.west).x),r=Math.abs(ot(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/Gt.METRES_PER_DEGREE,north:e.north+o.y/Gt.METRES_PER_DEGREE,west:e.west-o.x/(Gt.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180)),east:e.east+o.x/(Gt.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180))},h=m=>Math.min(Gt.MAX_PIXELS,Math.max(Gt.MIN_PIXELS,Math.ceil(m/Gt.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)>Gt.COARSE_METRES_PER_PIXEL;for(const m of f?[...Gt.LAYERS].reverse():Gt.LAYERS)try{const g=await this.heights(c,d,m);m===Gt.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<Gt.MESH_FROM_VERTICES||e.height<Gt.MESH_FROM_VERTICES)return e;const s=(n,r)=>{const a=Math.ceil(n/Gt.FINE_SPACING_M),o=Math.max(r-1,Math.min(Gt.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 Xv.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>Gt.NO_DATA_BELOW)))try{const n=(await this.geoplatform.elevatedRoadLines({west:t.west,south:t.south,east:t.east,north:t.north})).filter(a=>ll.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,Gt.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,Gt.DECK)&&(c[g]=1,h=!0);if(!h)return;const d=Gt.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,Gt.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,Gt.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>Gt.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)*Gt.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),c=(i.north-i.south)*Gt.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>Gt.NO_DATA_BELOW?M:void 0},f=Gt.DECK_HALF_WIDTH_M,m=Gt.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 Gt.chains(s.map(b=>b.map(u)))){const b=[0];for(let _=1;_<v.length;_++)b.push(b[_-1]+Math.hypot(v[_].x-v[_-1].x,v[_].y-v[_-1].y));const w=b[b.length-1];if(w<1||w>Gt.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(_=>_.x))-x)/h)),E=Math.min(n-1,Math.ceil((Math.max(...v.map(_=>_.x))+x)/h)),A=Math.max(0,Math.floor((Math.min(...v.map(_=>_.y))-x)/d)),T=Math.min(r-1,Math.ceil((Math.max(...v.map(_=>_.y))+x)/d));for(let _=A;_<=T;_++)for(let D=S;D<=E;D++){const O=Gt.nearestAlong(v,b,{x:(D+.5)*h,y:(_+.5)*d});if(O.distance>f||O.s<-m||O.s>w+m)continue;const L=y+(M-y)*Math.min(1,Math.max(0,O.s/w)),R=_*n+D;t[R]>=L||(e.values[R]=L)}}}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)>Gt.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<Gt.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<Gt.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 G9{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 pg=256,V9=5;async function f_(l,e,t,i){const s=(l.south+l.north)/2,n=(l.west+l.east)/2,r=Math.abs(ot(s,l.east,s,l.west).x),a=Math.abs(ot(l.north,n,l.south,n).z),o=Math.max(r,a),{zoom:c,gridSize:h}=W9(s,o,Math.max(e.width,e.height)),{tiles:d,bounds:u}=u_(n,s,c,h),p=h*pg,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)*pg,(y.y-g.y)*pg)}));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 W9(l,e,t){let i=l_(l,e/Math.max(1,t)),s=sA(l,i,e);for(;s>V9&&i>0;)i--,s=sA(l,i,e);return{zoom:i,gridSize:s,mPerPixel:JM(l,i)/pg}}function sA(l,e,t){const i=Math.ceil(t/2/JM(l,e));return Math.max(3,2*i+1)}class m_{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 f_(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Ur{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=Ur.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=Ur.FRANCE;return o>=h.south&&o<=h.north&&c>=h.west&&c<=h.east?[Ur.FRANCE_ENDPOINT,...t.filter(u=>u!==Ur.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=Ur.queue.then(e,e);return Ur.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints??Ur.endpointsFor(e))for(let s=0;s<2;s++){try{const n=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(Ur.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,Ur.RETRY_MS))}throw t??new Error("No Overpass instance answered")}}class hl{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 Ur(e)}async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${hl.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:hl.surfaceOf(n),widthM:hl.widthOf(n),...hl.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:hl.WIDTH_M[e.highway]??hl.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 cy="https://ufoathome.org/roads/index.json";class nu{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??nu.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(`
|
|
9122
|
-
`);let t=nu.shared.get(e);return t||(t=this.fetchFirstAvailable(),nu.shared.set(e,t),t.then(i=>{i.length===0&&nu.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.204.
|
|
9123
|
-
`);let t=ru.shared.get(e);return t||(t=this.fetchFirstAvailable(),ru.shared.set(e,t),t.then(i=>{i.length===0&&ru.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.204.1")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==ly?[t,ly]:[ly]).map(i=>i+e)}}class _r{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=_r.key(e);let i=_r.asked.get(t);return i===void 0&&(i=this.recalled(t,e),_r.asked.set(t,i),i.catch(()=>_r.asked.delete(t))),structuredClone(await i)}static forget(){_r.asked.clear()}static key(e){return`v${_r.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await _r.openCache(),s=_r.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<_r.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&_r.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-_r.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(_r.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class yl{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 ei(e)}static covers(e){return ei.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>yl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=yl.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=yl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=yl.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]>yl.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 Pn{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 Ur(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"~"^(${Pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Pn.ROUTES})$"];out body;`;return Pn.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=Pn.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(v=>ot(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 Pn.samples(a)){d++;const b=Pn.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=Pn.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=Pn.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=Pn.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=>ot(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=Pn.SAMPLE_M/2;a<s;a+=Pn.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(Pn.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<=Pn.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 au{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 Ur(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${au.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Pn.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=Pn.voltageOf(r),c=au.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=au.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:au.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 X9{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(!yl.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 Xs{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=Xs.key(e);let i=Xs.asked.get(t)??Xs.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Xs.asked.set(t,i),s.catch(()=>Xs.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Xs.asked.clear(),Xs.failedAt=-1/0}static key(e){return`v${Xs.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Xs.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 Xs.openCache(),s=Xs.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<Xs.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-Xs.failedAt<Xs.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(Xs.failedAt=this.now(),n)return n;throw a}return i&&Xs.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-Xs.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Xs.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const hy="https://ufoathome.org/railways/index.json";class ou{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??ou.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(`
|
|
9124
|
-
`);let t=ou.shared.get(e);return t||(t=this.fetchFirstAvailable(),ou.shared.set(e,t),t.then(i=>{i.length===0&&ou.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.204.1")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==hy?[t,hy]:[hy]).map(i=>i+e)}}function g_(){return{elevation:v_(),imagery:b_(),roads:y_(),water:w_(),railways:M_()}}function v_(){return new G9(new Gt,new p_)}function b_(){return new m_}function y_(){return new nu({fallback:new $9(new bl,new hl)})}function w_(){return new ru({fallback:new _r(new K9(new am,new mh))})}function M_(){return new ou({fallback:new Xs(new X9(new yl,new au))})}const Y9=new Set,Iu="show-observer-map",_u="hide-milestones",Ah="minified";class Jt extends HTMLElement{static get observedAttributes(){return["src",Iu,_u,Ah]}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 Mi;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=Fv.create();issues=[];issueCheck=0;sightingAudio=new tA;liveSightingAudio;hearInto(e){e?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new tA(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>Jt.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");Jt.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 F(async()=>{const{VideoButton:n}=await import("./VideoButton-CzJg9lBG.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?u0(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.namesHeldValue?void 0: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)<Jt.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>=Mi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Mi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Jt.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=Mi.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>${T9}</style>${A9}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new qu(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 fh(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===Iu&&this.applyObserverMapDefault(),e===_u&&this.setMilestonesShown(!this.hasAttribute(_u)),e===Ah){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Ah)}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(x_)))};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 aa.recording(e)}get sightingData(){return im(this.currentSighting)}set sightingData(e){const t=Tn.recording(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=wm(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 F(async()=>{const{default:r}=await import("./sightingSchema-DoPVOlCB.js");return{default:r}},[],import.meta.url);s=new wa(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],rm.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(j9,{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=rm.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=W.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)<Jt.TIME_SAID_EVERY_MS||(this.timeSaid=e,this.dispatchEvent(new CustomEvent(q9,{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"),Jt.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)),Jt.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?Nh(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=Jt.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=Jt.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?u0(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 qu(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=Jt.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?u0(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=qn.windowEndingAt(e,this.currentSighting.exposureAt(e)??0);if(t.ms<Jt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Jt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Jt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Jt.EXPOSURE_STEP_PX),n=Math.min(Jt.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)return;const s=this.exposureTimes(),n=this.currentSighting.timeline;for(const o of s){const c=n.hitTest(o,e,t,i);if(c)return c}const r=this.canvas.getBoundingClientRect().width;if(r===0)return;const a=Jt.SHAPE_REACH_CSS_PX*this.canvas.width/r;for(const o of s){const c=n.hitNear(o,e,t,a,i);if(c)return c}}static SHAPE_REACH_CSS_PX=8;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(e=this.currentTime){const t=zt.frameWidthPx(this.currentSighting.instrumentAt(e),this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${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.currentSighting.changesInstrument&&this.applyFrameFormat(e),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:Y9;this.canvasRenderer.setStarPoints(zt.starPointsOf(this.sighting.instrumentAt(e),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?li.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(MM(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 I9(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*Jt.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){Jt.icons.get(e)!==t&&(Jt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set namesHeld(e){this.namesHeldValue=e,e&&(this.tooltip.hidden=!0)}namesHeldValue=!1;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},Jt.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(),Jt.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(Iu),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;Jt.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=Uh.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=Mi.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?Mi.expand(e,Jt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=Mi.IMAGERY_PX*(t?1+2*Jt.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:b_();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?Mi.expand(e,Jt.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=Jt.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},Jt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrumentAt(e),s=[],n=this.currentSighting.milestones.length>0?u0(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?Nh(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?ra.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(zt.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,Nh(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??"",Jt.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=la(i,e),{lat:n,lng:r}=xr(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=ra.of(this.currentSighting.instrumentAt(this.currentTime),this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return Di.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=Jt.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)),Jt.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){Jt.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}Jt.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;Jt.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 ws(xs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=da(xs.preferencesFor(this),Gr);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await R5.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=qh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?A1(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 Zc(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?rA(nA(this.realStartMs+i)):Zc(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Zc(e):Zc(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Zc(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Zc(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Zc(this.currentSighting.timeline.duration):this.canShowClockTime?rA(nA(this.realStartMs+this.realDurationMs)):Zc(this.realDurationMs)}}function nA(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function rA(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 Zc(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Aw="rr0-ufo";function Yv(){customElements.get(Aw)||customElements.define(Aw,Jt)}const q9="timechange",j9="recordingissues",x_="minifiedreset";class Jp{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+Jp.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Jp.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Jp.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 cu{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=ot(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-cu.HALF_SPAN_MS),o=r(t+cu.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*cu.HALF_SPAN_MS/1e3;if(h/d<cu.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 Z9=.08,aA=.15,oA=2,J9=2e3;class cA{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}}ua.isLive(this.context)&&ua.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);ua.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<J9),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()*oA*.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,Z9),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,aA/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},aA*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*oA,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 om{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 om.BY_KIND[e??"generic"]??om.BY_KIND.generic}}class Nn{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 Nn.ROAD_KINDS.includes(e)}static roadOf(e){return e&&Nn.isRoad(e.kind)?e.kind:void 0}static aircraftOf(e){return e&&!Nn.isRoad(e.kind)?e.kind:void 0}static transmission(e){const t=Nn.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?Nn.WINDOWS_OPEN_DB:Nn.isRoad(e.kind)?Nn.ROAD_CLOSED_DB:Nn.CANOPIED.includes(e.kind)?Nn.CANOPY_DB:Nn.FUSELAGE_DB:Nn.OPEN_AIR}}class Th{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=Th.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<Th.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 Th(a,i)}at(e){const t=(e-this.startMs)/Th.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 tv{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=ot(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=Nn.roadOf(a);if(a&&o){const h=om.of(o),d=this.drive(`observer:${o}`,tv.trackKey(e),()=>Th.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=om.of(h.engine.kind),u=g=>{const v=la(h,g);return{eastM:v.eastM,northM:v.northM}},p=this.drive(`decor:${h.id}`,tv.decorKey(h,r),()=>Th.of(d,u,0,r));if(!p)continue;const f=la(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 Q9="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==",e7=`
|
|
9126
|
+
`);let t=nu.shared.get(e);return t||(t=this.fetchFirstAvailable(),nu.shared.set(e,t),t.then(i=>{i.length===0&&nu.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.204.2")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==cy?[t,cy]:[cy]).map(i=>i+e)}}class bl{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 ei(e)}static covers(e){return ei.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,s)=>bl.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=bl.BY_NATURE[s]??bl.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),o=Number(e.properties.vitesse_moyenne_vl),c=bl.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=bl.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 $9{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(bl.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}class am{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(e={}){this.platform=new ei(e)}static covers(e){return ei.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getWater(e){return(await this.platform.waterSurfaces(e)).flatMap((i,s)=>am.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=>am.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 mh{attribution="Water © OpenStreetMap contributors";client;constructor(e={}){this.client=new Ur(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 mh.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=mh.rings(a("inner"));for(const[c,h]of mh.rings(a("outer")).entries()){const d=o.filter(u=>mh.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 mh.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 K9{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(e){if(am.covers(e))try{const t=await this.regional.getWater(e);if(t.length>0)return t}catch{}return this.worldwide.getWater(e)}}const ly="https://ufoathome.org/water/index.json";class ru{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??ru.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(`
|
|
9127
|
+
`);let t=ru.shared.get(e);return t||(t=this.fetchFirstAvailable(),ru.shared.set(e,t),t.then(i=>{i.length===0&&ru.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.204.2")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==ly?[t,ly]:[ly]).map(i=>i+e)}}class _r{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=_r.key(e);let i=_r.asked.get(t);return i===void 0&&(i=this.recalled(t,e),_r.asked.set(t,i),i.catch(()=>_r.asked.delete(t))),structuredClone(await i)}static forget(){_r.asked.clear()}static key(e){return`v${_r.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await _r.openCache(),s=_r.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<_r.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&_r.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-_r.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(_r.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class yl{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 ei(e)}static covers(e){return ei.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>yl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=yl.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=yl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=yl.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]>yl.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 Pn{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 Ur(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"~"^(${Pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Pn.ROUTES})$"];out body;`;return Pn.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=Pn.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(v=>ot(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 Pn.samples(a)){d++;const b=Pn.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=Pn.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=Pn.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=Pn.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=>ot(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=Pn.SAMPLE_M/2;a<s;a+=Pn.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(Pn.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<=Pn.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 au{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 Ur(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${au.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=Pn.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=Pn.voltageOf(r),c=au.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=au.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:au.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 X9{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(!yl.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 Xs{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=Xs.key(e);let i=Xs.asked.get(t)??Xs.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Xs.asked.set(t,i),s.catch(()=>Xs.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Xs.asked.clear(),Xs.failedAt=-1/0}static key(e){return`v${Xs.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Xs.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 Xs.openCache(),s=Xs.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<Xs.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-Xs.failedAt<Xs.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(Xs.failedAt=this.now(),n)return n;throw a}return i&&Xs.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-Xs.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Xs.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const hy="https://ufoathome.org/railways/index.json";class ou{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??ou.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(`
|
|
9128
|
+
`);let t=ou.shared.get(e);return t||(t=this.fetchFirstAvailable(),ou.shared.set(e,t),t.then(i=>{i.length===0&&ou.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.204.2")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==hy?[t,hy]:[hy]).map(i=>i+e)}}function g_(){return{elevation:v_(),imagery:b_(),roads:y_(),water:w_(),railways:M_()}}function v_(){return new G9(new Gt,new p_)}function b_(){return new m_}function y_(){return new nu({fallback:new $9(new bl,new hl)})}function w_(){return new ru({fallback:new _r(new K9(new am,new mh))})}function M_(){return new ou({fallback:new Xs(new X9(new yl,new au))})}const Y9=new Set,Iu="show-observer-map",_u="hide-milestones",Ah="minified";class Jt extends HTMLElement{static get observedAttributes(){return["src",Iu,_u,Ah]}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 Mi;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=Fv.create();issues=[];issueCheck=0;sightingAudio=new tA;liveSightingAudio;hearInto(e){e?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new tA(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>Jt.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");Jt.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 F(async()=>{const{VideoButton:n}=await import("./VideoButton-CzJg9lBG.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?u0(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.namesHeldValue?void 0: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)<Jt.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>=Mi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Mi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Jt.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=Mi.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>${T9}</style>${A9}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new qu(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 fh(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===Iu&&this.applyObserverMapDefault(),e===_u&&this.setMilestonesShown(!this.hasAttribute(_u)),e===Ah){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Ah)}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(x_)))};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 aa.recording(e)}get sightingData(){return im(this.currentSighting)}set sightingData(e){const t=Tn.recording(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=wm(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 F(async()=>{const{default:r}=await import("./sightingSchema-DoPVOlCB.js");return{default:r}},[],import.meta.url);s=new wa(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],rm.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(j9,{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=rm.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=W.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)<Jt.TIME_SAID_EVERY_MS||(this.timeSaid=e,this.dispatchEvent(new CustomEvent(q9,{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"),Jt.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)),Jt.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?Nh(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=Jt.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=Jt.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?u0(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 qu(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=Jt.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?u0(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=qn.windowEndingAt(e,this.currentSighting.exposureAt(e)??0);if(t.ms<Jt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Jt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Jt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Jt.EXPOSURE_STEP_PX),n=Math.min(Jt.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)return;const s=this.exposureTimes(),n=this.currentSighting.timeline;for(const o of s){const c=n.hitTest(o,e,t,i);if(c)return c}const r=this.canvas.getBoundingClientRect().width;if(r===0)return;const a=Jt.SHAPE_REACH_CSS_PX*this.canvas.width/r;for(const o of s){const c=n.hitNear(o,e,t,a,i);if(c)return c}}static SHAPE_REACH_CSS_PX=8;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(e=this.currentTime){const t=zt.frameWidthPx(this.currentSighting.instrumentAt(e),this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${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.currentSighting.changesInstrument&&this.applyFrameFormat(e),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:Y9;this.canvasRenderer.setStarPoints(zt.starPointsOf(this.sighting.instrumentAt(e),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?li.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(MM(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 I9(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*Jt.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){Jt.icons.get(e)!==t&&(Jt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set namesHeld(e){this.namesHeldValue=e,e&&(this.tooltip.hidden=!0)}namesHeldValue=!1;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},Jt.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(),Jt.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(Iu),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;Jt.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=Uh.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=Mi.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?Mi.expand(e,Jt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=Mi.IMAGERY_PX*(t?1+2*Jt.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:b_();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?Mi.expand(e,Jt.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=Jt.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},Jt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrumentAt(e),s=[],n=this.currentSighting.milestones.length>0?u0(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?Nh(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?ra.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(zt.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,Nh(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??"",Jt.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=la(i,e),{lat:n,lng:r}=xr(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=ra.of(this.currentSighting.instrumentAt(this.currentTime),this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return Di.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=Jt.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)),Jt.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){Jt.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}Jt.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;Jt.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 ws(xs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=da(xs.preferencesFor(this),Gr);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await R5.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=qh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?A1(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 Zc(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?rA(nA(this.realStartMs+i)):Zc(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Zc(e):Zc(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Zc(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Zc(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Zc(this.currentSighting.timeline.duration):this.canShowClockTime?rA(nA(this.realStartMs+this.realDurationMs)):Zc(this.realDurationMs)}}function nA(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function rA(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 Zc(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Aw="rr0-ufo";function Yv(){customElements.get(Aw)||customElements.define(Aw,Jt)}const q9="timechange",j9="recordingissues",x_="minifiedreset";class Jp{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+Jp.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Jp.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Jp.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 cu{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=ot(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-cu.HALF_SPAN_MS),o=r(t+cu.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*cu.HALF_SPAN_MS/1e3;if(h/d<cu.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 Z9=.08,aA=.15,oA=2,J9=2e3;class cA{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}}ua.isLive(this.context)&&ua.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);ua.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<J9),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()*oA*.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,Z9),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,aA/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},aA*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*oA,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 om{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 om.BY_KIND[e??"generic"]??om.BY_KIND.generic}}class Nn{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 Nn.ROAD_KINDS.includes(e)}static roadOf(e){return e&&Nn.isRoad(e.kind)?e.kind:void 0}static aircraftOf(e){return e&&!Nn.isRoad(e.kind)?e.kind:void 0}static transmission(e){const t=Nn.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?Nn.WINDOWS_OPEN_DB:Nn.isRoad(e.kind)?Nn.ROAD_CLOSED_DB:Nn.CANOPIED.includes(e.kind)?Nn.CANOPY_DB:Nn.FUSELAGE_DB:Nn.OPEN_AIR}}class Th{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=Th.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<Th.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 Th(a,i)}at(e){const t=(e-this.startMs)/Th.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 tv{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=ot(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=Nn.roadOf(a);if(a&&o){const h=om.of(o),d=this.drive(`observer:${o}`,tv.trackKey(e),()=>Th.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=om.of(h.engine.kind),u=g=>{const v=la(h,g);return{eastM:v.eastM,northM:v.northM}},p=this.drive(`decor:${h.id}`,tv.decorKey(h,r),()=>Th.of(d,u,0,r));if(!p)continue;const f=la(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 Q9="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==",e7=`
|
|
9125
9129
|
<div class="stage" id="stage">
|
|
9126
9130
|
<div class="frame" id="frame">
|
|
9127
9131
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -11845,7 +11849,7 @@ ${c.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
11845
11849
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
11846
11850
|
}
|
|
11847
11851
|
`,transparent:!0,depthWrite:!1,side:hn,fog:!1,blending:jh,blendSrc:Zh,blendDst:Wf})}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=ir.DISC_INDEX[e],s=ir.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 Pe.respond(t*Pe.relativeOfResponse(Math.max(e,1e-5)))}}class Dr{static SIZE=64;static MOVE_M=.01;holder=new as;cameras=[];faces=[];target=new pi(Dr.SIZE,Dr.SIZE);white=new Er({color:new ce(1,1,1),side:hn});scene=new pa;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 Un(90,1,.02,20);s.up.copy(i),s.lookAt(t),this.holder.add(s),this.cameras.push(s),this.faces.push(new Uint8Array(Dr.SIZE*Dr.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)<Dr.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(Dr.SIZE-1,Math.floor((n+1)/2*Dr.SIZE)),o=Math.min(Dr.SIZE-1,Math.floor((r+1)/2*Dr.SIZE));return this.faces[t][(o*Dr.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 ir))return;const c=new ge(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),hv.now(e,this.target,0,0,Dr.SIZE,Dr.SIZE,this.faces[r])}e.setRenderTarget(s),e.shadowMap.autoUpdate=n;for(const r of i)r.removeFromParent()}}const wy="https://ufoathome.org/models/index.json";class cf{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??CF()}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(`
|
|
11848
|
-
`);let t=cf.shared.get(e);return t||(t=this.fetchFirstAvailable(),cf.shared.set(e,t),t.then(i=>{i.length===0&&cf.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 CF(){const l=`?v=${encodeURIComponent("0.204.
|
|
11852
|
+
`);let t=cf.shared.get(e);return t||(t=this.fetchFirstAvailable(),cf.shared.set(e,t),t.then(i=>{i.length===0&&cf.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 CF(){const l=`?v=${encodeURIComponent("0.204.2")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==wy?[e,wy]:[wy]).map(t=>t+l)}const Fw=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 cf}]);class lf{constructor(e,t=Fw){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 My(l){const{GLTFLoader:e}=await F(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BIk0ozTu.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 ia{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new ge(new lr(2,2),new Ft({uniforms:{uColor:{value:new ce(0,0,0)},uRadius:{value:1}},vertexShader:ia.VERTEX,fragmentShader:ia.FRAGMENT,transparent:!0,depthWrite:!1,blending:fn,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*ia.MIN_ANGLE_RAD),r=ia.FILL*Math.PI*n*n;return{radiusM:n,luminanceCdM2:i*Math.min(ia.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(ia.MAX_SHARE*ia.FILL*Math.PI))}static VERTEX=`
|
|
11849
11853
|
uniform float uRadius;
|
|
11850
11854
|
varying vec2 vOffset;
|
|
11851
11855
|
void main() {
|
|
@@ -12567,7 +12571,7 @@ ${Yt.rules([],[".model-picker .model-picker-address p"])}
|
|
|
12567
12571
|
.model-picker .model-name { font-weight: 600; }
|
|
12568
12572
|
.model-picker .model-credit { font-size: .8em; color: #666; }
|
|
12569
12573
|
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await F(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-dnCeD6UT.js");return{ModelThumbnails:i}},__vite__mapDeps([53,54]),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=>gf.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=gf.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=W.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),F(async()=>{const{ModelViewer:S}=await import("./ModelViewer-BNGSukqO.js");return{ModelViewer:S}},__vite__mapDeps([55,54]),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 R=document.createElement("span");R.className="model-credit",R.textContent=S.title,E.append(R)}g(S.value).then(R=>gf.pictureOf(R)).then(R=>{if(!R)return;const N=new Image;N.src=R,N.alt="",A.append(N)});let _,D=!1;const O=()=>{D&&!(_&&!_.active)||(D=!0,Promise.all([g(S.value),F(()=>import("./ModelViewer-BNGSukqO.js"),__vite__mapDeps([55,54]),import.meta.url)]).then(([R,{ModelViewer:N}])=>{!R||!D||(_=N.show(A,R))}).catch(()=>{}))},L=()=>{D=!1,_?.stop(),_=void 0};return w.set(E,O),E.addEventListener("pointerenter",O),E.addEventListener("focus",O),E.addEventListener("pointerleave",()=>{document.activeElement!==E&&L()}),E.addEventListener("blur",L),E.addEventListener("click",R=>{if(_?.consumeDrag()){R.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 bx{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=bx.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 qz{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 vr{static STEP_MS=100;static plan(e){const t=vr.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}=ot(p,f,u.lat,u.lng);return Math.hypot(g,v)<Qe.rebuildDistanceFor(m)};for(let u=0;;u=Math.min(s,u+vr.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=nm.map(u=>ha.of(u)).filter(u=>u.reachM&&ha.eventsOf(e.skyEvents,u).length>0);if(d.length>0){const u=p=>Math.max(...d.map(f=>f.reachM(ha.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=vr.routeOf(t),c=[];for(const[u,p]of i.entries()){try{const f=await s.elevation.getElevationGrid(Sr.boundsOf(p),{width:Cw,height:Cw},{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 lm.encode({takenOn:r,attribution:h,patches:c}),attribution:h,takenOn:r,answered:c.length,patches:i.length}}case"imagery":{const o=new IT,c=Ji(Vh,s.imagery),h=c.create(o.fetch);let d=0;for(const[f,m]of i.entries()){try{await h.getImageryTexture(Sr.boundsOf(m),{width:nf,height:nf}),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 gv.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 vr.vector(s.roads,i,r,a,(o,c)=>o.getRoads(c),o=>o.contemporary);case"water":return vr.vector(s.water,i,r,a,(o,c)=>o.getWater(c));case"railways":return vr.vector(s.railways,i,r,a,(o,c)=>o.getRailways(c),o=>o.contemporary)}}static mapGround(e){const t=Uh.of(e);return t&&Mi.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=vr.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new IT,r=Ji(Vh,t),a=r.create(n.fetch),o=Mi.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 gv.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,Sr.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 vs{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:vs.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&vs.isInline(t.src)}annex(e){const t=this.host.sighting().snapshots?.[e];return t?.src!==void 0?t:void 0}isLive(e){return ms.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 ms.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&&vs.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&&!vs.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 F(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-tIOJTG_y.js");return{SightingFileEditor:r}},__vite__mapDeps([56,25,57]),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 vs.describe(e,n)}}catch{Yt.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){Yt.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}Pt.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}Yt.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await F(async()=>{const{InputFileElement:s}=await Promise.resolve().then(()=>n5);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 vs.describe(e,t)}catch{Yt.show(this.note,this.messages.annexUnreadable,"warning");return}const a=n!==void 0&&vs.isInline(n.src),o=a?vs.dataUrl(e,t):n?.src??ms.annexName(this.host.base(),e);a||Pt.hold(this.address(o),t),s[e]={...s[e]?.live?{live:!0}:{},src:o,...r},Yt.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||vs.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=vs.dataUrl(e,n):(r=ms.annexName(this.host.base(),e),Pt.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=vs.isInline(t.src)?ms.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:vs.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(vs.isZip(e)){const{unzipSync:s}=await F(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 Pt.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:${vs.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&&!vs.isInline(i)?vs.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,vr.plan(this.host.sighting()),this.host.sources(),s))?Yt.show(this.note,void 0):Yt.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 ms.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||vr.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=>ms.isLive(i,d),r=d=>i[d]?.src!==void 0?i[d]:void 0;for(const d of ms.NAMES)!i.live&&i[d]?.live&&(i[d]={live:!0});const a=vr.plan(t);let o;for(const d of ms.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");vr.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},vs.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 vr.freeze(e,this.host.sighting(),i,s,(o,c)=>Yt.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(o)).replaceAll("{of}",String(c))));return Yt.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){Yt.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await vr.freezeMap(this.host.sighting(),t.imagery);return Yt.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=vr.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await Pt.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&Sr.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 Pt.zip(s))["index.json"])).patches:(await Pt.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(a=>a.radiusM<=Qe.ROADS_MAX_RADIUS_M);return Sr.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&&vs.isInline(t))return vs.dataUrl(e,s);const n=t??ms.annexName(i,e);return Pt.hold(this.address(n),s),n}async keep(e,t){if(!vs.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{Yt.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return Pt.bytes(this.address(e.src))}address(e){return Pt.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of ms.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=ms.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 Sv{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,Yt.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[si.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 ws(xs.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:si.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=im(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:Tn.CURRENT.sighting,takenOn:i,attribution:s,...si.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)??si.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},Yt.show(this.note,void 0),this.write(e,o);return}let i;try{const{InputFileElement:o}=await F(async()=>{const{InputFileElement:h}=await Promise.resolve().then(()=>n5);return{InputFileElement:h}},void 0,import.meta.url),c=await o.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=Tn.recording(JSON.parse(new TextDecoder().decode(c))),typeof i!="object"||i===null||si.KEYS[e].every(h=>i[h]===void 0))throw new Error("Not this section")}catch{Yt.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...im(s)};if(e==="decor")si.put(e,n,"timeline"in i?si.taken(e,i):i);else for(const o of si.KEYS[e])n[o]=i[o];const r=wm(n);Sv.copy(e,r,s);const a={...s.snapshots??{}};t.url?a[e]={...a[e]??{},src:t.url}:a[e]=a[e]??{},Yt.show(this.note,void 0),this.write(e,a)}write(e,t){this.host.sighting().snapshots=ms.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 si.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 jz{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 Zz=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 jz}]),Jz=["appearance","movement","incongruity","detection","close","beings","traces"];class i1{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 Is{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=Is.select("observerOccupationKind");graduate=Is.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=Is.select("observersRelation");activity=Is.select("observerActivity");factors=new Map(Jz.map(e=>[e,Is.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){ns.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]);Is.choices(this.occupationKind,"",c(Object.keys(i1.OCCUPATIONS))),Is.choices(this.graduate,"",o),Is.choices(this.relation,"",c(i1.RELATIONS)),Is.choices(this.activity,"",c(i1.ACTIVITIES));for(const h of this.factors.values())Is.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,Is.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),Is.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),Is.choices(this.relation,e.unknown,Object.entries(e.relations)),Is.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)Is.choices(i,Is.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=Is.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=Is.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=Is.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:Is.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);ns.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 Q0=new Set;Yv();t5();vu.register();const Wd={width:48,height:28},Qz=2500,eg=40,tg=10,eH=30,tH=10,JT=600,QT=900,$d=2e-4,iH=900,sH=-1.46,nH=3,s1=.2,rH=.5,aH=3,oH=.01,cH=1.6,n1=2e3,lH=250,e3=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),hH=1,dH=5,uH=10,el=4,Up="ufo-1",pH={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function fH(l){return l.kind==="oval"?"oval":"polygon"}const mH=-6,gH=21;class me extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=Zz[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new qz;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;sectionIndexResize;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=Wz();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(Gz());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;poseInstrumentSelect;labelPoseInstrument;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 me.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?Hr.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?.[0]!=null?String(n[0]):"",r.max=n?.[1]!=null?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]??-1/0),o[1]??1/0);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 lf;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=$t.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...pH};currentSourceId=Up;selectedSourceIds=new Set([Up]);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(e3.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;e3.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>${S9}</style>${E9}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const h of this.shadow.querySelectorAll(Yg))h.build();for(const h of this.shadow.querySelectorAll(xv))h.build();for(const h of this.shadow.querySelectorAll(dm))h.build();for(const h of this.shadow.querySelectorAll(jg))h.build();this.sceneElement=document.createElement(hm),this.sceneElement.addEventListener("observermapchange",h=>{this.ufoElement.sighting.observerMap=h.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",h=>{const{lat:d,lng:u}=h.detail;this.latInput.value=String(Number(d.toFixed(6))),this.lngInput.value=String(Number(u.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 Jp(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const h of[this.timeStartLabel,this.timeEndLabel])h.addEventListener("click",()=>this.switchTimeDisplay()),h.addEventListener("keydown",d=>{d.key!=="Enter"&&d.key!==" "||(d.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(xv),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 Kt(this.shadow);const t=this.shadow.getElementById("section-index");this.sectionFolds.indexIn(t,()=>this.groupPanels?.find(h=>!h.hidden)),this.sectionIndexResize=new io(this.shadow.getElementById("section-index-resize"),this.shadow.querySelector(".app"),()=>t,"rr0-section-index-width","--rr0-section-index-width",44);const i=this;this.witnessErrorView=new JI({get sighting(){return i.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:h=>{const d=this.ufoElement.sighting,{conditions:u,...p}=d.account??{},f={...p,...h?{conditions:h}:{}};d.account=Object.values(f).some(m=>m!==void 0)?f:void 0},recordingJson:()=>this.sightingData,valueSources:()=>this.valueSources(),lawsChanged:()=>{this.sceneElement.confrontationTolerance=Qt.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new Mm(this.shadow.getElementById("timeline-tracks"),h=>this.goToMark(h),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",h=>{h.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new t_(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",h=>{const d=h.target.id;me.SCENE_LINKED.includes(d)&&this.setActiveSceneField(d)}),this.shadow.addEventListener("focusout",h=>{const d=h.relatedTarget;(!d||!me.SCENE_LINKED.includes(d.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 Is(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.poseInstrumentSelect=this.shadow.getElementById("poseInstrument"),this.labelPoseInstrument=this.shadow.getElementById("label-pose-instrument"),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(`${jg}[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(me.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 vs(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:(h,d)=>this.download(h,d)}),this.sectionFilePanel=new Sv(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(h,d)=>this.download(h,d),changed:h=>{if(this.touch(),this.ufoElement.refresh(),h==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),h==="place"&&this.syncPlaceNameField(),h==="lightPollution"){const d=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=d===void 0?"":String(d),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const s={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:h=>this.goToMark(h),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const h=this.ufoElement.sighting.timeline;return h.sourceIds.includes(this.currentSourceId)?h.topOf(this.currentSourceId):void 0},shapesLabel:h=>this.shapesLabel(h),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:h=>this.naming.point(h),lookedAt:()=>{const h=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return h?.headingDeg===void 0||h.pitchDeg===void 0?void 0:{azimuthDeg:h.headingDeg,altitudeDeg:h.pitchDeg}},bodyLabel:h=>{const d=this.ufoElement.sighting.interpretation?.bodies.find(u=>u.id===h);return this.said.read(d?.title)??h},valueSources:()=>this.valueSources()};this.eventsPanel=new Ho(this.shadow.getElementById("events-section"),s,void 0),this.phenomenonEventsPanel=new Ho(this.shadow.getElementById("phenomenon-events-section"),s,void 0,"phenomenon"),this.bodiesEventsPanel=new Ho(this.shadow.getElementById("bodies-events-section"),s,void 0,"bodies"),this.aroundPanel=new r9(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 h=Number(this.samplingRateInput.value);s.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(h)&&h>0?h:void 0,ft.refresh(this.ufoElement.sighting),s.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",h=>{h.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 uz(this.shadow.getElementById("aircraft-flights"),h=>this.aimAtFlight(h),h=>this.naming.point(h)),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 Fn({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:h=>`option-decor-${h}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:h=>this.selectDecor(h),onAdd:h=>this.addDecor(h),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 Fn({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:h=>this.selectObserver(h),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 Rn(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:h=>this.setPlantedDecor(h),kindName:h=>this.decorList.kindLabel(h),cite:h=>this.citeSource(h),busy:(h,d)=>this.sceneElement.setBusy(h,d),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(h=>({lat:h.pose.lat,lng:h.pose.lng})).filter(h=>typeof h.lat=="number"&&typeof h.lng=="number")},this.messages,async(h,d)=>this.surroundingsProvider?this.surroundingsProvider.covers(h,d)?this.surroundingsProvider:void 0:(await F(async()=>{const{SurroundingsSources:u}=await import("./surroundingsSources-CqL7lcmF.js");return{SurroundingsSources:u}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,h,d),{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 h=this.scenerySource.value===me.FILE_SOURCE;if(this.setDecorFromFile(h),h){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===me.NO_SCENERY){this.surroundings.withdraw();return}const d=this.plantingCentre();d&&this.surroundings.survey(d.lat,d.lng)}),this.sceneryRadius.addEventListener("input",()=>{const h=Number(this.sceneryRadius.value);if(!Number.isFinite(h)||h<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const d=this.plantingCentre();this.surroundings.radiusChanged(h,d?.lat,d?.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 sm(this.addReferenceButton,"reference-add-kind",h=>this.addReferenceOfKind(h),h=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[h]??`reference-add-${h}`),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 gf(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 qa(this.decorParametersHost,"en","decorParam.");const n={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new qa(this.decorBaseHost,"en","decorBase.",n,(h,d)=>this.enhanceDecorModelChoice(h,d)),this.decorStateForm=new qa(this.decorStateHost,"en","decorState.",n),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",h=>{this.focus({preventScroll:!0}),this.onPointerDown(h)}),this.ufoElement.canvasElement.addEventListener("pointermove",h=>this.onPointerMove(h));let r;this.ufoElement.canvasElement.addEventListener("pointerdown",h=>{r={x:h.clientX,y:h.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",h=>{const d=r;r=void 0,!(!d?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(h.clientX-d.x,h.clientY-d.y)>me.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",h=>this.onContextMenu(h)),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 a=this.shadow.getElementById("editor-mute"),o=this.shadow.getElementById("editor-volume");a.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.toggleMuted()}),o.addEventListener("input",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.volume=Number(o.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",h=>{const d=h.detail;d.file?this.importFromFile(d.file):this.importFromUrl(d.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 h of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])h.addEventListener(h instanceof HTMLSelectElement||h.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 h=this.ufoElement.sighting;h.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),h.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),h.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",h=>{const{seconds:d,text:u}=h.detail;this.ufoElement.sighting.event.durationText=u,this.ufoElement.durationSeconds=d,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((d??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 h of this.referenceFields)h.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",h=>void this.setReferenceSource(h.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 h=this.shadow.getElementById("trace-import-row");h.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",h=>void this.addTraces(h.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",h=>this.onReferenceWheel(h),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",h=>this.onBodyWheel(h),{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 h of[this.milestoneLabelInput,this.milestoneNoteInput])h.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(mx,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(fx,()=>{const h=this.currentReference();h&&this.syncReferenceStatus(h)}),this.sceneElement.addEventListener(px,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(ux,()=>{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 sm(this.addShapeButton,"add-shape-kind",h=>{const d=gc.byId(h);if(d){this.addModel(d);return}this.currentAppearance={...this.currentAppearance,presetId:h},this.addShape()},h=>`add-shape-${h}`),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 h of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])h.addEventListener("input",()=>this.updateObserver());for(const h of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])h.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",h=>{if(this.observerSaid=h.detail.said,!this.observerPosition.relative)return;const d=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(d,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",h=>this.writeObserverBasis(h.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",h=>{h.key==="Enter"&&(h.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.poseInstrumentSelect.addEventListener("change",()=>{this.updateObserver(),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument()}),this.instrumentSelect.addEventListener("change",()=>{const h=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const d=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(u=>[u.t,Bi.fovOf(this.ufoElement.sighting,u.t)]));this.retuneFieldOfView(h),this.retuneExposure(h),Bi.reproject(this.ufoElement.sighting,h,d),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 c=h=>this.shadow.querySelector(`${Yg}[name="${h}"]`);this.startDate=c("obs-time"),this.endDate=c("obs-end-time"),this.birthDate=c("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=Ja.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const h of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(h,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",h=>{const{time:d}=h.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=d}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",h=>{this.birth=h.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",h=>{const{time:d}=h.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=d})});for(const h of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])h.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(me.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const h of this.weatherFields){if(h===this.iceCrystalAlignmentInput||h===this.rareIceCrystalsInput){h.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}h.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const h of this.soundFields)h.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(h=>this.shadow.getElementById(h.getAttribute("aria-controls")));for(const h of this.groupTabs)h.addEventListener("click",()=>this.toggleGroup(h,!this.isGroupOpen(h)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const h of this.subgroupTabs)h.addEventListener("click",()=>this.openSubgroup(h)),me.pictureTab(h);this.buildSkyParts(),an.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",h=>this.onParamSummaryClick(h)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(h=>h.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=j8(this.shadow.getElementById("cloud-editor"),this.sceneElement,(h=!0)=>{h&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(h,d)=>{this.headingInput.value=String(this.rounded(h)),this.pitchInput.value=String(this.rounded(d)),this.updateObserver()},da(xs.preferencesFor(this),Gr),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),xs.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),F(async()=>{const{ModuleSession:t}=await import("./ModuleSession-DOhPD2XZ.js").then(i=>i.b);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=Ja.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=Tn.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]??Up,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:()=>`${$h.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=Zt.issues(this.ufoElement.sighting);if(Yt.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=ps.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=ps.namesOf(this.sightingData);this.observerLastNameInput.value=ps.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>ps.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=ps.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=ps.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=ps.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 si.NAMES){const a=this.sectionFilePanel.annex(r);a&&(/^[a-z][a-z0-9+.-]*:/i.test(a.src)||t.set(a.src,a.bytes),si.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 F(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}",vs.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"),...si.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...ms.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,me.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=ms.NAMES.includes(e),i=si.NAMES.includes(e)?e:void 0,s=e===me.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||Fn.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)?Sv.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 lf)||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||ZT.names(n,o,s)||(n=[...n??[],ZT.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??=F(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-DTnJICg0.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([58,59]),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 si.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=Ji(K0,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:Ji(Vh,this.chosenSourceId.get("imagery")).id,roads:y_(),water:w_(),railways:M_()}}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)}));Pt.release();const i=await this.recordingText(t),s=JSON.parse(i);if(xi.isCase(s)){if(xi.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 F(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)&&Pt.hold(Pt.address(d.slice(a.length),void 0),u);const o=i(s[r]),c=JSON.parse(o);let h=!1;for(const d of si.NAMES){const u=c.snapshots?.[d]?.src,p=u!==void 0?s[a+u]:void 0;if(!p)continue;const f=Tn.recording(JSON.parse(i(p)));si.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 aa.recording(e);if(xi.isCase(t)){xi.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;Pt.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=ys.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(){Yt.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof vf)return e.said(this.messages.formatVersionError);if(!(e instanceof il))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=v0[0].create();get narrativeSourceId(){return Ji(v0,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:me.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof qr&&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=So.stated(r);if(a.length>0){const o=this.ufoElement.sighting.provenance,c=Kg(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=So.apply(c,ev.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:me.valueAt(Kg(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[vH[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=Ji(v0,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 qr))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(){me.pageCredentials.clear(),Dc.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!==""?me.pageCredentials.set(t,i):me.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(me.NARRATIVE_KEY_STORAGE),localStorage.removeItem(me.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 me.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} `),me.creditLink(Ji(t1,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",Yz,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),me.creditLink(Ji(q0,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",v0,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",t1,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",q0,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",K0,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",Vh,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[me.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[me.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[me.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",Fw,()=>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,me.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()?me.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=Ji(t,r.value);Dc.set(g.id,u.value),i(g,!0)});const f=()=>{const g=r.value===me.FILE_SOURCE,v=Ji(t,g?o():r.value);d.hidden=g||!v.keyUrl,p.href=v.keyUrl??"",u.value=Dc.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===me.FILE_SOURCE;g||this.chosenSourceId.set(e,r.value),s?.setFromFile(g),f(),g||i(Ji(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?me.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===me.FILE_SOURCE&&s?g:o(),f(),v&&r.value!==me.FILE_SOURCE&&i(Ji(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),c,h,d),n}aircraftPicker(){const e=this.sourcePicker("aircraft",Jw,(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?Yt.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):Yt.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=ms.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=me.LIVE_ROADS;static LIVE_RAILWAYS=me.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} `),me.creditLink(Ji(t1,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),me.creditLink(Ji(q0,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:Ji(K0,this.chosenSourceId.get("elevation")).create(),imagery:Ji(Vh,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(Ji(Jw,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new lf(Ji(Fw,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)<$d&&Math.abs(i-this.namedCoordinates.lng)<$d||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),QT))}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)<$d&&Math.abs(i-s.lng)<$d||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),QT))}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.instrumentId,f=this.poseInstrumentSelect.value===""||this.poseInstrumentSelect.value===p?void 0:this.poseInstrumentSelect.value,m=f===void 0?this.ufoElement.sighting.instrument:zt.byId(f),g=this.numberOrUndefined(this.focalLengthInput.value),v=(m.frame&&g!==void 0?zt.fieldOfViewDegAt(m,g):g)??this.currentFovDeg(),b=this.numberOrUndefined(this.fNumberInput.value),w=this.filterSelect.value,y=ss.byId(o.getLatestPoseAt(c-1)?.filter),M=w===ss.NONE.id||w===""?y===ss.NONE?void 0:ss.NONE.id:w;if(f===void 0){const D=this.statedExposureSeconds(m);this.ufoElement.sighting.exposureSeconds=D===m.exposureSeconds?void 0:D}const x=this.numberOrUndefined(this.focusDistanceInput.value),S=Math.abs(v-zt.fieldOfViewDeg(m))>.01||b!==m.fNumber||x!==void 0||M!==void 0||f!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&u===0&&!S?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:v,fNumber:b,focusDistanceM:x,filter:M,...f===void 0?{}:{instrument:f}});const A=this.stringOrUndefined(this.placeNameInput.value.trim()),T=o.getInterpolatedPoseAt(0);a.place=e!==void 0&&t!==void 0?[{lat:T?.lat??e,lng:T?.lng??t,name:A}]:void 0;const _=this.plantingCentre();this.surroundings.placeChanged(_?.lat,_?.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&&!Y0.isFirm(t))return;const s=Y0.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&&Y0.at(i,e)===t)return;const s=Y0.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&&qh({...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=Zt.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,Zt.renamed(e,s,Zt.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:Ja.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={...Cs(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={...Cs(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;Fn.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"||fs.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=fs.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=fs.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(Yt.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>Iz?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)||j0))},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?fs.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(fs.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:Tz,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:j0},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=fs.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??=F(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-D8fDZm4v.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:fs.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)||j0,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);Fn.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(fs.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 F(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:j0}})}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;Fn.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 F(async()=>{const{TraceImport:d}=await import("./TraceImport-uGVIjCrc.js");return{TraceImport:d}},[],import.meta.url);i=await h.fromBytes(await vx.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 F(async()=>{const{GEO_EXPORT_TEXTS:a}=await import("./GeoExportTexts-Cp95Dg-h.js");return{GEO_EXPORT_TEXTS:a}},[],import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:a}=await F(async()=>{const{KmlExport:c}=await import("./KmlExport-DIxM5Hpx.js");return{KmlExport:c}},__vite__mapDeps([60,61]),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 F(async()=>{const{GeoJsonExport:a}=await import("./GeoJsonExport-CdadOwd2.js");return{GeoJsonExport:a}},__vite__mapDeps([62,61]),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 AR){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(),Qz)}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=MM(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===me.FILE_SOURCE;if(!e){const t=Ji(go,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(si.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=ms.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=go.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==Ji(go,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new Fp(e.create())}else!e&&t!==void 0&&!go.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new Fp(Ji(go,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...go.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,me.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!J0(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?me.FILE_SOURCE:i?i.id:Ji(go,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=Ji(go,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&&!J0(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),JT))}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||!J0(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&&J0(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&&en(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=!si.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=q0[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(),JT)}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=qh(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=LR(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(),W.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)>nH;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),iH))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<$d&&Math.abs(e.lng-i)<$d}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=Ji(K0,this.chosenSourceId.get("elevation")),n=await new bx(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(me.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=Cs(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??_g)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??G3)),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=jE(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!==me.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 F(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-tIOJTG_y.js");return{SightingFileEditor:t}},__vite__mapDeps([56,25,57]),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"){Yt.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of si.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&si.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of si.NAMES){const n=si.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||si.put(s,e,si.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return O2.of(e,t,t==="thin"?Bi.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(me.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(me.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=wm(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=O2.of(this.ownJson(im(e)),t,t==="thin"?Bi.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(me.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()):go.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 vf?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+=me.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+=me.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=Bi.fovOf(i,s),d=2*ra.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=d=>{let u=-1;return d.forEach((p,f)=>{p<=i()&&(u=f)}),u===-1&&d.length>0?0:u};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const d=n(t().observerTrack.allKeyframes.map(u=>u.t));return d===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${d}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const d=t().timeline.allKeyframes,u=n(d.filter(g=>g.shapes.some(v=>v.sourceId===this.currentSourceId)).map(g=>g.t));if(u===-1||this.apparentWidthInput.value==="")return;const p=d.filter(g=>g.shapes.some(v=>v.sourceId===this.currentSourceId))[u],f=d.indexOf(p),m=p.shapes.findIndex(g=>g.sourceId===this.currentSourceId);return`timeline.keyframes.${f}.shapes.${m}.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",a.id=Za.CANDIDATES_SECTION,a.dataset.icon="candidates",this.shadow.getElementById("group-observation").append(a);const o=d=>d?.closest("label")??void 0;this.candidatesView=new Lr({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const d=this.ufoElement.sighting.event,u=d.place?.[0];if(!u||d.time?.year===void 0||d.time.hour===void 0)return;const p=en(d.time,u.lng,d.utcOffsetHours);return p?{date:p,observer:{lat:u.lat,lng:u.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:d=>Xa(d,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:d=>this.poherLoaded(d),facts:()=>this.poherFacts(),satellites:()=>{const d=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,u=this.sceneElement.satellitePassesDuring(d);return u.length>0?{passes:u,positionsAt:p=>this.sceneElement.satellitePositionsAt(p)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const d=this.ufoElement.sighting.interpretation;return[...d&&(d.bodies.length>0||Wt.computes(d,to.kinds()))?[{id:"own",label:this.said.read(d.title)??this.principalObserverLabel(),interpretation:d}]:[],...this.readings]},computed:d=>this.sceneElement.computedInterpretation(d),starName:d=>this.naming.star({name:d}),projectionAt:(d,u)=>this.sceneElement.bodyProjectionAt(d,u),variants:()=>this.ufoElement.sighting.variants,keep:d=>this.editVariants(u=>[...u,d]),remove:d=>this.editVariants(u=>u.filter((p,f)=>f!==d))},a),Zr.register();const c=document.createElement("div");c.className="form-section hvs-section",c.id=Za.HVS_SECTION,c.dataset.icon="candidates",c.hidden=!0;const h=document.createElement("h3");h.className="section-title",this.hvsElement=document.createElement(Zr.TAG),this.hvsElement.frame={section:c,title:h},c.append(h,this.hvsElement),this.shadow.getElementById("group-observation").append(c),this.hvsElement.show(this.hvsInput)}hvsElement;hvsInput;set hvs(e){this.hvsInput=e,this.hvsElement?.show(e),this.isConnected&&this.runHypotheses()}redrawHvs(){this.hvsElement?.redraw(),this.isConnected&&this.runHypotheses()}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherLoaded(e){const t=`${e}/${this.language}`;return this.poherMatrix?.key!==t&&(this.poherMatrix={key:t,loaded:sa.load(e,this.language,i=>aa.json(i))}),this.poherMatrix.loaded}poherFacts(){return QI.of(this.ufoElement.sighting,this.groundElevationM??0)}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=()=>getComputedStyle(t).display==="grid",n=()=>s()?"--rr0-scene-wide-height":"--rr0-scene-max-height",r=()=>s()?`${me.SCENE_HEIGHT_KEY}-wide`:me.SCENE_HEIGHT_KEY,a=o=>{const[c,h]=[n(),r()];o===void 0?t.style.removeProperty(c):t.style.setProperty(c,`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,o)))}px`);try{o===void 0?localStorage.removeItem(h):localStorage.setItem(h,t.style.getPropertyValue(c))}catch{}};try{for(const[o,c]of[["--rr0-scene-max-height",me.SCENE_HEIGHT_KEY],["--rr0-scene-wide-height",`${me.SCENE_HEIGHT_KEY}-wide`]]){const h=localStorage.getItem(c);h&&/^\d+px$/.test(h)&&t.style.setProperty(o,h)}}catch{}e.addEventListener("pointerdown",o=>{o.preventDefault();const c=o.clientY,h=i.getBoundingClientRect().height;e.setPointerCapture?.(o.pointerId),e.classList.add("dragging");const d=p=>a(h+p.clientY-c),u=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",d),e.removeEventListener("pointerup",u),e.removeEventListener("pointercancel",u)};e.addEventListener("pointermove",d),e.addEventListener("pointerup",u),e.addEventListener("pointercancel",u)}),e.addEventListener("keydown",o=>{o.key!=="ArrowUp"&&o.key!=="ArrowDown"||(o.preventDefault(),a(i.getBoundingClientRect().height+(o.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>a(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"?Zt.isObserver(t,h):Zt.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=>Zt.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=Zt.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??Zt.observerId(t);if(Zt.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 Zt.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(Zt.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=to.kinds();if(Wt.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Wt.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(),this.runHypotheses()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=me.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips,...this.hypothesisChips]){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==="hypothesis"?this.messages.hypothesisGroup:s.group==="summary"?this.messages.summaryGroup:me.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),n_.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","hypothesis"];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 ZM(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())}unfoldedChips=new Set;hypothesisChips=[];hypothesisToken=0;async runHypotheses(){const e=++this.hypothesisToken,t=new Za(this.messages,this.language),i=[];try{const s=sa.chosenVersion(),{matrix:n,labels:r}=await this.poherLoaded(s),a=new ip(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions).of(this.poherFacts()).filter(c=>n.has(c.question)),o=t.poher(n.rank(a),a.length,r,s);o&&i.push(o)}catch{}try{const s=await this.hvsElement?.weigh(),n=s?t.hvs(s.result,s.title):void 0;n&&i.push(n)}catch{}e!==this.hypothesisToken||!this.isConnected||(this.hypothesisChips=i.map(s=>({...s,panel:this.panelIndex(s.about??"")})),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(`
|
|
12570
|
-
`)}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=me.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(me.QUESTION_FIELDS))for(const a of me.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(me.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=me.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,me.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),e.full!==void 0&&t.classList.add("describable");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),Za.fold(t,s,e,this.unfoldedChips),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&&Fn.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:fH(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(me.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,Ut.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,Ut.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(Ut.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(Ut.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={[ss.NONE.id]:this.messages.filterNone,[ss.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[ss.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==ss.ALL.length||ss.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||ss.NONE.id;this.filterSelect.replaceChildren();for(const r of ss.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||ss.usableWith(ss.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){this.refreshPoseInstrumentOptions();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=zt.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=zt.CATEGORIES.map(r=>({label:s[r],children:eu.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=me.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}refreshPoseInstrumentOptions(){const e=this.poseInstrumentSelect.value,t=document.createElement("option");t.value="",t.textContent=this.messages.poseInstrumentOwn,this.poseInstrumentSelect.replaceChildren(t,...eu.map(i=>{const s=document.createElement("option");return s.value=i.id,s.textContent=this.naming.instrument(i),s})),this.poseInstrumentSelect.value=e}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrumentAt(this.ufoElement.currentTime),i=et(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??zt.fieldOfViewDeg(t),r=s?zt.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),an.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.exposureAt(this.ufoElement.currentTime);this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":me.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const u of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(u,Vt.records(t));const c=e.ownInstrumentAt(this.ufoElement.currentTime);this.exposureInput.disabled=t.exposureRangeSeconds===void 0||!c;for(const u of[this.isoInput,this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])u.disabled=!c;const h=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const d=kc.byId(e.film);this.isoInput.placeholder=h?h.autoExposure?"auto":String(d?.iso??h.iso):"",this.setRowVisible(this.isoInput,h!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,h?.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=ss.byId(i?.filter).id),this.poseInstrumentSelect!==this.shadow.activeElement&&(this.poseInstrumentSelect.value=i?.instrument===void 0||i.instrument===e.instrumentId?"":i.instrument),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=zt.fieldOfViewDeg(e),s=zt.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>oH||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??zt.fieldOfViewDeg(e.instrument)}currentProjection(){return ra.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=Ut.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?zt.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*Ew*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)??tH,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(Ut.sizeMAt(c,h),2),lengthM:s(Ut.sizeMAt(c,h),2),heightM:s(Ut.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??=F(async()=>{const{BodyEditor:e}=await import("./BodyEditor-Bd_pKafG.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=to.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=nm.map(i=>ha.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]}static pictureTab(e){const t=W.part(e.getAttribute("aria-controls")??"");t&&!e.querySelector("svg")&&e.insertAdjacentHTML("afterbegin",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),me.pictureTab(n),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(Ja.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:Ut.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=ra.of(i.instrument,Ut.CANVAS_HEIGHT_PX,Bi.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const a=Bi.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},...gc.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]??Up,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:Yu.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Ku}:{},windows:zI(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(me.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(me.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(me.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(me.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await F(()=>import("./surroundingsSources-CqL7lcmF.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=me.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,me.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!==me.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?me.FILE_SOURCE:this.sceneryChoice===me.NO_SCENERY?me.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===me.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=ms.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?Zg.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*n1,t=Math.round(e/lH*1e3);return{lights:Yu.byId("airliner")?.create(),track:[{t:0,eastM:-n1,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:n1,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=Qf(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?Vg[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=Nh([...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=Nh(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;Fn.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=me.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!==me.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!==me.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 F(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([63,48]),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=kc.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:kc.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(kc.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 Wl(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?ja.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(Oc.resolve(Qr.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(Oc.resolve(Qr.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}=la(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=Fh.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:Fh.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:Qr.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:Vg[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=ja.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(c=>c.id===s.id?ja.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?ki.of(e,this.publishedParametersOf(e)):void 0,i=t&&Oc.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 Wl(()=>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?en(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=gi("Sun",i,t).altitudeDeg;return Xa(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Rr;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new yv;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new ws(["en"]);tagNames=new Sw({});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?en(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,Cs(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 Mn.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Bi.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=gi("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Xa(i,s,n),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<sH)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(Xa(i,0,n)));return r<=uf?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(uf))}showerClause(e,t){const i=us.observedRatePerHour(us.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=Cu.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=Cu.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:Cu.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=wg.brightestAt(e,t);if(!i||i.magnitude>ju){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=wv.brightestAt(e,t);if(!i||i.magnitude>ju){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=Rs.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=gi("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=gi("Moon",e,t);if(i.altitudeDeg<=0||hh(e).illuminatedFraction<.97)return;const s=[],n=sr.distanceKm(e,t),r=sr.relativeToMean(sr.radiusAtKm(n)),a=n<=sr.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=sr.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(sr.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Ev.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=Ga.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=Xa(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,me.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=Ga.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=gi("Sun",i.peak.date,t);return s<=Xa(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=en(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=>Ta.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Ta.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=en(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=Cs(this.ufoElement.sighting,0),s=gi("Sun",e,t),n=gi("Moon",e,t),r=At.deckLitUntilDeg(At.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(At.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(At.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??_g;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=Cs(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=gi("Sun",e,t),n=gi("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(Zn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=Zn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(Zn.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(hh(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=gi("Sun",e,t);if(i.altitudeDeg>mH)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<=ci.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=gi("Moon",e,t),o=s.darkestSkyMagPerArcsec2<gH,c=this.ufoElement.sighting.lightPollution,h=fe.scatteringAt(90-a.altitudeDeg)*fe.moonOutput(fe.phaseAngleOf(hh(e).illuminatedFraction),a.altitudeDeg)*fe.scatteredFraction(90),d=fe.artificialZenithNanolamberts(c)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(hh(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=gi("Sun",e,t),s=gi("Moon",e,t);return fe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:fe.phaseAngleOf(hh(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new ci;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<wg.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=en(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=wg.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=en(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=wv.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}=la(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-cH-(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??me.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return jE(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Wd.width/2,y:e.height/2-Wd.height/2,width:Wd.width,height:Wd.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 gx(this.ufoElement.sighting.timeline,new pz(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"})),W.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=xs.preferencesFor(this);this.preferences=t;const i=da(t,Gr),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([eM.load(i),i==="en"?{}:U5(i),r3(i),f9.load(i)]);if(await n,e!==this.localeToken)return;const h=i!==this.language;this.language=i,this.decorParameterTexts=c,this.naming=new yv(o),this.said=new ws(t),this.tagNames=new Sw(a),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new vl(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===Up&&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(me.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(me.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(dm))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,ns.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 vl(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,ns.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.labelPoseInstrument.textContent=e.poseInstrument,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.sectionIndexResize.label(e.resizeSectionIndex),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"])yr.popover(this.shadow.getElementById(s),e.close);yr.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),yr.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),yr.button(this.contextMenu,e.close,()=>this.hideContextMenu()),yr.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,me.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 oy(this.selectedMembers()),u=li.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"?li.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&&li.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,Q0);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"&&li.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Q0);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?li.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=s_;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=li.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=li.hitTestVertex(i,e);if(s===void 0)return;const n=li.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(eg,(e.maxX-e.minX)/2*t.width),s=Math.max(eg,(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=tg,o=tg+eH,c=t.width-tg,h=t.height-r-tg,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<eg||f-u<eg?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=li.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:s1};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:rH};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:ja.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,Q0)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=ja.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&&Vl(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Vl(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=li.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"?li.resizeShape(r,a,t):li.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)<aH)return;this.cameraDragState.moved=!0}const a=s+(t.x-i.x)*s1,o=Math.max(-90,Math.min(90,n-(t.y-i.y)*s1));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?uH: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)*dH*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)*hH*t,a=i*Math.PI/180,o=xr(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=ot(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(Rl,i.width-el);break;case"ArrowRight":i.width+=el;break;case"ArrowUp":i.height=Math.max(Rl,i.height-el);break;case"ArrowDown":i.height+=el;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=el;break;case"ArrowRight":i.x+=el;break;case"ArrowUp":i.y-=el;break;case"ArrowDown":i.y+=el;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 oy(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&&li.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&&li.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,Q0)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=li.hitTestHandle({bounds:new oy(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"&&li.hitTestVertex(o,t)!==void 0)return"vertex";const c=o&&li.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-${li.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(H3(this.buildPrototype({x:0,y:0,width:Wd.width,height:Wd.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 vH={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},t3="rr0-sighting-editor";function o5(){jI(),jM(),s5(),bz(),gz(),xz(),Yv(),customElements.get(t3)||customElements.define(t3,me)}const c5="rr0-read",bH="rr0-edit",Oh="in-place",yH="rr0-mode";class wH{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 yx{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(Oh)||e.setAttribute(Oh,""),e.addEventListener(c5,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([F(()=>import("./CaseElement-4CRoH54h.js"),__vite__mapDeps([64,65]),import.meta.url),F(()=>import("./SightingElement-4YMo_us5.js"),[],import.meta.url)]);r(),i();const o=xi.isCase(ys.read(e)??await aa.json(e)),c=document.createElement(o?s:a);c.setAttribute(Oh,""),c.setAttribute("show-labels",""),o&&t&&c.setAttribute(n,yx.fileKey(t)),c.setAttribute("src",e),c.addEventListener(bH,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(),ys.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 F(async()=>{const{register:r,CASE_EDITOR_ELEMENT_NAME:a}=await Promise.resolve().then(()=>xH);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):e?.start&&(n.caseStart=e.start),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(e){const t=this.editor;if(!t)return this.edit(e?{start:e}:void 0);this.reading&&await this.edit(),t.askBeforeReplacing(()=>{t.remove(),this.editor=void 0,this.edit(e?{start:e}:void 0)})}dropReader(){this.reader?.remove(),this.reader=void 0}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}}const Qw="rr0-case-editor",MH=`
|
|
12574
|
+
`)}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=me.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(me.QUESTION_FIELDS))for(const a of me.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(me.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=me.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,me.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),e.full!==void 0&&t.classList.add("describable");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),Za.fold(t,s,e,this.unfoldedChips),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&&Fn.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:fH(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(me.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,Ut.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,Ut.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(Ut.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(Ut.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={[ss.NONE.id]:this.messages.filterNone,[ss.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[ss.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==ss.ALL.length||ss.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||ss.NONE.id;this.filterSelect.replaceChildren();for(const r of ss.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||ss.usableWith(ss.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){this.refreshPoseInstrumentOptions();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=zt.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=zt.CATEGORIES.map(r=>({label:s[r],children:eu.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=me.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}refreshPoseInstrumentOptions(){const e=this.poseInstrumentSelect.value,t=document.createElement("option");t.value="",t.textContent=this.messages.poseInstrumentOwn,this.poseInstrumentSelect.replaceChildren(t,...eu.map(i=>{const s=document.createElement("option");return s.value=i.id,s.textContent=this.naming.instrument(i),s})),this.poseInstrumentSelect.value=e}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrumentAt(this.ufoElement.currentTime),i=et(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??zt.fieldOfViewDeg(t),r=s?zt.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),an.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.exposureAt(this.ufoElement.currentTime);this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":me.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const u of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(u,Vt.records(t));const c=e.ownInstrumentAt(this.ufoElement.currentTime);this.exposureInput.disabled=t.exposureRangeSeconds===void 0||!c;for(const u of[this.isoInput,this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])u.disabled=!c;const h=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const d=kc.byId(e.film);this.isoInput.placeholder=h?h.autoExposure?"auto":String(d?.iso??h.iso):"",this.setRowVisible(this.isoInput,h!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,h?.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=ss.byId(i?.filter).id),this.poseInstrumentSelect!==this.shadow.activeElement&&(this.poseInstrumentSelect.value=i?.instrument===void 0||i.instrument===e.instrumentId?"":i.instrument),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=zt.fieldOfViewDeg(e),s=zt.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>oH||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??zt.fieldOfViewDeg(e.instrument)}currentProjection(){return ra.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=Ut.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?zt.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*Ew*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)??tH,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(Ut.sizeMAt(c,h),2),lengthM:s(Ut.sizeMAt(c,h),2),heightM:s(Ut.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??=F(async()=>{const{BodyEditor:e}=await import("./BodyEditor-Bd_pKafG.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=to.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=nm.map(i=>ha.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]}static pictureTab(e){const t=W.part(e.getAttribute("aria-controls")??"");t&&!e.querySelector("svg")&&e.insertAdjacentHTML("afterbegin",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),me.pictureTab(n),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(Ja.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:Ut.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=ra.of(i.instrument,Ut.CANVAS_HEIGHT_PX,Bi.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const a=Bi.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},...gc.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]??Up,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:Yu.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Ku}:{},windows:zI(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(me.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(me.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(me.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(me.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await F(()=>import("./surroundingsSources-CqL7lcmF.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=me.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,me.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!==me.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?me.FILE_SOURCE:this.sceneryChoice===me.NO_SCENERY?me.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===me.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=ms.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?Zg.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*n1,t=Math.round(e/lH*1e3);return{lights:Yu.byId("airliner")?.create(),track:[{t:0,eastM:-n1,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:n1,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=Qf(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?Vg[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=Nh([...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=Nh(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;Fn.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=me.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!==me.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!==me.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 F(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([63,48]),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=kc.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:kc.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(kc.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 Wl(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?ja.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(Oc.resolve(Qr.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(Oc.resolve(Qr.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}=la(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=Fh.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:Fh.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:Qr.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:Vg[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=ja.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(c=>c.id===s.id?ja.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?ki.of(e,this.publishedParametersOf(e)):void 0,i=t&&Oc.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 Wl(()=>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?en(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=gi("Sun",i,t).altitudeDeg;return Xa(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Rr;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new yv;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new ws(["en"]);tagNames=new Sw({});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?en(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,Cs(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 Mn.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Bi.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=gi("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Xa(i,s,n),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<sH)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(Xa(i,0,n)));return r<=uf?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(uf))}showerClause(e,t){const i=us.observedRatePerHour(us.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=Cu.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=Cu.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:Cu.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=wg.brightestAt(e,t);if(!i||i.magnitude>ju){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=wv.brightestAt(e,t);if(!i||i.magnitude>ju){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=Rs.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=gi("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=gi("Moon",e,t);if(i.altitudeDeg<=0||hh(e).illuminatedFraction<.97)return;const s=[],n=sr.distanceKm(e,t),r=sr.relativeToMean(sr.radiusAtKm(n)),a=n<=sr.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=sr.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(sr.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Ev.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=Ga.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=Xa(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,me.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=Ga.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=gi("Sun",i.peak.date,t);return s<=Xa(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=en(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=>Ta.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Ta.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=en(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=Cs(this.ufoElement.sighting,0),s=gi("Sun",e,t),n=gi("Moon",e,t),r=At.deckLitUntilDeg(At.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(At.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(At.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??_g;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=Cs(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=gi("Sun",e,t),n=gi("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(Zn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=Zn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(Zn.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(hh(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=gi("Sun",e,t);if(i.altitudeDeg>mH)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<=ci.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=gi("Moon",e,t),o=s.darkestSkyMagPerArcsec2<gH,c=this.ufoElement.sighting.lightPollution,h=fe.scatteringAt(90-a.altitudeDeg)*fe.moonOutput(fe.phaseAngleOf(hh(e).illuminatedFraction),a.altitudeDeg)*fe.scatteredFraction(90),d=fe.artificialZenithNanolamberts(c)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(hh(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=gi("Sun",e,t),s=gi("Moon",e,t);return fe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:fe.phaseAngleOf(hh(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new ci;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<wg.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=en(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=wg.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=en(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=wv.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}=la(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-cH-(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??me.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return jE(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Wd.width/2,y:e.height/2-Wd.height/2,width:Wd.width,height:Wd.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 gx(this.ufoElement.sighting.timeline,new pz(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"})),W.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=xs.preferencesFor(this);this.preferences=t;const i=da(t,Gr),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([eM.load(i),i==="en"?{}:U5(i),r3(i),f9.load(i)]);if(await n,e!==this.localeToken)return;const h=i!==this.language;this.language=i,this.decorParameterTexts=c,this.naming=new yv(o),this.said=new ws(t),this.tagNames=new Sw(a),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new vl(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===Up&&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(me.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(me.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(dm))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,ns.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 vl(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,ns.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.labelPoseInstrument.textContent=e.poseInstrument,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.sectionIndexResize.label(e.resizeSectionIndex),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"])yr.popover(this.shadow.getElementById(s),e.close);yr.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),yr.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),yr.button(this.contextMenu,e.close,()=>this.hideContextMenu()),yr.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,me.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 oy(this.selectedMembers()),u=li.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"?li.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&&li.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,Q0);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"&&li.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Q0);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?li.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=s_;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=li.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=li.hitTestVertex(i,e);if(s===void 0)return;const n=li.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(eg,(e.maxX-e.minX)/2*t.width),s=Math.max(eg,(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=tg,o=tg+eH,c=t.width-tg,h=t.height-r-tg,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<eg||f-u<eg?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=li.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:s1};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:rH};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:ja.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,Q0)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=ja.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&&Vl(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Vl(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=li.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"?li.resizeShape(r,a,t):li.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)<aH)return;this.cameraDragState.moved=!0}const a=s+(t.x-i.x)*s1,o=Math.max(-90,Math.min(90,n-(t.y-i.y)*s1));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?uH: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)*dH*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)*hH*t,a=i*Math.PI/180,o=xr(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=ot(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(Rl,i.width-el);break;case"ArrowRight":i.width+=el;break;case"ArrowUp":i.height=Math.max(Rl,i.height-el);break;case"ArrowDown":i.height+=el;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=el;break;case"ArrowRight":i.x+=el;break;case"ArrowUp":i.y-=el;break;case"ArrowDown":i.y+=el;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 oy(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&&li.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&&li.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,Q0)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=li.hitTestHandle({bounds:new oy(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"&&li.hitTestVertex(o,t)!==void 0)return"vertex";const c=o&&li.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-${li.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(H3(this.buildPrototype({x:0,y:0,width:Wd.width,height:Wd.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 vH={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},t3="rr0-sighting-editor";function o5(){jI(),jM(),s5(),bz(),gz(),xz(),Yv(),customElements.get(t3)||customElements.define(t3,me)}const c5="rr0-read",bH="rr0-edit",Oh="in-place",yH="rr0-mode";class wH{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 yx{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(Oh)||e.setAttribute(Oh,""),e.addEventListener(c5,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([F(()=>import("./CaseElement-zFqMRzIe.js"),__vite__mapDeps([64,65]),import.meta.url),F(()=>import("./SightingElement-Bf654S_I.js"),[],import.meta.url)]);r(),i();const o=xi.isCase(ys.read(e)??await aa.json(e)),c=document.createElement(o?s:a);c.setAttribute(Oh,""),c.setAttribute("show-labels",""),o&&t&&c.setAttribute(n,yx.fileKey(t)),c.setAttribute("src",e),c.addEventListener(bH,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(),ys.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 F(async()=>{const{register:r,CASE_EDITOR_ELEMENT_NAME:a}=await Promise.resolve().then(()=>xH);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):e?.start&&(n.caseStart=e.start),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(e){const t=this.editor;if(!t)return this.edit(e?{start:e}:void 0);this.reading&&await this.edit(),t.askBeforeReplacing(()=>{t.remove(),this.editor=void 0,this.edit(e?{start:e}:void 0)})}dropReader(){this.reader?.remove(),this.reader=void 0}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}}const Qw="rr0-case-editor",MH=`
|
|
12571
12575
|
<style>
|
|
12572
12576
|
/* What the layout adapts to: the width this editor is given, never the window's. */
|
|
12573
12577
|
:host { display: block; container-type: inline-size; }
|