@rr0/ufoathome 0.194.0 → 0.195.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed-scene/rr0-scene.mjs +4 -4
- package/dist-embed-sighting/{CaseReportExport-B9iaGKNP.js → CaseReportExport-BeKawC8S.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +8 -8
- package/dist-embed-sighting-editor/{CaseElement-DzwFIDZZ.js → CaseElement-CVi_yfyW.js} +1 -1
- package/dist-embed-sighting-editor/{CaseReportExport-D0GXupCT.js → CaseReportExport-DisXbZ3b.js} +1 -1
- package/dist-embed-sighting-editor/{SightingElement-BfxNhmfn.js → SightingElement-Bdkf99VT.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +17 -16
- package/dist-embed-ufoathome/{AdsbLolArchiveProvider-DXRO-h2K.js → AdsbLolArchiveProvider-veDw9Mxo.js} +1 -1
- package/dist-embed-ufoathome/{BallesterGuaspAssessor-ZSDHMhXN.js → BallesterGuaspAssessor-BVygSN0R.js} +1 -1
- package/dist-embed-ufoathome/{BeamEditor-BvF4J204.js → BeamEditor-eDeeNBE9.js} +1 -1
- package/dist-embed-ufoathome/{BeamSystem-Yg5JRiCT.js → BeamSystem-B5u4ithz.js} +1 -1
- package/dist-embed-ufoathome/{BodyEditor-CRJFVGzZ.js → BodyEditor-23Dua2K5.js} +1 -1
- package/dist-embed-ufoathome/{CaseEditorElement-MwO-zwnP.js → CaseEditorElement-DYMt7oB4.js} +13 -12
- package/dist-embed-ufoathome/{CaseElement-Ch0QzF7-.js → CaseElement-C6KVIESP.js} +3 -3
- package/dist-embed-ufoathome/{CaseReportExport-D9YyGZHP.js → CaseReportExport-Cgs2Y0v3.js} +3 -3
- package/dist-embed-ufoathome/{CaseTimeline-CnP5rqaK.js → CaseTimeline-BwCuVg5N.js} +3 -3
- package/dist-embed-ufoathome/{ContrailSystem-O_yvjart.js → ContrailSystem-CtQPQFyc.js} +1 -1
- package/dist-embed-ufoathome/{ControlPasses-BaglOE-7.js → ControlPasses-B_uf1Wmh.js} +1 -1
- package/dist-embed-ufoathome/{CoverageAssessor-CBh0sDI1.js → CoverageAssessor-JQCFe16i.js} +1 -1
- package/dist-embed-ufoathome/{Flightradar24Provider-C8Uj-qTs.js → Flightradar24Provider-BR8_7wmx.js} +1 -1
- package/dist-embed-ufoathome/{GLTFLoader-B4SVqjkZ.js → GLTFLoader-DrBMau2Y.js} +1 -1
- package/dist-embed-ufoathome/{GeoJsonExport-C-daFhc2.js → GeoJsonExport-wUgEVyel.js} +1 -1
- package/dist-embed-ufoathome/{GeographicFigures-N4WyX3J_.js → GeographicFigures-CpbFopao.js} +1 -1
- package/dist-embed-ufoathome/{HeadlightSystem-7mtgTwud.js → HeadlightSystem-YXD1Zdpn.js} +1 -1
- package/dist-embed-ufoathome/{HynekAssessor-DdoHR-Qt.js → HynekAssessor-BV2nWUx8.js} +1 -1
- package/dist-embed-ufoathome/{InterviewEditorElement-BSXLlt4e.js → InterviewEditorElement-DiT6FZnj.js} +1 -1
- package/dist-embed-ufoathome/{InterviewElement-Dwk9iHNv.js → InterviewElement-DFcCnZtF.js} +1 -1
- package/dist-embed-ufoathome/{KmlExport-CX-tTjIv.js → KmlExport-wWr2S8H-.js} +1 -1
- package/dist-embed-ufoathome/{LaserBeam-DUL1O57g.js → LaserBeam-CejB0H9v.js} +1 -1
- package/dist-embed-ufoathome/{LaunchEditor-X_zWEOTY.js → LaunchEditor-ConcMLIe.js} +1 -1
- package/dist-embed-ufoathome/{LaunchPlume-CcfhClxb.js → LaunchPlume-BQEYjeSf.js} +1 -1
- package/dist-embed-ufoathome/{LaunchSimulation-C9gbGzGM.js → LaunchSimulation-BIiU6D8P.js} +1 -1
- package/dist-embed-ufoathome/{ModelSource-BtuW2Ztg.js → ModelSource-B93j0IA6.js} +1 -1
- package/dist-embed-ufoathome/{ModelThumbnails-CacTTCW4.js → ModelThumbnails-3U8M50_n.js} +1 -1
- package/dist-embed-ufoathome/{ModelViewer-BlFPQJAr.js → ModelViewer-Cnxj0Oi9.js} +1 -1
- package/dist-embed-ufoathome/{ModuleConformance-qYpBoQH9.js → ModuleConformance-BlrRirPF.js} +2 -2
- package/dist-embed-ufoathome/{ModuleSession-D4LhYKvL.js → ModuleSession-Cdilmebx.js} +3 -3
- package/dist-embed-ufoathome/{ModuleThree-DLikU-uy.js → ModuleThree-Dpv5uvYp.js} +1 -1
- package/dist-embed-ufoathome/{ModulesPanelElement-GY7cTQ5t.js → ModulesPanelElement-CwgqBVUI.js} +3 -3
- package/dist-embed-ufoathome/{NearestApproach-4ntSx6IQ.js → NearestApproach-CQ2w9ctm.js} +1 -1
- package/dist-embed-ufoathome/{PictureRegistration-BLs4DkTI.js → PictureRegistration-DOSDjiOf.js} +1 -1
- package/dist-embed-ufoathome/{PoherAssessor-6t5qvmJy.js → PoherAssessor-C8g5YvJi.js} +1 -1
- package/dist-embed-ufoathome/{RailwaySystem-Dm-PbG_D.js → RailwaySystem-D8B965iv.js} +1 -1
- package/dist-embed-ufoathome/{ReentryEditor-C7A3Kh3_.js → ReentryEditor-CEbb0oLd.js} +1 -1
- package/dist-embed-ufoathome/{ReentrySimulation-BlgfVSxb.js → ReentrySimulation-D_JX7wWS.js} +1 -1
- package/dist-embed-ufoathome/{ReferenceSystem-Bv62TprV.js → ReferenceSystem-xm8mzWiT.js} +1 -1
- package/dist-embed-ufoathome/{ShareDialogElement-DLr5u_tk.js → ShareDialogElement-BBMLOqSW.js} +11 -11
- package/dist-embed-ufoathome/{SightingElement-DuNE_Yt0.js → SightingElement-e9ZcWa58.js} +2 -2
- package/dist-embed-ufoathome/{TraceSystem-Cl5kzaIr.js → TraceSystem-BL6qfrHF.js} +1 -1
- package/dist-embed-ufoathome/{VideoButton-DXPI7_Vt.js → VideoButton-DA48Qz2E.js} +1 -1
- package/dist-embed-ufoathome/{WaterSystem-CTGGh-Y-.js → WaterSystem-BLy0L9qC.js} +1 -1
- package/dist-embed-ufoathome/rr0-ufoathome.mjs +2 -2
- package/dist-embed-ufoathome/{surroundingsSources-CVKKb8h6.js → surroundingsSources-Dlyt6moH.js} +1 -1
- package/dist-embed-ufoathome/{trafficRuntime-DvKPyJcx.js → trafficRuntime-B_bwWY8d.js} +1 -1
- package/package.json +1 -1
package/dist-embed-ufoathome/{CaseEditorElement-MwO-zwnP.js → CaseEditorElement-DYMt7oB4.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DqGmxMZD.js","./rr0-ufoathome.mjs","./ModelThumbnails-
|
|
2
|
-
import{C as se,F as $e,H as ze,M as We,_ as M,d as Us,P as di,e as he,f as Xe,g as F,h as X,i as _,r as _s,I as Si,s as hi,U as ci,S as Je,O as _e,j as Ot,k as Hs,m as $s,n as Lt,o as Dt,p as ys,b as Ws,c as js,q as mt,t as Gs,u as Ks,v as Vs,R as qs,w as Zs}from"./rr0-ufoathome.mjs";import{P as nt,I as D,g as Es,S as ct,l as Ys}from"./SaidPosition-CWiVNaNW.js";import{E as fe,P as rt,a as Rt,r as vi,B as Qe,N as Pt,A as ui,b as ks,W as Ne,c as xi}from"./ParameterForm-DfpJQGku.js";import{C as Be,b as Js,I as Xs,a as Qs,R as en}from"./CaseTimeline-CnP5rqaK.js";import{H as xe,E as ot,k as Ii,l as Ae,W as ee,s as be,m as V,n as tn,o as Ti,p as Gt,q as sn,t as Kt,u as Mi,v as ue,w as q,x as pi,y as Li,D as Ss,a as xs,z as Vt,F as nn,Z as rn,N as pe,G as Ye,I as Di,J as Ai,K as on,L as Te,Q as Is,U as At,V as Ci,X as z,Y as at,_ as lt,$ as Oi,a0 as Ri,a1 as Pi,a2 as an,a3 as ln,a4 as Bi,a5 as de,a6 as mi,a7 as Ts,a8 as Ms,a9 as dn,aa as qt,b as hn,ab as cn,ac as un,ad as pn,ae as mn,af as gn,ag as Oe,ah as gt,A as gi,ai as ft,aj as fn,ak as bn,al as vn,am as Fi,an as Zt,ao as Ni,ap as zi,aq as le,P as Yt,ar as Jt,as as Ke,i as wn,at as yn,au as bt,av as En,aw as Ui,ax as _i,ay as Hi,az as $i,aA as tt,g as Wi,e as ji,aB as kn,aC as Gi,aD as Ki,aE as Xt,aF as Qt,aG as Vi,aH as qi,aI as Sn,aJ as Ve,aK as Zi,aL as vt,aM as ei,f as Yi,aN as ti,aO as J,aP as xn,aQ as Ji,r as In,S as Ls,c as Tn,d as Xi,B as Mn,h as Ln,R as Dn}from"./ShareDialogElement-DLr5u_tk.js";import{K as An,r as Ct,a as fi,b as re,c as Q,A as ge,m as Ds,d as Cn,e as On,D as we,s as Bt,I as ye,S as Rn,f as Pn,g as Bn,h as Fn,i as Qi,j as Nn,k as zn,p as Un}from"./Sighting-CBpJpdm9.js";import{T as wi}from"./TimelineTracks-X_GEZi12.js";import{H as _n,o as Hn,D as As,h as $n,d as Cs,a as Wn,b as es,r as ts,c as is}from"./Decor-Dn-cvniW.js";import{R as jn}from"./ReentryArchive-CeXHrU7L.js";import{R as Re}from"./ReferenceTimeline-2kBldQeG.js";import{U as Gn}from"./upperAirSources-BGuLpdwu.js";import{S as Kn}from"./Account-C4jhsVtN.js";class oe{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===se.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",o={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:se.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},l=new oe(o,new URL("case.json",n).href),a=l.tracks[0];return a.recording=e,a.base={url:s},a.event.id=l.proposedId(a),l.caseChanged=!0,l}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===se.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(),o=e?e.event.id??this.proposedId(e):"case";let l=1;for(;r.has(`interview-${o}-${l}`);)l++;const a={type:"event",eventType:se.INTERVIEW_EVENT,id:`interview-${o}-${l}`,...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??[],a],this.caseChanged=!0,a}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&&oe.sealed(e.event)||(t=$e.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===se.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,o=n.interpretationOf===void 0?"observer":"reading",l=this.tracks.find(a=>a.url===r);return l?(l.event=n,l.kind=o,l):{event:n,url:r,kind:o}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const o=(e.events??[]).find(l=>l.eventType===se.INTERVIEW_EVENT&&(n.id!==void 0&&l.id===n.id||n.url!==void 0&&l.url===n.url));o&&s.set(o,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=o=>(o??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let o=s;for(let l=2;n.has(o);l++)o=`${s}-${l}`;return o}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=o=>o===i||o===e.recording?.id,n=(this.json.events??[]).filter(o=>o.eventType===se.SIGHTING_EVENT&&o.interpretationOf!==void 0&&[o.interpretationOf].flat().some(l=>l!==void 0&&s(l))),r=this.interviews.filter(o=>[o.interviewOf].flat().some(l=>l!==void 0&&s(l)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!oe.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const o of n){const l=[o.interpretationOf].flat().map(a=>s(a)?t:a);o.interpretationOf=Array.isArray(o.interpretationOf)?l:l[0]}for(const o of r){const l=[o.interviewOf].flat().map(a=>a!==void 0&&s(a)?t:a);o.interviewOf=Array.isArray(o.interviewOf)?l:l[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return se.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$/,""),o=new Set(this.tracks.map(A=>A.event.url)),l=new Set(this.tracks.map(A=>A.recording?.id));let a=this.tracks.filter(A=>A.kind==="reading").length+1;for(;o.has(`interpretation-${r}-${a}.json`)||l.has(`${n.id??r}-interpretation-${a}`);)a++;const d=`interpretation-${r}-${a}.json`,h=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:c,version:u,observer:p,account:m,description:f,sources:g,tags:b,timeline:v,milestones:I,interpretation:S,...w}=structuredClone(n),x={version:4,id:`${n.id??r}-interpretation-${a}`,...w,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},C={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:h+d};this.json.events=[...this.json.events??[],C],this.caseChanged=!0;const B={event:C,url:new URL(C.url,this.url).href,kind:"reading",recording:x};return this.tracks.push(B),B}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)),o=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",l=s?"interpretation":"observer";let a=`${l}-${o}.json`,d=e.id??o;for(let m=2;n.has(a)||r.has(d);m++)a=`${l}-${o}-${m}.json`,d=`${e.id??o}-${m}`;const h={...e,id:d},c=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",u={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:c+a};this.json.events=[...this.json.events??[],u],this.caseChanged=!0;const p={event:u,url:new URL(u.url,this.url).href,kind:s?"reading":"observer",recording:h};return this.tracks.push(p),s||(u.id=this.proposedId(p)),p}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};if(oe.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"||oe.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=l=>l.startsWith(i)?l.slice(i.length):l,n=this.tracks.filter(l=>e&&l.recording!==void 0&&(t||this.changed(l))).map(l=>({path:s(l.url),content:JSON.stringify(l.recording,null,2)+`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DqGmxMZD.js","./rr0-ufoathome.mjs","./ModelThumbnails-3U8M50_n.js","./ShareDialogElement-BBMLOqSW.js","./SaidPosition-CWiVNaNW.js","./Sighting-CBpJpdm9.js","./VisualAids-DI-hEL46.js","./Decor-Dn-cvniW.js","./RecordingIssue-BlWT8Xsu.js","./Obstacles-v9SkfBD7.js","./ModelSource-B93j0IA6.js","./ModelViewer-Cnxj0Oi9.js","./SightingFileEditor-Cllslp2u.js","./index-C8cdeM8E.js","./sightingSchema-CgwoRMl-.js","./surroundingsSources-Dlyt6moH.js","./ModuleSession-Cdilmebx.js","./ModulesPanelElement-CwgqBVUI.js","./ParameterForm-DfpJQGku.js","./CaseTimeline-BwCuVg5N.js","./TimelineTracks-X_GEZi12.js","./ReentryArchive-CeXHrU7L.js","./ReferenceTimeline-2kBldQeG.js","./upperAirSources-BGuLpdwu.js","./Account-C4jhsVtN.js","./PictureRegistration-DOSDjiOf.js","./TraceImport-CntRHXoJ.js","./GeoExportTexts-3a51cuxQ.js","./KmlExport-wWr2S8H-.js","./GeographicFigures-CpbFopao.js","./GeoJsonExport-wUgEVyel.js","./BodyEditor-23Dua2K5.js","./GhostSearchView-Dlhj3xWa.js","./PictureFetch-C3wgf1ZV.js","./interviewJson-D-i14LTf.js","./InterviewEditorElement-DiT6FZnj.js","./InterviewMedia-CvAxC62V.js","./InterviewElement-DFcCnZtF.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{C as se,F as $e,H as ze,M as We,_ as M,d as Us,P as di,e as he,f as Xe,g as F,h as X,i as _,r as _s,I as Si,s as hi,U as ci,S as Je,O as _e,j as Ot,k as Hs,m as $s,n as Lt,o as Dt,p as ys,b as Ws,c as js,q as mt,t as Gs,u as Ks,v as Vs,R as qs,w as Zs}from"./rr0-ufoathome.mjs";import{P as nt,I as D,g as Es,S as ct,l as Ys}from"./SaidPosition-CWiVNaNW.js";import{E as fe,P as rt,a as Rt,r as vi,B as Qe,N as Pt,A as ui,b as ks,W as Ne,c as xi}from"./ParameterForm-DfpJQGku.js";import{C as Be,b as Js,I as Xs,a as Qs,R as en}from"./CaseTimeline-BwCuVg5N.js";import{H as xe,E as ot,k as Ii,l as Ae,W as ee,s as be,m as V,n as tn,o as Ti,p as Gt,q as sn,t as Kt,u as Mi,v as ue,w as q,x as pi,y as Li,D as Ss,a as xs,z as Vt,F as nn,Z as rn,N as pe,G as Ye,I as Di,J as Ai,K as on,L as Te,Q as Is,U as At,V as Ci,X as z,Y as at,_ as lt,$ as Oi,a0 as Ri,a1 as Pi,a2 as an,a3 as ln,a4 as Bi,a5 as de,a6 as mi,a7 as Ts,a8 as Ms,a9 as dn,aa as qt,b as hn,ab as cn,ac as un,ad as pn,ae as mn,af as gn,ag as Oe,ah as gt,A as gi,ai as ft,aj as fn,ak as bn,al as vn,am as Fi,an as Zt,ao as Ni,ap as zi,aq as le,P as Yt,ar as Jt,as as Ke,i as wn,at as yn,au as bt,av as En,aw as Ui,ax as _i,ay as Hi,az as $i,aA as tt,g as Wi,e as ji,aB as kn,aC as Gi,aD as Ki,aE as Xt,aF as Qt,aG as Vi,aH as qi,aI as Sn,aJ as Ve,aK as Zi,aL as vt,aM as ei,f as Yi,aN as ti,aO as J,aP as xn,aQ as Ji,r as In,S as Ls,c as Tn,d as Xi,B as Mn,h as Ln,R as Dn}from"./ShareDialogElement-BBMLOqSW.js";import{K as An,r as Ct,a as fi,b as re,c as Q,A as ge,m as Ds,d as Cn,e as On,D as we,s as Bt,I as ye,S as Rn,f as Pn,g as Bn,h as Fn,i as Qi,j as Nn,k as zn,p as Un}from"./Sighting-CBpJpdm9.js";import{T as wi}from"./TimelineTracks-X_GEZi12.js";import{H as _n,o as Hn,D as As,h as $n,d as Cs,a as Wn,b as es,r as ts,c as is}from"./Decor-Dn-cvniW.js";import{R as jn}from"./ReentryArchive-CeXHrU7L.js";import{R as Re}from"./ReferenceTimeline-2kBldQeG.js";import{U as Gn}from"./upperAirSources-BGuLpdwu.js";import{S as Kn}from"./Account-C4jhsVtN.js";class oe{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===se.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",o={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:se.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},l=new oe(o,new URL("case.json",n).href),a=l.tracks[0];return a.recording=e,a.base={url:s},a.event.id=l.proposedId(a),l.caseChanged=!0,l}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===se.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(),o=e?e.event.id??this.proposedId(e):"case";let l=1;for(;r.has(`interview-${o}-${l}`);)l++;const a={type:"event",eventType:se.INTERVIEW_EVENT,id:`interview-${o}-${l}`,...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??[],a],this.caseChanged=!0,a}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&&oe.sealed(e.event)||(t=$e.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===se.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,o=n.interpretationOf===void 0?"observer":"reading",l=this.tracks.find(a=>a.url===r);return l?(l.event=n,l.kind=o,l):{event:n,url:r,kind:o}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const o=(e.events??[]).find(l=>l.eventType===se.INTERVIEW_EVENT&&(n.id!==void 0&&l.id===n.id||n.url!==void 0&&l.url===n.url));o&&s.set(o,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=o=>(o??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let o=s;for(let l=2;n.has(o);l++)o=`${s}-${l}`;return o}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=o=>o===i||o===e.recording?.id,n=(this.json.events??[]).filter(o=>o.eventType===se.SIGHTING_EVENT&&o.interpretationOf!==void 0&&[o.interpretationOf].flat().some(l=>l!==void 0&&s(l))),r=this.interviews.filter(o=>[o.interviewOf].flat().some(l=>l!==void 0&&s(l)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!oe.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const o of n){const l=[o.interpretationOf].flat().map(a=>s(a)?t:a);o.interpretationOf=Array.isArray(o.interpretationOf)?l:l[0]}for(const o of r){const l=[o.interviewOf].flat().map(a=>a!==void 0&&s(a)?t:a);o.interviewOf=Array.isArray(o.interviewOf)?l:l[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return se.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$/,""),o=new Set(this.tracks.map(A=>A.event.url)),l=new Set(this.tracks.map(A=>A.recording?.id));let a=this.tracks.filter(A=>A.kind==="reading").length+1;for(;o.has(`interpretation-${r}-${a}.json`)||l.has(`${n.id??r}-interpretation-${a}`);)a++;const d=`interpretation-${r}-${a}.json`,h=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:c,version:u,observer:p,account:m,description:f,sources:g,tags:b,timeline:v,milestones:I,interpretation:S,...w}=structuredClone(n),x={version:4,id:`${n.id??r}-interpretation-${a}`,...w,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},C={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:h+d};this.json.events=[...this.json.events??[],C],this.caseChanged=!0;const B={event:C,url:new URL(C.url,this.url).href,kind:"reading",recording:x};return this.tracks.push(B),B}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)),o=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",l=s?"interpretation":"observer";let a=`${l}-${o}.json`,d=e.id??o;for(let m=2;n.has(a)||r.has(d);m++)a=`${l}-${o}-${m}.json`,d=`${e.id??o}-${m}`;const h={...e,id:d},c=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",u={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:c+a};this.json.events=[...this.json.events??[],u],this.caseChanged=!0;const p={event:u,url:new URL(u.url,this.url).href,kind:s?"reading":"observer",recording:h};return this.tracks.push(p),s||(u.id=this.proposedId(p)),p}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};if(oe.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"||oe.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=l=>l.startsWith(i)?l.slice(i.length):l,n=this.tracks.filter(l=>e&&l.recording!==void 0&&(t||this.changed(l))).map(l=>({path:s(l.url),content:JSON.stringify(l.recording,null,2)+`
|
|
3
3
|
`})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",o=[...this.transcripts].filter(([l,a])=>e&&l.url!==void 0&&(t||this.transcriptChanged(a))).map(([l,a])=>({path:s(new URL(l.url,this.url).href),content:a.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
|
|
4
4
|
`},...n,...o]}}const Ft="rr0-date-input",Vn=`
|
|
5
5
|
rr0-date-input { position: relative; display: inline-flex; align-items: center; gap: .3em; }
|
|
@@ -2603,22 +2603,23 @@ ${Xe.fields(".app")}
|
|
|
2603
2603
|
/* What a click in the scene opened, pointed out for a moment. */
|
|
2604
2604
|
.flash { background: var(--warn-bg) !important; border-radius: 8px; box-shadow: 0 0 0 6px var(--warn-bg); transition: background .3s ease, box-shadow .3s ease; }
|
|
2605
2605
|
@media (prefers-reduced-motion: reduce) { .scene-card > :is(.render-line, .playback-row) { transition: none; } }
|
|
2606
|
-
/* Given the width (the app on a computer): the
|
|
2607
|
-
|
|
2606
|
+
/* Given the width (the app on a computer): the chips of the sections across the whole width, under them the render in a column of its
|
|
2607
|
+
own on the right and the section open on the left (dicté 2026-11-20 : « settings à gauche, rendu à droite »), the editor the height of the screen and the open section scrolling on its own. The chips have
|
|
2608
|
+
the whole width so that they all show on one line: in the right column alone they ran past its edge. The grip has nothing to share out between the two any more. The
|
|
2608
2609
|
width this editor is given, never the window's: held by a case, it is the case's. */
|
|
2609
|
-
@container (min-width:
|
|
2610
|
+
@container (min-width: 760px) {
|
|
2610
2611
|
.app {
|
|
2611
2612
|
/* The screen's height, or what a page that has something above it says is left (see UfoAtHomeElement). */
|
|
2612
2613
|
max-width: none; height: var(--rr0-editor-height, 100dvh); max-height: none;
|
|
2613
|
-
display: grid; grid-template-columns: minmax(
|
|
2614
|
+
display: grid; grid-template-columns: minmax(22rem, 9fr) minmax(0, 11fr);
|
|
2614
2615
|
grid-template-rows: auto auto auto auto minmax(0, 1fr);
|
|
2615
|
-
grid-template-areas: "head head" "notes notes" "
|
|
2616
|
+
grid-template-areas: "head head" "notes notes" "tabs tabs" "tracks scene" "panel scene";
|
|
2616
2617
|
}
|
|
2617
2618
|
.app > .editor-head { grid-area: head; }
|
|
2618
2619
|
.app > .save-refused { grid-area: notes; }
|
|
2619
|
-
.app > .scene-card { grid-area: scene; align-self: start; border-
|
|
2620
|
+
.app > .scene-card { grid-area: scene; align-self: start; border-left: 1px solid var(--line); }
|
|
2620
2621
|
/* As tall as the screen leaves it under the header, whatever height the grip gave it in one column. */
|
|
2621
|
-
.app > .scene-card { --rr0-scene-max-height: calc(var(--rr0-editor-height, 100dvh) -
|
|
2622
|
+
.app > .scene-card { --rr0-scene-max-height: calc(var(--rr0-editor-height, 100dvh) - 9.5rem); }
|
|
2622
2623
|
.app > .scene-resize { display: none; }
|
|
2623
2624
|
.app > #group-tabs { grid-area: tabs; }
|
|
2624
2625
|
.app > #timeline-tracks { grid-area: tracks; }
|
|
@@ -2695,8 +2696,8 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
|
|
|
2695
2696
|
.model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
|
|
2696
2697
|
.model-picker .model-name { font-weight: 600; }
|
|
2697
2698
|
.model-picker .model-credit { font-size: .8em; color: #666; }
|
|
2698
|
-
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await M(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-CacTTCW4.js");return{ModelThumbnails:i}},__vite__mapDeps([2,3,1,4,5,6,7,8,9,10]),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 o=()=>{const a=++n,d=e.selectedOptions[0],h=e.value===""?i?.current():void 0,c=JSON.stringify([e.value,d?.textContent,h?.url,h?.title,this.messages().choose,[...e.options].map(m=>m.value).join()]);if(c===r){--n;return}r=c,s.replaceChildren();const u=document.createElement("span");u.textContent=`${h?h.title||h.url:d?.textContent??""} …`,s.title=this.messages().choose,s.append(u);const p=e.value;(h?Promise.resolve({url:h.url}):t(p)).then(m=>ht.pictureOf(m)).then(m=>{if(!m||a!==n)return;const f=new Image;f.src=m,f.alt="",s.prepend(f)})};e.addEventListener("change",o),new MutationObserver(o).observe(e,{childList:!0,subtree:!0});const l=i&&{current:()=>i.current(),apply:a=>{i.apply(a),o()}};s.addEventListener("click",()=>void this.open(e,t,l)),o()}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=ht.STYLE,t.append(i)}open(e,t,i,s){const n=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const o=document.createElement("div");o.className="model-picker",o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true");const l=document.createElement("h2");l.textContent=n.title;const a=document.createElement("button");a.type="button",a.className="model-picker-close",a.setAttribute("aria-label",n.close),a.title=n.close,a.innerHTML=D.CLOSE;const d=document.createElement("header");d.append(l,a);const h=document.createElement("div");h.className="model-picker-body",o.append(d,h),r.append(o);const c=()=>{r.remove(),document.removeEventListener("keydown",u,!0),M(async()=>{const{ModelViewer:x}=await import("./ModelViewer-BlFPQJAr.js");return{ModelViewer:x}},__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),import.meta.url).then(({ModelViewer:x})=>x.end())},u=x=>{x.key==="Escape"&&(x.stopPropagation(),c())},p=i?.current(),m="\0address",f=x=>x===m&&p?Promise.resolve({url:p.url}):t(x),g=x=>{if(c(),s){x!==m&&s(x);return}x===m||x===e.value||(e.value=x,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const v=new Map,I=x=>{const C=document.createElement("button");C.type="button",C.className="model-card",C.dataset.value=x.value,C.setAttribute("aria-pressed",String(!s&&(x.value===m||x.value===e.value&&!p)));const B=document.createElement("div");B.className="model-thumb";const A=document.createElement("span");if(A.className="model-name",A.textContent=x.textContent,C.append(B,A),x.title){const E=document.createElement("span");E.className="model-credit",E.textContent=x.title,C.append(E)}f(x.value).then(E=>ht.pictureOf(E)).then(E=>{if(!E)return;const T=new Image;T.src=E,T.alt="",B.append(T)});let te,Z=!1;const Ce=()=>{Z&&!(te&&!te.active)||(Z=!0,Promise.all([f(x.value),M(()=>import("./ModelViewer-BlFPQJAr.js"),__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),import.meta.url)]).then(([E,{ModelViewer:T}])=>{!E||!Z||(te=T.show(B,E))}).catch(()=>{}))},je=()=>{Z=!1,te?.stop(),te=void 0};return v.set(C,Ce),C.addEventListener("pointerenter",Ce),C.addEventListener("focus",Ce),C.addEventListener("pointerleave",()=>{document.activeElement!==C&&je()}),C.addEventListener("blur",je),C.addEventListener("click",E=>{if(te?.consumeDrag()){E.preventDefault();return}g(x.value)}),C},S=()=>(b=document.createElement("div"),b.className="model-picker-grid",h.append(b),b);if(p){const x=new Option(p.title||p.url,m);x.title=[p.author,p.license].filter(Boolean).join(" — "),S().append(I(x))}for(const x of Array.from(e.children))if(x instanceof HTMLOptGroupElement){const C=document.createElement("h3");C.textContent=x.label,h.append(C);const B=S();for(const A of Array.from(x.children))B.append(I(A));b=void 0}else x instanceof HTMLOptionElement&&(b??S()).append(I(x));i&&this.addAddressForm(d,a,o,h,i,n,c),a.addEventListener("click",c),r.addEventListener("click",x=>{x.target===r&&c()}),document.addEventListener("keydown",u,!0),this.root.append(r);const w=o.querySelector('.model-card[aria-pressed="true"]');(w??a).focus(),w&&v.get(w)?.()}addAddressForm(e,t,i,s,n,r,o){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const a=document.createElement("form");a.className="model-picker-address",a.hidden=!0;const d=(v,I,S="")=>{const w=document.createElement("label"),x=document.createElement("span");x.textContent=v;const C=document.createElement("input");return C.type=I,C.placeholder=S,w.append(x,C),a.append(w),C},h=d(r.addressUrl,"url","https://…/model.glb"),c=d(r.addressName,"text"),u=d(r.addressAuthor,"text"),p=d(r.addressLicense,"text","CC0 1.0"),m=d(r.addressSource,"url","https://…"),f=document.createElement("p");f.textContent=r.addressIncomplete;const g=document.createElement("button");g.type="submit",g.className="model-picker-use",g.textContent=r.addressUse,a.append(f,g),i.insertBefore(a,s);const b=()=>{g.disabled=h.value.trim()==="",f.hidden=h.value.trim()===""||c.value.trim()!==""&&p.value.trim()!==""};for(const v of[h,c,u,p,m])v.addEventListener("input",b);l.addEventListener("click",()=>{const v=a.hidden;if(a.hidden=!v,l.setAttribute("aria-expanded",String(v)),!v)return;const I=n.current();h.value=I?.url??"",c.value=I?.title??"",u.value=I?.author??"",p.value=I?.license??"",m.value=I?.source??"",b(),h.focus()}),a.addEventListener("submit",v=>{v.preventDefault(),h.value.trim()!==""&&(n.apply({url:h.value.trim(),title:c.value.trim(),author:u.value.trim(),license:p.value.trim(),source:m.value.trim()}),o())}),b()}}class ki{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=ki.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 _r{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 ae{static STEP_MS=100;static plan(e){const t=ae.routeOf(e),i=Te.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const o=new Set,l=(c,u,p,m)=>{if(Math.abs(c.radiusM-m)>=m*.1)return!1;const{x:f,z:g}=Es(u,p,c.lat,c.lng);return Math.hypot(f,g)<Te.rebuildDistanceFor(m)};for(let c=0;;c=Math.min(s,c+ae.STEP_MS)){const u=Q(e,c);if(u?.lat!==void 0&&u.lng!==void 0){const p=Te.groundRadiusFor(u.elevationM??0),m=Te.patchRadiusFor(p,u.elevationM??0),f=Math.max(m,i);(!r||!l(r,u.lat,u.lng,f))&&(r=n.find(g=>l(g,u.lat,u.lng,f)),r||n.push(r={lat:u.lat,lng:u.lng,radiusM:f})),f<p&&o.add(r)}if(c>=s)break}const a=e.weatherTrack.allKeyframes.map(c=>c.weather.visibilityKm).filter(c=>c!==void 0),d=Te.farRingRadiusFor(a.length>0?Math.max(...a):void 0);for(const c of o)n.push({lat:c.lat,lng:c.lng,radiusM:d,far:!0});if(d>Te.FAR_RING_RADIUS_M)for(const c of[...n])!c.far&&!o.has(c)&&c.radiusM<d&&n.push({lat:c.lat,lng:c.lng,radiusM:d,far:!0});const h=Is.map(c=>At.of(c)).filter(c=>c.reachM&&At.eventsOf(e.skyEvents,c).length>0);if(h.length>0){const c=u=>Math.max(...h.map(p=>p.reachM(At.eventsOf(e.skyEvents,p),u)));for(const u of[...n])u.far||o.has(u)||n.some(p=>p.far&&p.lat===u.lat&&p.lng===u.lng)||Te.needsFarRing(u.radiusM,0,c(u))&&n.push({lat:u.lat,lng:u.lng,radiusM:d,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),o=l=>n?.(l,i.length);switch(e){case"relief":{const l=ae.routeOf(t),a=[];for(const[c,u]of i.entries()){try{const p=await s.elevation.getElevationGrid(lt.boundsOf(u),{width:Pi,height:Pi},{route:l});a.push({...u,grid:p})}catch(p){console.warn("Relief not snapshots for a patch:",p)}o(c+1)}if(a.length===0)return;const d=s.elevationCredit;return{bytes:await an.encode({takenOn:r,attribution:d,patches:a}),attribution:d,takenOn:r,answered:a.length,patches:i.length}}case"imagery":{const l=new Ci,a=z(at,s.imagery),d=a.create(l.fetch);let h=0;for(const[p,m]of i.entries()){try{await d.getImageryTexture(lt.boundsOf(m),{width:Oi,height:Oi}),h++}catch(f){console.warn("Imagery not snapshots for a patch:",f)}o(p+1)}if(l.tiles.size===0)return;const c=d.attribution;return{bytes:await Ri.encode({takenOn:r,source:a.id,attribution:c,patches:[...i],tiles:l.tiles}),attribution:c,takenOn:r,answered:h,patches:i.length}}case"roads":return ae.vector(s.roads,i,r,o,(l,a)=>l.getRoads(a),l=>l.contemporary);case"water":return ae.vector(s.water,i,r,o,(l,a)=>l.getWater(a));case"railways":return ae.vector(s.railways,i,r,o,(l,a)=>l.getRailways(a),l=>l.contemporary)}}static mapGround(e){const t=ln.of(e);return t&&Bi.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=ae.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Ci,r=z(at,t),o=r.create(n.fetch),l=Bi.IMAGERY_PX;try{await o.getImageryTexture(i,{width:l,height:l})}catch(h){console.warn("Map imagery not snapshots:",h);return}const a=o.attribution;return{bytes:await Ri.encode({takenOn:s,source:r.id,attribution:a,patches:[],map:{bounds:i,pixels:l},tiles:n.tiles}),attribution:a,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const o=[];for(const[d,h]of t.entries()){if(h.radiusM<=Te.ROADS_MAX_RADIUS_M)try{o.push({...h,items:await n(e,lt.boundsOf(h))})}catch(c){console.warn("Not snapshots for a patch:",c)}s(d+1)}if(o.length===0)return;const l={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:o};return{bytes:new TextEncoder().encode(JSON.stringify(l)),attribution:e.attribution,takenOn:i,answered:o.length,patches:t.length}}}class j{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:j.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&j.isInline(t.src)}annex(e){const t=this.host.sighting().snapshots?.[e];return t?.src!==void 0?t:void 0}isLive(e){return X.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 X.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,o=r&&j.isInline(i.src);this.sourceInput.url=r?o?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&&!o?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!j.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 M(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:r}},__vite__mapDeps([12,13,14]),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 j.describe(e,n)}}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}de.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}F.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await M(async()=>{const{InputFileElement:s}=await import("./rr0-ufoathome.mjs").then(n=>n.J);return{InputFileElement:s}},[],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 j.describe(e,t)}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}const o=n!==void 0&&j.isInline(n.src),l=o?j.dataUrl(e,t):n?.src??X.annexName(this.host.base(),e);o||de.hold(this.address(l),t),s[e]={...s[e]?.live?{live:!0}:{},src:l,...r},F.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${l}`),this.setSnapshots(s)}async setStorage(e,t){const i={...this.host.sighting().snapshots??{}},s=this.annex(e);if(!s||j.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=j.dataUrl(e,n):(r=X.annexName(this.host.base(),e),de.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=j.isInline(t.src)?X.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:j.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(j.isZip(e)){const{unzipSync:s}=await M(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 de.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:${j.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&&!j.isInline(i)?j.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,ae.plan(this.host.sighting()),this.host.sources(),s))?F.show(this.note,void 0):F.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 X.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||ae.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=h=>X.isLive(i,h),r=h=>i[h]?.src!==void 0?i[h]:void 0;for(const h of X.NAMES)!i.live&&i[h]?.live&&(i[h]={live:!0});const o=ae.plan(t);let l;for(const h of X.TERRAIN){if(n(h))continue;const c=r(h);if(o.length>0&&(!c||c.refresh||!await this.fits(h,c,o))&&await this.take(h,i,o,l??=this.host.sources(),e)){await this.keep(r(h),s);continue}c?.refresh&&(i[h]={...c,refresh:void 0}),r(h)&&await this.keep(r(h),s)}if(!n("map")){const h=r("map");ae.mapGround(t)!==void 0&&(!h||h.refresh||!await this.fitsMap(h))&&await this.takeMap(i,l??=this.host.sources(),e)?await this.keep(r("map"),s):h&&(h.refresh&&(i.map={...h,refresh:void 0}),await this.keep(r("map"),s))}const a=this.host.upperAirHeard(),d=r("upperAir");if(!n("upperAir")&&a&&(!d||d.refresh)){const h=new Date().toISOString().slice(0,10),c={version:1,takenOn:h,attribution:a.answer.source.name,answers:[a]},u=new TextEncoder().encode(JSON.stringify(c)),p=this.place("upperAir",d?.src,e,u);i.upperAir={src:p,takenOn:h,attribution:a.answer.source.name},j.isInline(p)||s.set(p,u)}else d&&!n("upperAir")&&(d.refresh&&(i.upperAir={...d,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),o=await ae.freeze(e,this.host.sighting(),i,s,(l,a)=>F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(l)).replaceAll("{of}",String(a))));return F.show(this.note,void 0),o?(t[e]={src:this.place(e,t[e]?.src,n,o.bytes),takenOn:o.takenOn,attribution:o.attribution},!0):!1}async takeMap(e,t,i){F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await ae.freezeMap(this.host.sighting(),t.imagery);return F.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=ae.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await de.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&<.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 de.zip(s))["index.json"])).patches:(await de.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(o=>o.radiusM<=Te.ROADS_MAX_RADIUS_M);return lt.samePatches(n.map(({lat:o,lng:l,radiusM:a})=>({lat:o,lng:l,radiusM:a})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&j.isInline(t))return j.dataUrl(e,s);const n=t??X.annexName(i,e);return de.hold(this.address(n),s),n}async keep(e,t){if(!j.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return de.bytes(this.address(e.src))}address(e){return de.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of X.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=X.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 jt{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,F.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[_.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 ct(ze.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:_.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=mi(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:$e.CURRENT.sighting,takenOn:i,attribution:s,..._.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)??_.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(l=>{if(!l.ok)throw new Error(String(l.status))})}catch{const l={...this.host.sighting().snapshots??{}};l[e]={...l[e]??{},src:t.url},F.show(this.note,void 0),this.write(e,l);return}let i;try{const{InputFileElement:l}=await M(async()=>{const{InputFileElement:d}=await import("./rr0-ufoathome.mjs").then(h=>h.J);return{InputFileElement:d}},[],import.meta.url),a=await l.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=$e.recording(JSON.parse(new TextDecoder().decode(a))),typeof i!="object"||i===null||_.KEYS[e].every(d=>i[d]===void 0))throw new Error("Not this section")}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...mi(s)};if(e==="decor")_.put(e,n,"timeline"in i?_.taken(e,i):i);else for(const l of _.KEYS[e])n[l]=i[l];const r=Ts(n);jt.copy(e,r,s);const o={...s.snapshots??{}};t.url?o[e]={...o[e]??{},src:t.url}:o[e]=o[e]??{},F.show(this.note,void 0),this.write(e,o)}write(e,t){this.host.sighting().snapshots=X.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 _.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 Hr{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 $r=he.point("timeZone").provide(he.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new Hr}]);class oi{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 K{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=K.select("observerOccupationKind");graduate=K.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=K.select("observersRelation");activity=K.select("observerActivity");factors=new Map(Kn.map(e=>[e,K.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){Ae.register(),e.append(this.label(this.occupationKind,d=>[d.occupationKind,d.occupationKindHint]),this.label(this.graduate,d=>[d.graduate]));const n=this.label(this.enquiryMinutes,d=>[d.enquiryMinutes,d.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,d=>[d.relation]),this.label(this.activity,d=>[d.activity]));const o=Object.assign(document.createElement("h3"),{className:"section-title"});o.append(this.strangenessTitle),i.append(o,this.strangenessIntro,...[...this.factors].map(([d,h])=>this.label(h,c=>[c.factors[d],c.factorHints[d]])));const l=[["yes","yes"],["no","no"]],a=d=>d.map(h=>[h,h]);K.choices(this.occupationKind,"",a(Object.keys(oi.OCCUPATIONS))),K.choices(this.graduate,"",l),K.choices(this.relation,"",a(oi.RELATIONS)),K.choices(this.activity,"",a(oi.ACTIVITIES));for(const d of this.factors.values())K.choices(d,"",l);for(const d of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])d.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,K.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),K.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),K.choices(this.relation,e.unknown,Object.entries(e.relations)),K.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)K.choices(i,K.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=K.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=K.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=K.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:K.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);Ae.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 It=new Set;Ms();In();Ls.register();const qe={width:48,height:28},Wr=2500,Tt=40,Mt=10,jr=30,Gr=10,fs=600,bs=900,Ze=2e-4,Kr=900,Vr=-1.46,qr=3,ai=.2,Zr=.5,Yr=3,Jr=.01,Xr=1.6,li=2e3,Qr=250,vs=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),eo=1,to=5,io=10,Pe=4,st="ufo-1",so={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function no(k){return k.kind==="oval"?"oval":"polygon"}const ro=-6,oo=21;class y extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=$r[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new _r;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;exportKmlButton;exportGeoJsonButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;saidInterviews;candidatesView;sectionFolds;snapshotsPanel;sectionFilePanel;eventsPanel;aroundPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;aircraftStatus=Object.assign(document.createElement("span"),{className:"source-status"});aircraftFlights;aircraftFlightsShownAt=0;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=Ur();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 it(Nr());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;static FIELDS_OF_PATH={time:["obs-time","obs-time-native"],"place.locations.0.lat":["lat"],"place.locations.0.lng":["lng"]};markBeyondKnown(e){for(const{field:t,title:i}of this.markedBeyondKnown)t.removeAttribute("aria-invalid"),i===null?t.removeAttribute("title"):t.setAttribute("title",i);this.markedBeyondKnown=[];for(const{path:t,why:i}of e)for(const s of y.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?dn.boundsOf(e.time):void 0;t?.setBounds(i?{...i,...e.hour?{adjust:e.hour}:{}}:void 0);for(const[s,n]of[["lat",e.lat],["lng",e.lng]]){const r=this.shadow.getElementById(s);if(r&&(this.numberBounds.set(r,n),r.min=n?String(n[0]):"",r.max=n?String(n[1]):"",!this.boundedFields.has(r))){this.boundedFields.add(r);const o=()=>{const l=this.numberBounds.get(r),a=Number(r.value);if(!l||r.value===""||!Number.isFinite(a))return;const d=Math.min(Math.max(a,l[0]),l[1]);d!==a&&(r.value=String(d))};r.addEventListener("change",o,{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 qt;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=We.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...so};currentSourceId=st;selectedSourceIds=new Set([st]);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(vs.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;vs.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>${ar}</style>${or}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const a of this.shadow.querySelectorAll(Ft))a.build();for(const a of this.shadow.querySelectorAll($t))a.build();for(const a of this.shadow.querySelectorAll(Si))a.build();for(const a of this.shadow.querySelectorAll(xi))a.build();this.sceneElement=document.createElement(hn),this.sceneElement.addEventListener("observermapchange",a=>{this.ufoElement.sighting.observerMap=a.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",a=>{const{lat:d,lng:h}=a.detail;this.latInput.value=String(Number(d.toFixed(6))),this.lngInput.value=String(Number(h.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 dt(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const a of[this.timeStartLabel,this.timeEndLabel])a.addEventListener("click",()=>this.switchTimeDisplay()),a.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($t),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 W(this.shadow);const t=this;this.witnessErrorView=new Ps({get sighting(){return t.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:a=>{const d=this.ufoElement.sighting,{conditions:h,...c}=d.account??{},u={...c,...a?{conditions:a}:{}};d.account=Object.values(u).some(p=>p!==void 0)?u:void 0},recordingJson:()=>this.sightingData,valueSources:()=>this.valueSources(),lawsChanged:()=>{this.sceneElement.confrontationTolerance=cn.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new wi(this.shadow.getElementById("timeline-tracks"),a=>this.goToMark(a),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",a=>{a.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new Bs(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",a=>{const d=a.target.id;y.SCENE_LINKED.includes(d)&&this.setActiveSceneField(d)}),this.shadow.addEventListener("focusout",a=>{const d=a.relatedTarget;(!d||!y.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 K(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${xi}[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(y.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 j(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:(a,d)=>this.download(a,d)}),this.sectionFilePanel=new jt(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,d)=>this.download(a,d),changed:a=>{if(this.touch(),this.ufoElement.refresh(),a==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),a==="place"&&this.syncPlaceNameField(),a==="lightPollution"){const d=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=d===void 0?"":String(d),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const i={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:a=>this.goToMark(a),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const a=this.ufoElement.sighting.timeline;return a.sourceIds.includes(this.currentSourceId)?a.topOf(this.currentSourceId):void 0},shapesLabel:a=>this.shapesLabel(a),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:a=>this.naming.point(a),lookedAt:()=>{const a=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return a?.headingDeg===void 0||a.pitchDeg===void 0?void 0:{azimuthDeg:a.headingDeg,altitudeDeg:a.pitchDeg}},bodyLabel:a=>{const d=this.ufoElement.sighting.interpretation?.bodies.find(h=>h.id===a);return this.said.read(d?.title)??a},valueSources:()=>this.valueSources()};this.eventsPanel=new Se(this.shadow.getElementById("events-section"),i,void 0),this.phenomenonEventsPanel=new Se(this.shadow.getElementById("phenomenon-events-section"),i,void 0,"phenomenon"),this.bodiesEventsPanel=new Se(this.shadow.getElementById("bodies-events-section"),i,void 0,"bodies"),this.aroundPanel=new tr(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 a=Number(this.samplingRateInput.value);i.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(a)&&a>0?a:void 0,ue.refresh(this.ufoElement.sighting),i.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.snapshotsPanel.localize(this.messages),this.sectionFilePanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",a=>{a.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 lr(this.shadow.getElementById("aircraft-flights"),a=>this.aimAtFlight(a),a=>this.naming.point(a)),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 fe({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:a=>`option-decor-${a}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectDecor(a),onAdd:a=>this.addDecor(a),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 fe({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:a=>this.selectObserver(a),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 ie(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:a=>this.setPlantedDecor(a),kindName:a=>this.decorList.kindLabel(a),cite:a=>this.citeSource(a),busy:(a,d)=>this.sceneElement.setBusy(a,d),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(a=>({lat:a.pose.lat,lng:a.pose.lng})).filter(a=>typeof a.lat=="number"&&typeof a.lng=="number")},this.messages,async(a,d)=>this.surroundingsProvider?this.surroundingsProvider.covers(a,d)?this.surroundingsProvider:void 0:(await M(async()=>{const{SurroundingsSources:h}=await import("./surroundingsSources-CVKKb8h6.js");return{SurroundingsSources:h}},__vite__mapDeps([15,1,3,4,5,6,7,8,9]),import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,a,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 a=this.scenerySource.value===y.FILE_SOURCE;if(this.setDecorFromFile(a),a){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===y.NO_SCENERY){this.surroundings.withdraw();return}const d=this.plantingCentre();d&&this.surroundings.survey(d.lat,d.lng)}),this.sceneryRadius.addEventListener("input",()=>{const a=Number(this.sceneryRadius.value);if(!Number.isFinite(a)||a<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const d=this.plantingCentre();this.surroundings.radiusChanged(a,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 ui(this.addReferenceButton,"reference-add-kind",a=>this.addReferenceOfKind(a),a=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[a]??`reference-add-${a}`),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 ht(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 rt(this.decorParametersHost,"en","decorParam.");const s={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new rt(this.decorBaseHost,"en","decorBase.",s,(a,d)=>this.enhanceDecorModelChoice(a,d)),this.decorStateForm=new rt(this.decorStateHost,"en","decorState.",s),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{this.focus({preventScroll:!0}),this.onPointerDown(a)}),this.ufoElement.canvasElement.addEventListener("pointermove",a=>this.onPointerMove(a));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{n={x:a.clientX,y:a.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",a=>{const d=n;n=void 0,!(!d?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(a.clientX-d.x,a.clientY-d.y)>y.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",a=>this.onContextMenu(a)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()});const r=this.shadow.getElementById("editor-mute"),o=this.shadow.getElementById("editor-volume");r.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",a=>{const d=a.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 a of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])a.addEventListener(a instanceof HTMLSelectElement||a.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 a=this.ufoElement.sighting;a.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),a.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),a.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",a=>{const{seconds:d,text:h}=a.detail;this.ufoElement.sighting.event.durationText=h,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 a of this.referenceFields)a.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",a=>void this.setReferenceSource(a.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 a=this.shadow.getElementById("trace-import-row");a.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",a=>void this.addTraces(a.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",a=>this.onReferenceWheel(a),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onBodyWheel(a),{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 a of[this.milestoneLabelInput,this.milestoneNoteInput])a.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(un,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(pn,()=>{const a=this.currentReference();a&&this.syncReferenceStatus(a)}),this.sceneElement.addEventListener(mn,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(gn,()=>{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 ui(this.addShapeButton,"add-shape-kind",a=>{const d=Me.byId(a);if(d){this.addModel(d);return}this.currentAppearance={...this.currentAppearance,presetId:a},this.addShape()},a=>`add-shape-${a}`),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 a of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])a.addEventListener("input",()=>this.updateObserver());for(const a of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])a.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",a=>{if(this.observerSaid=a.detail.said,!this.observerPosition.relative)return;const d=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(d,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",a=>this.writeObserverBasis(a.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("input",()=>this.refreshHeadingPoint()),this.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const a=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const d=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(h=>[h.t,Oe.fovOf(this.ufoElement.sighting,h.t)]));this.retuneFieldOfView(a),this.retuneExposure(a),Oe.reproject(this.ufoElement.sighting,a,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 l=a=>this.shadow.querySelector(`${Ft}[name="${a}"]`);this.startDate=l("obs-time"),this.endDate=l("obs-end-time"),this.birthDate=l("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=gt.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const a of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(a,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",a=>{const{time:d}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=d}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",a=>{this.birth=a.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",a=>{const{time:d}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=d})});for(const a of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])a.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(y.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const a of this.weatherFields){if(a===this.iceCrystalAlignmentInput||a===this.rareIceCrystalsInput){a.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}a.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const a of this.soundFields)a.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(a=>this.shadow.getElementById(a.getAttribute("aria-controls")));for(const a of this.groupTabs)a.addEventListener("click",()=>this.toggleGroup(a,!this.isGroupOpen(a)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const a of this.subgroupTabs)a.addEventListener("click",()=>this.openSubgroup(a));this.buildSkyParts(),Pt.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",a=>this.onParamSummaryClick(a)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(a=>a.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=Xn(this.shadow.getElementById("cloud-editor"),this.sceneElement,(a=!0)=>{a&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(a,d)=>{this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(d)),this.updateObserver()},hi(ze.preferencesFor(this),ci),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),ze.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),he.changes.addEventListener("change",this.onModulesChanged),M(async()=>{const{ModuleSession:t}=await import("./ModuleSession-D4LhYKvL.js");return{ModuleSession:t}},__vite__mapDeps([16,1,3,4,5,6,7,8,9]),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=gt.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),he.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=$e.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]??st,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:()=>`${gi.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=q.issues(this.ufoElement.sighting);if(F.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=U.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=U.namesOf(this.sightingData);this.observerLastNameInput.value=U.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>U.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=U.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=U.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=U.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 _.NAMES){const o=this.sectionFilePanel.annex(r);o&&(/^[a-z][a-z0-9+.-]*:/i.test(o.src)||t.set(o.src,o.bytes),_.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:o}=await M(async()=>{const{zipSync:d,strToU8:h}=await import("./browser-CltifEM0.js");return{zipSync:d,strToU8:h}},[],import.meta.url),l={[s]:o(n)};for(const[d,h]of t)l[d]=h;const a=r(l,{level:0});this.download(new Blob([a],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.snapshotExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",j.size(a.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"),..._.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...X.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,y.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=X.NAMES.includes(e),i=_.NAMES.includes(e)?e:void 0,s=e===y.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 o=this.shadow.getElementById(r);o.hidden||fe.glue(o)}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)?jt.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 qt)||he.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 o=await e.moduleOf(r),l=o===void 0?void 0:he.installed().find(a=>a.id===o)?.url;!l||gs.names(n,l,s)||(n=[...n??[],gs.of(l,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??=M(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-GY7cTQ5t.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([17,1,16,3,4,5,6,7,8,9,18,19,20,21,22,23,24]),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 _.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=z(ft,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:z(at,this.chosenSourceId.get("imagery")).id,roads:vn(),water:bn(),railways:fn()}}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 o=new FileReader;o.onload=()=>n(o.result),o.onerror=()=>r(o.error),o.readAsArrayBuffer(e)}));de.release();const i=await this.recordingText(t),s=JSON.parse(i);if(se.isCase(s)){if(se.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 M(async()=>{const{unzipSync:h,strFromU8:c}=await import("./browser-CltifEM0.js");return{unzipSync:h,strFromU8:c}},[],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(h=>h.endsWith(".json")&&!n.test(h));if(!r)throw new Error("No recording in this archive");const o=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[h,c]of Object.entries(s))h!==r&&h.startsWith(o)&&de.hold(de.address(h.slice(o.length),void 0),c);const l=i(s[r]),a=JSON.parse(l);let d=!1;for(const h of _.NAMES){const c=a.snapshots?.[h]?.src,u=c!==void 0?s[o+c]:void 0;if(!u)continue;const p=$e.recording(JSON.parse(i(u)));_.put(h,a,p),d=!0}return d?JSON.stringify(a):l}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 Je.recording(e);if(se.isCase(t)){se.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;de.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=_e.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(){F.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof Ot)return e.said(this.messages.formatVersionError);if(!(e instanceof Hs))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=wt[0].create();get narrativeSourceId(){return z(wt,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:y.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof ce&&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,o=ke.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,a=Fi(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=ke.apply(a,_t.loadable(r),o)}finally{this.patchingDraft=!1}this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.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:y.valueAt(Fi(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[ao[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 o=document.createElement(t==="stated"?"q":"span");o.textContent=s.rationale,n.append(r,o),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=z(wt,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(),o=r===""?void 0:s.suspect(r);n.classList.toggle("invalid",o!==void 0),n.title=o?this.said.read(o)??"":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 l of i.choices??[]){const a=document.createElement("option");a.value=l.value,a.textContent=this.said.read(l.label)??l.value,r.appendChild(a)}}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 o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),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 ce))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(){y.pageCredentials.clear(),Zt.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!==""?y.pageCredentials.set(t,i):y.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(y.NARRATIVE_KEY_STORAGE),localStorage.removeItem(y.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 y.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} `),y.creditLink(z(ri,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",Gn,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),y.creditLink(z(Et,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",wt,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",ri,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",Et,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",ft,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",at,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[y.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[y.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[y.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",Ni,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,s){const n=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;const o=()=>{r.replaceChildren(...t.map(f=>{const g=document.createElement("option");return g.value=f.id,g.textContent=f.name,g.title=f.credit,g})),s&&r.appendChild(new Option(this.messages.sourceFile,y.FILE_SOURCE))};o();const l=()=>{const f=this.chosenSourceId.get(e);return f!==void 0&&t.some(g=>g.id===f)?f:t[0].id};r.value=s?.fromFile()?y.FILE_SOURCE:l();const a=document.createElement("a");a.className="source-credit",a.target="_blank",a.rel="noopener noreferrer";const d=document.createElement("button");d.type="button",d.className="link source-file-link",d.addEventListener("click",()=>this.openFileItem(s.item));const h=document.createElement("label");h.className="source-key";const c=document.createElement("input");c.type="password",c.id=`${e}SourceKey`,c.autocomplete="off",c.spellcheck=!1,c.title=this.messages.sourceKeyHint;const u=document.createElement("a");u.className="source-credit",u.target="_blank",u.rel="noopener noreferrer",u.textContent=this.messages.sourceKeyGet,h.append(document.createTextNode(`${this.messages.sourceKey} `),c,document.createTextNode(" "),u),c.addEventListener("change",()=>{const f=z(t,r.value);Zt.set(f.id,c.value),i(f,!0)});const p=()=>{const f=r.value===y.FILE_SOURCE,g=z(t,f?l():r.value);h.hidden=f||!g.keyUrl,u.href=g.keyUrl??"",c.value=Zt.of(g.id)??"",r.title=f?s.where():g.credit,a.hidden=f,a.href=g.creditUrl,a.textContent=g.credit,d.hidden=!f,f&&(d.textContent=s.label(),d.title=s.where())};p(),r.addEventListener("change",()=>{const f=r.value===y.FILE_SOURCE;f||this.chosenSourceId.set(e,r.value),s?.setFromFile(f),p(),f||i(z(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?y.FILE_SOURCE:l(),p()});const m=()=>{const f=r.value,g=this.chosenSourceId.has(e)&&!t.some(b=>b.id===this.chosenSourceId.get(e));g&&this.chosenSourceId.delete(e),o(),r.value=f===y.FILE_SOURCE&&s?f:l(),p(),g&&r.value!==y.FILE_SOURCE&&i(z(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),a,d,h),n}aircraftPicker(){const e=this.sourcePicker("aircraft",zi,(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?F.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):F.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=X.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=y.LIVE_ROADS;static LIVE_RAILWAYS=y.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 o=document.createElement("select");o.id=t;const l=s.map(([d,h,c])=>{o.append(new Option(h,d));const u=document.createElement("span");return u.className="source-picker",u.dataset.kind=d,u.append(c),u});o.value=this.sourceKindShown.get(i)??s[0][0];const a=()=>{this.sourceKindShown.set(i,o.value);for(const d of l)d.hidden=d.dataset.kind!==o.value};o.addEventListener("change",a),a(),n.append(r,document.createTextNode(" "),o),e.replaceChildren(n,...l)}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} `),y.creditLink(z(ri,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),y.creditLink(z(Et,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:z(ft,this.chosenSourceId.get("elevation")).create(),imagery:z(at,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(z(zi,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new qt(z(Ni,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)<Ze&&Math.abs(i-this.namedCoordinates.lng)<Ze||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),bs))}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)<Ze&&Math.abs(i-s.lng)<Ze||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),bs))}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,o=this.ufoElement.sighting.event,l=this.ufoElement.sighting.observerTrack,a=this.ufoElement.currentTime,d=l.getInterpolatedPoseAt(a),h=d?.altitudeM!==void 0?r:void 0,c=h!==void 0?d.elevationM:Math.max(0,r-(this.groundElevationM??0)),u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),m=(u.frame&&p!==void 0?ye.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),f=this.numberOrUndefined(this.fNumberInput.value),g=this.filterSelect.value,b=le.byId(l.getLatestPoseAt(a-1)?.filter),v=g===le.NONE.id||g===""?b===le.NONE?void 0:le.NONE.id:g,I=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=I===u.exposureSeconds?void 0:I;const S=this.numberOrUndefined(this.focusDistanceInput.value),w=Math.abs(m-ye.fieldOfViewDeg(u))>.01||f!==u.fNumber||S!==void 0||v!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&c===0&&!w?l.removeKeyframeAt(a):l.addKeyframe(a,{lat:e,lng:t,elevationM:c,...h!==void 0?{altitudeM:h}:{},headingDeg:i,pitchDeg:s,rollDeg:n===0?void 0:n,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:m,fNumber:f,focusDistanceM:S,filter:v});const C=this.stringOrUndefined(this.placeNameInput.value.trim()),B=l.getInterpolatedPoseAt(0);o.place=e!==void 0&&t!==void 0?[{lat:B?.lat??e,lng:B?.lng??t,name:C}]:void 0;const A=this.plantingCentre();this.surroundings.placeChanged(A?.lat,A?.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&&!yt.isFirm(t))return;const s=yt.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&&yt.at(i,e)===t)return;const s=yt.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&&Bt({...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=q.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,q.renamed(e,s,q.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:gt.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??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...s]:s;e.sources=l.length>0?l: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={...re(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={...re(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;fe.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"||Re.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=Re.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=Re.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(F.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>kr?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,o={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)||kt))},l=this.registrationShown(n),a=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.fovDeg,d=this.referenceKindSelect.value;return d==="video"?{...a?Re.withKey(n,this.ufoElement.currentTime,o):n,kind:d,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:d,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:o,from:a?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=Q(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(Re.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=Q(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=Q(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:Er,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:kt},from:this.observerPositionNow(),...i};s.references=[...s.references,o],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((o,l)=>{const a=new FileReader;a.onload=()=>o(a.result),a.onerror=()=>l(a.error),a.readAsDataURL(r)})}else i=e.url;const s=this.ufoElement.sighting,n=Re.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??=M(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-BLs4DkTI.js");return{PictureRegistration:e}},__vite__mapDeps([25,3,1,4,5,6,7,8,9]),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:Re.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 o=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(o&&Math.hypot(o.x-e.x,o.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(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:this.pictureRegistration.aimOf(r)};const l=this.pictureRegistration.picturePointOf(r,s.registration,n);return l?{...o,picture:l}:o})),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)||kt,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 o=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,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 o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,n)+l,this.referenceLandmarksSelect.appendChild(o)}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);fe.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(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),s=i.findIndex(o=>o.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const o=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+o}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(o=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o,s,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,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(o=>o!==void 0)?n:void 0,r.filter(o=>o.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,o=h=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:h.x/n.width,v:h.y/n.height},r,i)),l=[];for(const h of n.pairs){const c=o(h.ghost),u=o(h.light),p=o({x:h.ghost.x+h.ghost.radius,y:h.ghost.y});!c||!u||l.push({ghost:c,light:u,ghostRadius:p?Math.hypot(p.x-c.x,p.y-c.y):0})}const a=n.centre?o(n.centre):void 0,d=n.cropped?o({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(l,a,d)}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(Re.rollOfPicture(s)??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(a=>a.t===n);if(r<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[a,d]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${a}`,{basis:"derived",rationale:o,of:this.rounded(d)})}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=Q(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 M(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,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}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:kt}})}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;fe.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:d}=await M(async()=>{const{TraceImport:h}=await import("./TraceImport-CntRHXoJ.js");return{TraceImport:h}},__vite__mapDeps([26,1]),import.meta.url);i=await d.fromBytes(await $s.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(d=>d.id));let r=1;const o=this.said.write(void 0,i.documentName??t,this.writingLanguage),l=i.traces.map(d=>{for(;n.has(`trace-${r}`);)r++;const h=`trace-${r}`;return n.add(h),{...d,id:h,title:d.title===void 0?void 0:this.said.write(void 0,d.title,this.writingLanguage),source:o}});s.traces=[...s.traces,...l],this.currentTraceId=l[0].id,this.refreshTraceList();const a=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(l.length)).replace("{name}",t)+a,this.ufoElement.refresh()}async exportFigures(e){const t=this.fileBase(),{GEO_EXPORT_TEXTS:i}=await M(async()=>{const{GEO_EXPORT_TEXTS:o}=await import("./GeoExportTexts-3a51cuxQ.js");return{GEO_EXPORT_TEXTS:o}},__vite__mapDeps([27,1]),import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:o}=await M(async()=>{const{KmlExport:a}=await import("./KmlExport-CX-tTjIv.js");return{KmlExport:a}},__vite__mapDeps([28,29,5,6,1,4,3,7,8,9]),import.meta.url),l=o.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([l],{type:"application/vnd.google-earth.kml+xml"}),`${t}.kml`);return}const{GeoJsonExport:n}=await M(async()=>{const{GeoJsonExport:o}=await import("./GeoJsonExport-C-daFhc2.js");return{GeoJsonExport:o}},__vite__mapDeps([30,29,5,6,1,4,3,7,8,9]),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 Rn){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(),Wr)}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=Pn(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 it(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===y.FILE_SOURCE;if(!e){const t=z(Ee,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new it(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(_.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=X.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=Ee.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==z(Ee,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new it(e.create())}else!e&&t!==void 0&&!Ee.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new it(z(Ee,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...Ee.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,y.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!xt(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?y.FILE_SOURCE:i?i.id:z(Ee,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=z(Ee,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&&!xt(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),fs))}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||!xt(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 o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput&&o!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title=this.fieldHints.get(o.id)??"");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&xt(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&&be(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=!_.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=Et[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(),fs)}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 o=await s.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${s.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.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=Bt(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=Bn(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?Yt.MUTED:Yt.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(),D.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(ot.opensPrecise(e.time)),this.endDate.setPrecise(ot.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)>qr;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),Kr))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ze&&Math.abs(e.lng-i)<Ze}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=z(ft,this.chosenSourceId.get("elevation")),n=await new ki(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 o=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime)?.altitudeM;this.syncElevationField(r,o)}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=Q(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(y.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(ot.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=re(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??fi)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??Fn)),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=Qi(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!==y.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 M(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:t}},__vite__mapDeps([12,13,14]),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"){F.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of _.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&_.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of _.NAMES){const n=_.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||_.put(s,e,_.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return ss.of(e,t,t==="thin"?Oe.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(y.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(y.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Ts(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=ss.of(this.ownJson(mi(e)),t,t==="thin"?Oe.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(y.weatherOf(this.fileTextApplied)),o={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 l=this.ufoElement.sighting.weatherSource;l===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):Ee.some(a=>a.id===l.id)&&this.askAboutWeather(o,l.name??l.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(l){this.showFileNote(l instanceof Ot?l.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=o=>this.rounded(o).toLocaleString(this.language,{maximumFractionDigits:1}),s=o=>o.x>=-.05&&o.x<=1.05&&o.y>=-.05&&o.y<=1.05;let n;if(e!==void 0){const o=(e%360+360)%360,l=[];for(let a=0;a<360;a+=y.COMPASS_STEP_DEG){const d=this.sceneElement.horizonPointAt(a);d&&s(d)&&l.push({...d,label:this.naming.point(a)})}n={label:this.messages.overlayHeading.replaceAll("{deg}",i(o)).replaceAll("{point}",this.naming.point(o)),compass:l}}let r;if(t!==void 0){const o=[[]];for(let l=0;l<=360;l+=y.HORIZON_STEP_DEG){const a=this.sceneElement.horizonPointAt(l);a&&Math.abs(a.x-.5)<1.5&&Math.abs(a.y-.5)<1.5?o[o.length-1].push(a):o[o.length-1].length>0&&o.push([])}r={line:o,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,o=a=>this.numberOrUndefined(a.value),l=(a,d=1)=>a===void 0?"?":a.toLocaleString(this.language,{maximumFractionDigits:d});if(t==="pitch")this.showOrientation(void 0,o(this.pitchInput)??0);else if(t==="heading")this.showOrientation(o(this.headingInput)??0,void 0);else if(t==="focalLength"){const a=Oe.fovOf(i,s),h=2*Jt.of(i.instrument,n.height,a).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",l(a)).replaceAll("{h}",l(h)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const a=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!a){e.hide();return}const d=a.bounds,c=[[o(this.apparentWidthInput),"°",1],[o(this.realWidthInput)," m",1],[o(this.objectDistanceInput)," m",0]].filter(([u])=>u!==void 0).map(([u,p,m])=>`${l(u,m)}${p}`).join(" · ");e.measure((d.x+d.width/2)/n.width,(d.y+d.height/2)/n.height,Math.max(d.width,d.height)*1.3/n.width,c)}else if(t==="windDirection"||t==="windSpeed"){const a=o(this.windDirectionInput)??0,d=a-(o(this.headingInput)??0);e.wind(d,r.overlayWind.replaceAll("{point}",this.naming.point(a)).replaceAll("{speed}",l(o(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=a=>{let d=-1;return a.forEach((h,c)=>{h<=i()&&(d=c)}),d===-1&&a.length>0?0:d};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const a=n(t().observerTrack.allKeyframes.map(d=>d.t));return a===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${a}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const a=t().timeline.allKeyframes,d=n(a.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId)).map(p=>p.t));if(d===-1||this.apparentWidthInput.value==="")return;const h=a.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId))[d],c=a.indexOf(h),u=h.shapes.findIndex(p=>p.sourceId===this.currentSourceId);return`timeline.keyframes.${c}.shapes.${u}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const o=document.createElement("div");o.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(o);const l=a=>a?.closest("label")??void 0;this.candidatesView=new ne({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const a=this.ufoElement.sighting.event,d=a.place?.[0];if(!d||a.time?.year===void 0||a.time.hour===void 0)return;const h=be(a.time,d.lng,a.utcOffsetHours);return h?{date:h,observer:{lat:d.lat,lng:d.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:a=>Ke(a,this.instrumentGain()),fieldLabels:()=>({time:l(s),heading:l(this.headingInput),size:l(this.apparentWidthInput),duration:l(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:a=>{const d=`${a}/${this.language}`;return this.poherMatrix?.key!==d&&(this.poherMatrix={key:d,loaded:Ue.load(a,this.language,h=>Je.json(h))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const a=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,d=this.sceneElement.satellitePassesDuring(a);return d.length>0?{passes:d,positionsAt:h=>this.sceneElement.satellitePositionsAt(h)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const a=this.ufoElement.sighting.interpretation;return[...a&&(a.bodies.length>0||Lt.computes(a,Dt.kinds()))?[{id:"own",label:this.said.read(a.title)??this.principalObserverLabel(),interpretation:a}]:[],...this.readings]},computed:a=>this.sceneElement.computedInterpretation(a),starName:a=>this.naming.star({name:a}),projectionAt:(a,d)=>this.sceneElement.bodyProjectionAt(a,d),variants:()=>this.ufoElement.sighting.variants,keep:a=>this.editVariants(d=>[...d,a]),remove:a=>this.editVariants(d=>d.filter((h,c)=>c!==a))},o)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,s=i.place?.[0];if(s&&i.time?.year!==void 0&&i.time.hour!==void 0){const d=be(i.time,s.lng,i.utcOffsetHours);d&&(t.sunAltitudeDeg=V("Sun",d,{lat:s.lat,lng:s.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const d=re(e,0);t.cloudCover=d.cloudCover,t.lightning=d.storm,t.lowVisibility=d.precipitationType!=="none"&&d.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const d=n.allKeyframes.filter(u=>u.shapes.some(p=>p.sourceId===r)),h=d.map(u=>({t:u.t,shape:n.getShapeAt(u.t,r)})).filter(u=>u.shape?.aim),c=n.getInterpolatedShapeAt(d[0]?.t??0,r);if(c?.aim&&(t.elevationDeg=c.aim.altitudeDeg),c?.angular){t.widthDeg=c.angular.widthDeg;const u=c.angular.heightDeg>0?c.angular.widthDeg/c.angular.heightDeg:1;t.round=c.kind==="oval"&&u>.8&&u<1.25}if(c?.brightness!==void 0&&(t.brightness=c.brightness),h.length>1){const u=(g,b)=>{const v=Math.PI/180,I=Math.sin(g.altitudeDeg*v)*Math.sin(b.altitudeDeg*v)+Math.cos(g.altitudeDeg*v)*Math.cos(b.altitudeDeg*v)*Math.cos((g.azimuthDeg-b.azimuthDeg)*v);return Math.acos(Math.max(-1,Math.min(1,I)))/v},p=h.slice(1).map((g,b)=>({deg:u(h[b].shape.aim,g.shape.aim),s:(g.t-h[b].t)/1e3}));t.sweepDeg=u(h[0].shape.aim,h[h.length-1].shape.aim);const m=p.reduce((g,b)=>g+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const f=(h[h.length-1].t-h[0].t)/1e3;if(f>0){t.speedDegPerS=m/f;const g=Math.max(...p.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const o=new Set(n.sourceIds.map(d=>n.groupMembers(d)?.[0]??d));o.size>0&&(t.count=o.size);const l=[...o].map(d=>n.getInterpolatedShapeAt(0,d)?.aim).filter(d=>d!==void 0);if(l.length>=3){const d=Math.PI/180,h=l.map(m=>({x:(((m.azimuthDeg-l[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*d),y:m.altitudeDeg}));let[c,u]=[h[0],h[1]];for(const m of h)for(const f of h)Math.hypot(m.x-f.x,m.y-f.y)>Math.hypot(c.x-u.x,c.y-u.y)&&([c,u]=[m,f]);const p=Math.hypot(c.x-u.x,c.y-u.y);t.aligned=p>0&&h.every(m=>Math.abs((u.x-c.x)*(c.y-m.y)-(c.x-m.x)*(u.y-c.y))/p<=Math.max(.5,p*.1))}const a=new Set([...o].map(d=>n.getInterpolatedShapeAt(0,d)?.color).filter(d=>d!==void 0));return a.size>0&&(t.colors=[...a]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(d=>d.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}static SCENE_HEIGHT_KEY="rr0-editor-scene-height";resizeScene(e){const t=this.shadow.querySelector(".app"),i=this.sceneElement,s=n=>{n===void 0?t.style.removeProperty("--rr0-scene-max-height"):t.style.setProperty("--rr0-scene-max-height",`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,n)))}px`);try{n===void 0?localStorage.removeItem(y.SCENE_HEIGHT_KEY):localStorage.setItem(y.SCENE_HEIGHT_KEY,t.style.getPropertyValue("--rr0-scene-max-height"))}catch{}};try{const n=localStorage.getItem(y.SCENE_HEIGHT_KEY);n&&/^\d+px$/.test(n)&&t.style.setProperty("--rr0-scene-max-height",n)}catch{}e.addEventListener("pointerdown",n=>{n.preventDefault();const r=n.clientY,o=i.getBoundingClientRect().height;e.setPointerCapture?.(n.pointerId),e.classList.add("dragging");const l=d=>s(o+d.clientY-r),a=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",l),e.removeEventListener("pointerup",a),e.removeEventListener("pointercancel",a)};e.addEventListener("pointermove",l),e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a)}),e.addEventListener("keydown",n=>{n.key!=="ArrowUp"&&n.key!=="ArrowDown"||(n.preventDefault(),s(i.getBoundingClientRect().height+(n.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>s(void 0))}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=o=>{const l=this.groupTabs.find(a=>a.getAttribute("aria-controls")===o);l&&this.toggleGroup(l,!0)},s=o=>()=>{this.touch(),this.armHistory(),o(),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:o=>this.pickEvent(Number(o)),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:o=>this.pickEvent(Number(o)),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:o=>this.pickEvent(Number(o)),add:s(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(o=>o.t),open:()=>i("group-weather"),add:s(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(o=>o.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"?ue.observerTrackIsExpanded(t):ue.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(d=>d.t)};const n=this.ufoElement.seekableDuration,r=d=>e==="observer"?q.isObserver(t,d):q.isPhenomenon(t,d),o=(t.events??[]).map((d,h)=>({event:d,index:h})).filter(({event:d})=>r(d)),l=new Set(o.map(({event:d})=>d.who)).size>1,a=o.map(({event:d,index:h})=>{const c=this.messages.events.kinds[d.eventType]??d.eventType;return{id:String(h),t:d.t,until:d.until??n,label:e==="phenomenon"&&l?`${this.shapesLabel(d.who??"")} · ${c}`:c}});return{times:[],spans:a}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(l=>l.id)),s=l=>q.partOf(l)?.element??l??"",n=(e.events??[]).map((l,a)=>({event:l,index:a})).filter(({event:l})=>i.has(s(l.who)));if(n.length===0||!ue.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(l=>l.track.map(a=>a.t)))].sort((l,a)=>l-a)};const r=this.ufoElement.seekableDuration,o=n.map(({event:l,index:a})=>{const d=t.find(p=>p.id===s(l.who)),h=q.partOf(l.who)?.part,c=this.messages.events.kinds[l.eventType]??l.eventType,u=[...t.length>1?[this.said.read(d?.title)??s(l.who)]:[],...h?[h]:[]];return{id:String(a),t:l.t,until:l.until??r,label:[...u,c].join(" · ")}});return{times:[],spans:o}}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??q.observerId(t);if(q.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 q.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(q.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=(l,a)=>[...a].map(d=>({t:d,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>{if(this.showsBodies){const d=this.eventMarks("bodies");return d.spans?d.spans.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.bodiesTrack,d.times)}const{spans:a}=this.eventMarks("phenomenon");return a?a.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(d=>!l||d.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(d=>d.t))},s=()=>{const{times:l,spans:a}=this.eventMarks("observer");return a?a.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.observerTrack,l)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=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 l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,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=Yt.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=Dt.kinds();if(Lt.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Lt.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(a=>a.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:o,opensMostLacking:l}=this;this.openSubgroup(r),this.sectionChosen=o,this.opensMostLacking=l}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){if(!this.paramSummaryBuilder)return;const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|"),s=JSON.stringify(this.ufoElement.sighting.account??null);if(i===this.paramSummarySignature){s!==this.assessedAccount?(this.assessedAccount=s,this.assessSoon()):this.assessmentsOwed&&this.ufoElement.playbackState!=="playing"&&this.assessSoon();return}this.assessedAccount=s,this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.assessSoon()}assessmentsOwed=!1;assessSoon(){if(this.ufoElement.playbackState==="playing"){this.assessmentsOwed=!0;return}this.assessmentsOwed=!1,this.runAssessments()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=y.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==s.group&&(i=void 0),e.includes(s.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=s.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=s.group==="assessment"?this.messages.assessmentGroup:s.group==="summary"?this.messages.summaryGroup:y.tabLabel(this.groupTabs[this.summaryPanelIndex(s.group)]),r.append(o),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),xs.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return this.panelIndex(e==="phenomenon"?"shape":e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]},"bg-information":{panel:"observer",fields:["accountSource"]},"bg-occupation":{panel:"observer",fields:["observerOccupationKind"]},"bg-relation":{panel:"observer",fields:["observersRelation"]},"bg-activity":{panel:"observer",fields:["observerActivity"]},"bg-age":{panel:"observer",fields:["observerAge"]},"bg-appearance":{panel:"observer",fields:["strangeness-appearance"]},"bg-movement":{panel:"observer",fields:["strangeness-movement"]},"bg-incongruity":{panel:"observer",fields:["strangeness-incongruity"]},"bg-close":{panel:"observer",fields:["strangeness-close"]},"bg-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-occupants":{panel:"observer",fields:["strangeness-beings"]}};assessmentChips=[];assessmentToken=0;assessedAccount="";async runAssessments(){const e=++this.assessmentToken,t=await new wn(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=s=>{const n=s.querySelector(".tab-badge");return n&&!n.hidden?Number(n.textContent):0},t=this.groupTabs.find(s=>this.isGroupOpen(s));let i=t&&e(t)>0?t:void 0;for(const s of this.groupTabs)e(s)>(i?e(i):0)&&(i=s);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
|
|
2699
|
-
`)}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=y.QUESTION_FIELDS[n];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[n,r]of Object.entries(y.QUESTION_FIELDS))for(const o of y.QUESTION_FIELDS[n].fields){const l=this.shadow.getElementById(o);if(!l)continue;const a=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",a),(a||l.title===this.messages.questionUnanswered)&&(l.title=a?this.messages.questionUnanswered:this.fieldHints.get(o)??"")}const i=new Map;let s;for(const[n,r]of Object.entries(y.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const a=l.classList.contains("missing-required");!a&&!l.classList.contains("wanted")||(a&&(s=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const n of this.groupTabs){const r=this.panelOf(n),o=i.get(r)??0,l=r===s,a=y.badgeOn(n);a.hidden=o===0,a.textContent=String(o),a.classList.toggle("optional",!l);const d=o===0?void 0:l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o));d?n.dataset.unanswered=d:delete n.dataset.unanswered,y.titleGroupTab(n)}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field,e.detail&&(t.title=e.detail);const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const n=document.createElement("span");n.className="param-chip-swatch",n.style.background=e.color,t.append(n)}const s=document.createElement("span");return s.className="param-chip-value",s.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(s),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(o=>o.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 o=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(l=>l.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&&fe.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:no(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(y.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,ge.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,ge.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(ge.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(ge.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),o=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),l={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-o)/2,width:r,height:o},a=n.ofBounds(l),d=s.kind==="oval"?{...s,bounds:l,angular:a}:{...s,bounds:l,angular:a,points:this.scalePoints(s,l)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:d}]),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={[le.NONE.id]:this.messages.filterNone,[le.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[le.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==le.ALL.length||le.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||le.NONE.id;this.filterSelect.replaceChildren();for(const r of le.ALL){const o=document.createElement("option");o.value=r.id,o.textContent=t(r),this.filterSelect.appendChild(o)}this.filterSelect.value=n}const s=this.ufoElement?.sighting?.instrument;for(const n of this.filterSelect.options){const r=!s||le.usableWith(le.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,s={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,video:this.messages.instrumentCategoryVideo,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},n=r=>{const o=this.naming.instrument(r),l=ye.unavailability(r,t);if(!l)return{id:r.id,label:o};const a=(l.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(l.from)).replace("{to}",String(l.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",o),hint:a}:{id:r.id,label:o,disabledReason:a}};this.instrumentSelect.choices=ye.CATEGORIES.map(r=>({label:s[r],children:Nn.filter(o=>o.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=y.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const n=Number(i[1]),r=Number(i[2]);return r>0?n/r:void 0}const s=Number(t);return Number.isFinite(s)&&s>0?s:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=Q(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??ye.fieldOfViewDeg(t),r=s?ye.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),Pt.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 o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),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 l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":y.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const h of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(h,yn.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const a=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const d=bt.byId(e.film);this.isoInput.placeholder=a?a.autoExposure?"auto":String(d?.iso??a.iso):"",this.setRowVisible(this.isoInput,a!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,a?.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=le.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=ye.fieldOfViewDeg(e),s=ye.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>Jr||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 Q(e,this.ufoElement.currentTime)?.fovDeg??ye.fieldOfViewDeg(e.instrument)}currentProjection(){return Jt.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=ge.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=Q(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?ye.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,o=s?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const a=2*En*e/l*i.heightMm,d=r*r/(o*a)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(d))}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),o=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))+o+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,f)=>Number(m.toFixed(f)),n=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??Gr,o=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),l=o!==void 0&&o<r,a=s(r,1),d=i?.angular?.widthDeg,h=i?.angular?.heightDeg,c=d!==void 0&&h!==void 0&&d>0&&h>0?{widthM:s(ge.sizeMAt(a,d),2),lengthM:s(ge.sizeMAt(a,d),2),heightM:s(ge.sizeMAt(a,h),2)}:void 0,u={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},p={t,...u,distanceM:a,...l?{onGround:!0}:{},...c?{sizeM:c}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:p}:{keyframe:p}}loadBodyEditor(){return this.bodyEditorLoading??=M(async()=>{const{BodyEditor:e}=await import("./BodyEditor-CRJFVGzZ.js");return{BodyEditor:e}},__vite__mapDeps([31,3,1,4,5,6,7,8,9,18,20]),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=Dt.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=Is.map(i=>At.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,o)=>{this.headingInput.value=String(this.rounded(r)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()},changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language))}));return[...e,...t]}buildSkyParts(){const e=this.shadow.getElementById("weather-tabs"),t=this.shadow.getElementById("sky-event-parts");if(!e||!t)return;const i=this.wantedSkyParts();for(const[s,n]of this.skyParts)if(!i.some(r=>r.key===s&&r.kind===n.kind)){if(n.tab.getAttribute("aria-expanded")==="true"){const r=this.subgroupTabs.find(o=>o.parentElement===e&&o!==n.tab);r&&this.openSubgroup(r)}n.tab.remove(),n.panel.remove(),this.subgroupTabs.splice(this.subgroupTabs.indexOf(n.tab),1),this.skyParts.delete(s)}for(const s of i){if(this.skyParts.has(s.key))continue;const n=document.createElement("button");n.className="subgroup-tab",n.type="button",n.setAttribute("aria-controls",s.id),n.setAttribute("aria-expanded","false");const r=document.createElement("span");r.id=`label-${s.id}`,this.nameSkyPart(r,s.titles),n.append(r),n.addEventListener("click",()=>this.openSubgroup(n)),e.append(n),this.subgroupTabs.push(n);const o=document.createElement("section");o.className="subgroup-panel",o.id=s.id,o.hidden=!0,o.setAttribute("aria-labelledby",r.id);const l=document.createElement("div");l.className="toolbar";const a=document.createElement("div");a.id=`${s.id}-editor`,l.append(a),o.append(l),t.before(o),this.skyParts.set(s.key,{...s,tab:n,label:r,panel:o})}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(gt.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:ge.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=Jt.of(i.instrument,ge.CANVAS_HEIGHT_PX,Oe.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const o=Oe.aimOf(i,e,r.shape.bounds),l=s.ofBounds(r.shape.bounds),{aim:a,...d}=r.shape;return{...r,shape:o?{...d,aim:o,angular:l}:{...d,angular:l}}}))}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},...Me.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(d=>d.value===e.id).label,o=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",l={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},a=s.map((d,h)=>{const c=e.partNames[h],u=c?`${r} ${o}, ${l[c]}`:`${r} ${o}`;return{sourceId:n[h],shape:{...d,title:this.said.write(void 0,u,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,a),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 o=r.shapes.filter(l=>t.includes(l.sourceId)).map(l=>{const{bounds:a}=l.shape;return{sourceId:i[t.indexOf(l.sourceId)],shape:{...l.shape,bounds:{...a,x:a.x+s,y:a.y+s}}}});o.length>0&&this.commitShapes(r.t,o)}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]??st,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:Ui.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:As}:{},windows:Cs(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(y.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(y.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(y.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(y.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await M(()=>import("./surroundingsSources-CVKKb8h6.js"),__vite__mapDeps([15,1,3,4,5,6,7,8,9]),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=y.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(o=>{const l=document.createElement("option");return l.value=o.id,l.textContent=o.name,l.title=o.credit,l}),r=new Option(this.messages.sourceFile,y.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(s,...n,r),this.surveyIds=t.map(o=>o.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==y.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?y.FILE_SOURCE:this.sceneryChoice===y.NO_SCENERY?y.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===y.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=X.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?Nt.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*li,t=Math.round(e/Qr*1e3);return{lights:Ui.byId("airliner")?.create(),track:[{t:0,eastM:-li,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:li,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=Wn(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?es[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(l=>l.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 o={...n.sizeM,...Object.fromEntries(Object.entries(s.sizeM).filter(([,l])=>l!==void 0).map(([l,a])=>[l,this.roundedMeters(a)]))};this.updateDecor({sizeM:o})}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=_i([...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=_i(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;fe.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=y.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!==y.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!==y.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 M(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([32,33]),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=bt.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=(l,a,d=!1)=>{const h=document.createElement("option");h.value=l,h.textContent=a,h.disabled=d,this.filmStockSelect.appendChild(h)};r("",this.messages.filmStockAny);const o=i.map(l=>({stock:l,gap:bt.gap(l,t,s)}));for(const{stock:l}of o.filter(a=>!a.gap))r(l.id,l.name);for(const{stock:l,gap:a}of o.filter(d=>d.gap)){const d=a.kind==="before"?this.messages.filmStockNotYet.replace("{from}",String(a.from)):this.messages.filmStockNoLonger.replace("{to}",String(a.to));r(l.id,`${l.name} (${d})`,l.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(bt.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 Rt(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?tt.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(nt.resolve(me.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(nt.resolve(me.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}=ts(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=Hi.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:$i.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Hi.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:me.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:es[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(o=>o.id===e.id?n:o),n}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(a=>a.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=tt.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const o=this.ufoElement.sighting;o.decor=o.decor.map(a=>a.id===s.id?tt.apply(a,r,t,n):a),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const l=o.decor.find(a=>a.id===s.id);t==="title"&&this.decorList.rename(l.id,this.decorLabel(l)),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?Ss.of(e,this.publishedParametersOf(e)):void 0,i=t&&nt.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(o=>o.key).join(",")}`;if(s===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=s;const n=e.id,r=new Rt(()=>this.ufoElement.sighting.decor.find(o=>o.id===n),o=>{const l=this.ufoElement.sighting;l.decor=l.decor.map(a=>{if(a.id!==n)return a;const d=structuredClone(a);return o(d),d})});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?be(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=V("Sun",i,t).altitudeDeg;return Ke(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new jn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Wi;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new ct(["en"]);tagNames=new ji({});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?be(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,re(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},o=e.skySources!==!1,l=[this.starsClause(s,r),o?this.showerClause(s,r):this.messages.skyByHand,this.cometClause(s,r),this.novaClause(s,r),this.eclipseClause(s,r),this.moonClause(s,r),o?this.satelliteClause(s,r):void 0,o?this.reentryClause(s,r):void 0,o?this.fireballClause(s,r):void 0,this.opticsClause(s,r),this.rainbowClause(s,r),this.glowClause(s,r)].filter(a=>a!==void 0);o||(this.showMeteorButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0),this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",l.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 kn.gainFor(e.instrument,{fNumber:Q(e,0)?.fNumber,fieldOfViewDeg:Oe.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=V("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Ke(i,s,n),o=d=>d.toLocaleString(void 0,{maximumFractionDigits:1});if(r<Vr)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,a=Math.abs(s)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(s>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(s))).replace("{eye}",o(Ke(i,0,n)));return r<=Gi?a:a+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Gi))}showerClause(e,t){const i=Ki.observedRatePerHour(Ki.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=Xt.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 o=Xt.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:Xt.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.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=Qt.brightestAt(e,t);if(!i||i.magnitude>Vi){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=qi.brightestAt(e,t);if(!i||i.magnitude>Vi){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=Sn.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=V("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),o=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} 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=V("Moon",e,t);if(i.altitudeDeg<=0||Ye(e).illuminatedFraction<.97)return;const s=[],n=Ve.distanceKm(e,t),r=Ve.relativeToMean(Ve.radiusAtKm(n)),o=n<=Ve.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Ve.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return o&&s.push(o.replace("{distance}",(Math.round(n/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(Ve.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Wt.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=ve.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=Ke(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(h=>h.peakMagnitude<=n),o=this.listed(r.map(h=>this.naming.satelliteClass(h)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),a=(i.trackedObjects??0).toLocaleString(),d=h=>h.replace("{height}",l).replace("{count}",a);return i.lowOrbitLit?r.length===0?d(this.messages.skySatellitesLit):d(this.messages.skySatellitesLitWith).replace("{eras}",o):d(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 a={key:n,status:"loading"};this.reentries=a,y.reentryArchive.candidates(i,s,t).then(d=>{a.status=d?"ready":"unavailable",a.candidates=d,this.reentries===a&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=ve.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(a=>a.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(a=>this.reentryText(a));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.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 o=s.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}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(a=>a.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(a=>a.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,o=(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)),l=this.starlinkTrain(i);return l?`${o}, ${l}`:o}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=V("Sun",i.peak.date,t);return s<=Ke(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:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,s]=[...t.entries()].sort((r,o)=>o[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=Q(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=be(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=>Zi.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Zi.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=be(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=re(this.ufoElement.sighting,0),s=V("Sun",e,t),n=V("Moon",e,t),r=vt.deckLitUntilDeg(vt.DECK_HEIGHT_M),o=s.altitudeDeg>-r,l=o?s:n;if(l.altitudeDeg<=-r)return;const a=i.highCloudCover;if(a===void 0||a<=0)return this.messages.skyOpticsNoIce;if(vt.strength(a,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const d=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,h=this.listed(vt.formsAt(l.altitudeDeg,r).map(u=>this.opticsFormName(u))),c=i.iceCrystalAlignment??fi;return this.messages.skyOpticsPossible.replace("{forms}",h).replace("{source}",d)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(c*100)))}rainbowClause(e,t){const i=re(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=V("Sun",e,t),n=V("Moon",e,t),r=s.altitudeDeg>0,o=r?s:n;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(ei.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const a=ei.formsAt(o.altitudeDeg);if(a.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(ei.primary().radiusDeg)));const d=this.listed(a.map(c=>this.bowFormName(c)));if(r)return this.messages.skyBowPossible.replace("{forms}",d);const h=Math.round(Ye(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",d).replace("{lit}",String(h))}glowClause(e,t){const i=V("Sun",e,t);if(i.altitudeDeg>ro)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 u=s.zodiacal.sunSeparationDeg<=O.CONE_SEPARATION_DEG;n.push((u?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),o=V("Moon",e,t),l=s.darkestSkyMagPerArcsec2<oo,a=this.ufoElement.sighting.lightPollution,d=pe.scatteringAt(90-o.altitudeDeg)*pe.moonOutput(pe.phaseAngleOf(Ye(e).illuminatedFraction),o.altitudeDeg)*pe.scatteredFraction(90),h=pe.artificialZenithNanolamberts(a)>d;if(l&&o.altitudeDeg>0&&!h){const u=Math.round(Ye(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(u)).replace("{sky}",r)}const c=pe.artificialZenithNanolamberts(a)>pe.twilightExcessNanolamberts(i.altitudeDeg);return l&&h&&c?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=V("Sun",e,t),s=V("Moon",e,t);return pe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(Ye(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new O;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<Qt.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=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Qt.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=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=qi.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(a=>a.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}=ts(e,this.ufoElement.currentTime),r=Math.hypot(i,s);if(r===0&&n===0)return;const o=Math.atan2(i,s)*180/Math.PI,l=Math.atan2(n-Xr-(Q(this.ufoElement.sighting,this.ufoElement.currentTime)?.elevationM??0),r)*180/Math.PI;this.headingInput.value=String(Math.round(o*10)/10),this.pitchInput.value=String(Math.round(l*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??y.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return Qi(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-qe.width/2,y:e.height/2-qe.height/2,width:qe.width,height:qe.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 Ei(this.ufoElement.sighting.timeline,new dr(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"})),D.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=ze.preferencesFor(this);this.preferences=t;const i=hi(t,ci),s=this.decidedLanguage===void 0;if(this.decidedLanguage=i,s){for(const h of this.skyParts.values())this.nameSkyPart(h.label,h.titles);this.applyPerceptionLabels()}const n=this.narrativeProvider.localize?.(i),[r,o,l,a]=await Promise.all([ys.load(i),i==="en"?{}:Ws(i),js(i),ir.load(i)]);if(await n,e!==this.localeToken)return;const d=i!==this.language;this.language=i,this.decorParameterTexts=a,this.naming=new Wi(l),this.said=new ct(t),this.tagNames=new ji(o),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new Yi(r,this.naming,this.said,this.tagNames,{messages:r,locale:this.language},this.decorParameterTexts),this.refreshParamSummary()),d?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===st&&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,o)=>{this.shadow.getElementById(n).setAttribute(r,o),r==="title"&&this.fieldHints.set(n,o)};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(y.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(y.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(Si))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,Ae.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 o=this.shadow.getElementById(n);o&&(o.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 o=this.shadow.getElementById(`label-${n}-settings`);o&&(o.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 Yi(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,Ae.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,r]of this.soundKindOptions)r.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e),this.refreshFileItems(),this.refreshSkyCandidates()}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])Ne.popover(this.shadow.getElementById(s),e.close);Ne.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),Ne.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),Ne.button(this.contextMenu,e.close,()=>this.hideContextMenu()),Ne.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,y.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 h=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,c=h?this.sceneElement.pickAt(h.x,h.y):void 0;this.beginCameraDrag(t,c?.kind==="decor"?c.id:void 0,c?.kind==="body"?c.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,o=this.ufoElement.playbackState==="playing",l=i==="shape";if(l)if(this.selectedSourceIds.size>1){const h=new ti(this.selectedMembers()),c=J.hitTestHandle({bounds:h.bounds(),angle:0},t);if(c==="rotate"){if(o)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(c){if(o)return;this.dragState={kind:"group-resize",group:h,handle:c},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(r,this.currentSourceId),c=h?.kind==="polygon"?J.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&c!==void 0){if(o)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:c},this.startDragListening();return}const u=h&&J.hitTestHandle(h,t);if(h&&u){if(o)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const a=this.ufoElement.shapeAt(t.x,t.y,It);if(!a){const h=s==="ground"?this.ndcOf(e):void 0,c=h?this.sceneElement.pickAt(h.x,h.y):void 0;if(c?.kind==="body"&&c.id!==void 0){o?this.showBody(c.id):this.beginCameraDrag(t,void 0,c.id);return}const u=c?.kind==="decor"?c.id:void 0;if(u!==void 0){o?(this.selectDecor(u),this.revealDecorPanel()):this.beginCameraDrag(t,u);return}o||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(a.sourceId):this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),o||!l)return;const d=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===a.sourceId?a.shape:n.getInterpolatedShapeAt(r,h)??a.shape}));this.dragState={kind:"move",sources:d,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,o)=>n.indexOf(r)-n.indexOf(o)).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,o=n?.kind==="polygon"&&J.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId,shape:n}:this.ufoElement.shapeAt(t.x,t.y,It);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),a=l?this.ufoElement.sighting.decor.find(d=>d.id===l):void 0;a&&this.showDecorContextMenu(e.clientX,e.clientY,a)}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(u=>this.selectedSourceIds.has(u)),n=i.length<=s.length,r=s.length>0&&i.slice(i.length-s.length).every(u=>this.selectedSourceIds.has(u)),o=s.length>0&&i.slice(0,s.length).every(u=>this.selectedSourceIds.has(u));this.contextBringToFrontButton.disabled=n||r,this.contextSendToBackButton.disabled=n||o,this.contextBringToFrontButton.title=n?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=n?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const a=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),d=this.selectedSourceIds.size===1&&a?.kind==="polygon";this.contextAddVertexButton.disabled=!d,this.contextAddVertexButton.title=d?"":this.messages.notAPolygon;const h=d&&this.contextMenuPoint?J.hitTestVertex(a,this.contextMenuPoint):void 0,c=d&&a.points.length<=xn;this.contextDeleteVertexButton.disabled=!d||h===void 0||c,this.contextDeleteVertexButton.title=d?c?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 o=this.said.read(s.title)??s.id,l=this.messages;r.textContent=`${o} — ${n>=.995?l.masksBodyFully:n>.005?l.masksBodyPartly.replace("{share}",String(Math.round(n*100))):l.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(o=>o!==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=J.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=J.hitTestVertex(i,e);if(s===void 0)return;const n=J.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(Tt,(e.maxX-e.minX)/2*t.width),s=Math.max(Tt,(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,f)=>Math.max(m,(i.bottom-f.top)*s),0),o=Mt,l=Mt+jr,a=t.width-Mt,d=t.height-r-Mt,h=Math.max(e.x,o),c=Math.max(e.y,l),u=Math.min(e.x+e.width,a),p=Math.min(e.y+e.height,d);return u-h<Tt||p-c<Tt?e:{x:h,y:c,width:u-h,height:p-c}}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=J.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 c=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,u=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,p=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:p.headingDeg,pitchDeg:p.pitchDeg+u,rollDeg:p.rollDeg+c}:{headingDeg:p.headingDeg+c,pitchDeg:p.pitchDeg,rollDeg:p.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:s,startPointer:n,startSizeM:r,handle:o}=t,l=(c,u)=>Math.max(.05,Math.abs(c)/Math.max(1,Math.abs(u))),a=o==="e"||o==="w",d=o==="n"||o==="s",h=a?l(i.x-s.x,n.x-s.x):d?l(i.y-s.y,n.y-s.y):l(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:d?r.widthM:r.widthM*h,lengthM:d?r.lengthM:r.lengthM*h,heightM:a?r.heightM:r.heightM*h})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:ai};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:Zr};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=$i.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:tt.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(o=>o.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,It)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=tt.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),o=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,l=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,o);return!n||!l?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:l,grabHeightM:o,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&&is(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&is(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,o=t.y-n.y,l=s.map(({sourceId:a,original:d})=>({sourceId:a,shape:{...d,bounds:{...d.bounds,x:d.bounds.x+r,y:d.bounds.y+o}}}));this.commitShapes(i,l)}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,o=J.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:o}])}else{const{kind:s,sourceId:n,original:r,handle:o}=this.dragState,l=s==="resize"?J.resizeShape(r,o,t):J.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:l}])}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)<Yr)return;this.cameraDragState.moved=!0}const o=s+(t.x-i.x)*ai,l=Math.max(-90,Math.min(90,n-(t.y-i.y)*ai));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver(),this.rounded(o)!==this.rounded(s)&&(this.cameraDragState.headingTurned=!0),this.rounded(l)!==this.rounded(n)&&(this.cameraDragState.pitchTurned=!0),this.showOrientation(this.cameraDragState.headingTurned?o:void 0,this.cameraDragState.pitchTurned?l:void 0),this.showViewDragHint(e.altKey);const a=this.ufoElement.sighting.observerTrack,d=this.ufoElement.currentTime,h=a.allKeyframes.find(c=>c.t===d);h&&h.viewOnly===!0!==e.altKey&&(a.setViewOnly(d,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?io: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)*to*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)*eo*t,o=i*Math.PI/180,l=Ys(Math.sin(o)*r,-Math.cos(o)*r,s,n);this.latInput.value=l.lat.toFixed(7),this.lngInput.value=l.lng.toFixed(7);const a=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(a,this.plantingCentre()),this.surroundings.walked(l.lat,l.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=Es(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(l,a)=>Math.round((l-a)*1e3)/1e3,o=this.ufoElement.sighting;o.decor=o.decor.map(l=>({...l,eastM:r(l.eastM,s),northM:r(l.northM,n),...l.track?{track:l.track.map(a=>({...a,eastM:r(a.eastM,s),northM:r(a.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(Ji,i.width-Pe);break;case"ArrowRight":i.width+=Pe;break;case"ArrowUp":i.height=Math.max(Ji,i.height-Pe);break;case"ArrowDown":i.height+=Pe;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Pe;break;case"ArrowRight":i.x+=Pe;break;case"ArrowUp":i.y-=Pe;break;case"ArrowDown":i.y+=Pe;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 ti(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 l=r?this.bodyCanvasBounds():void 0,a=l&&J.hitTestHandle({bounds:l,angle:0},t);if(a)return this.cursorForHandle(a,0);const d=this.ndcOf(e),h=d&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(d.x,d.y):void 0;return r&&h?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const l=this.decorCanvasBounds(),a=l&&J.hitTestHandle({bounds:l,angle:0},t);if(a)return this.cursorForHandle(a,0);const d=this.editableDecor();if(d&&!this.ufoElement.shapeAt(t.x,t.y,It)&&this.grabsDecor(e,t,d))return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=J.hitTestHandle({bounds:new ti(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=s.getInterpolatedShapeAt(n,this.currentSourceId);if(l?.kind==="polygon"&&J.hitTestVertex(l,t)!==void 0)return"vertex";const a=l&&J.hitTestHandle(l,t);if(l&&a)return this.cursorForHandle(a,l.angle)}return s.hitTest(n,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${J.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(Ds(this.buildPrototype({x:0,y:0,width:qe.width,height:qe.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 ao={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},ws="rr0-sighting-editor";function zs(){Os(),ks(),_s(),mr(),ur(),br(),Ms(),customElements.get(ws)||customElements.define(ws,y)}const bi="rr0-case-editor",lo=`
|
|
2699
|
+
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await M(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-3U8M50_n.js");return{ModelThumbnails:i}},__vite__mapDeps([2,3,1,4,5,6,7,8,9,10]),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 o=()=>{const a=++n,d=e.selectedOptions[0],h=e.value===""?i?.current():void 0,c=JSON.stringify([e.value,d?.textContent,h?.url,h?.title,this.messages().choose,[...e.options].map(m=>m.value).join()]);if(c===r){--n;return}r=c,s.replaceChildren();const u=document.createElement("span");u.textContent=`${h?h.title||h.url:d?.textContent??""} …`,s.title=this.messages().choose,s.append(u);const p=e.value;(h?Promise.resolve({url:h.url}):t(p)).then(m=>ht.pictureOf(m)).then(m=>{if(!m||a!==n)return;const f=new Image;f.src=m,f.alt="",s.prepend(f)})};e.addEventListener("change",o),new MutationObserver(o).observe(e,{childList:!0,subtree:!0});const l=i&&{current:()=>i.current(),apply:a=>{i.apply(a),o()}};s.addEventListener("click",()=>void this.open(e,t,l)),o()}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=ht.STYLE,t.append(i)}open(e,t,i,s){const n=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const o=document.createElement("div");o.className="model-picker",o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true");const l=document.createElement("h2");l.textContent=n.title;const a=document.createElement("button");a.type="button",a.className="model-picker-close",a.setAttribute("aria-label",n.close),a.title=n.close,a.innerHTML=D.CLOSE;const d=document.createElement("header");d.append(l,a);const h=document.createElement("div");h.className="model-picker-body",o.append(d,h),r.append(o);const c=()=>{r.remove(),document.removeEventListener("keydown",u,!0),M(async()=>{const{ModelViewer:x}=await import("./ModelViewer-Cnxj0Oi9.js");return{ModelViewer:x}},__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),import.meta.url).then(({ModelViewer:x})=>x.end())},u=x=>{x.key==="Escape"&&(x.stopPropagation(),c())},p=i?.current(),m="\0address",f=x=>x===m&&p?Promise.resolve({url:p.url}):t(x),g=x=>{if(c(),s){x!==m&&s(x);return}x===m||x===e.value||(e.value=x,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const v=new Map,I=x=>{const C=document.createElement("button");C.type="button",C.className="model-card",C.dataset.value=x.value,C.setAttribute("aria-pressed",String(!s&&(x.value===m||x.value===e.value&&!p)));const B=document.createElement("div");B.className="model-thumb";const A=document.createElement("span");if(A.className="model-name",A.textContent=x.textContent,C.append(B,A),x.title){const E=document.createElement("span");E.className="model-credit",E.textContent=x.title,C.append(E)}f(x.value).then(E=>ht.pictureOf(E)).then(E=>{if(!E)return;const T=new Image;T.src=E,T.alt="",B.append(T)});let te,Z=!1;const Ce=()=>{Z&&!(te&&!te.active)||(Z=!0,Promise.all([f(x.value),M(()=>import("./ModelViewer-Cnxj0Oi9.js"),__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),import.meta.url)]).then(([E,{ModelViewer:T}])=>{!E||!Z||(te=T.show(B,E))}).catch(()=>{}))},je=()=>{Z=!1,te?.stop(),te=void 0};return v.set(C,Ce),C.addEventListener("pointerenter",Ce),C.addEventListener("focus",Ce),C.addEventListener("pointerleave",()=>{document.activeElement!==C&&je()}),C.addEventListener("blur",je),C.addEventListener("click",E=>{if(te?.consumeDrag()){E.preventDefault();return}g(x.value)}),C},S=()=>(b=document.createElement("div"),b.className="model-picker-grid",h.append(b),b);if(p){const x=new Option(p.title||p.url,m);x.title=[p.author,p.license].filter(Boolean).join(" — "),S().append(I(x))}for(const x of Array.from(e.children))if(x instanceof HTMLOptGroupElement){const C=document.createElement("h3");C.textContent=x.label,h.append(C);const B=S();for(const A of Array.from(x.children))B.append(I(A));b=void 0}else x instanceof HTMLOptionElement&&(b??S()).append(I(x));i&&this.addAddressForm(d,a,o,h,i,n,c),a.addEventListener("click",c),r.addEventListener("click",x=>{x.target===r&&c()}),document.addEventListener("keydown",u,!0),this.root.append(r);const w=o.querySelector('.model-card[aria-pressed="true"]');(w??a).focus(),w&&v.get(w)?.()}addAddressForm(e,t,i,s,n,r,o){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const a=document.createElement("form");a.className="model-picker-address",a.hidden=!0;const d=(v,I,S="")=>{const w=document.createElement("label"),x=document.createElement("span");x.textContent=v;const C=document.createElement("input");return C.type=I,C.placeholder=S,w.append(x,C),a.append(w),C},h=d(r.addressUrl,"url","https://…/model.glb"),c=d(r.addressName,"text"),u=d(r.addressAuthor,"text"),p=d(r.addressLicense,"text","CC0 1.0"),m=d(r.addressSource,"url","https://…"),f=document.createElement("p");f.textContent=r.addressIncomplete;const g=document.createElement("button");g.type="submit",g.className="model-picker-use",g.textContent=r.addressUse,a.append(f,g),i.insertBefore(a,s);const b=()=>{g.disabled=h.value.trim()==="",f.hidden=h.value.trim()===""||c.value.trim()!==""&&p.value.trim()!==""};for(const v of[h,c,u,p,m])v.addEventListener("input",b);l.addEventListener("click",()=>{const v=a.hidden;if(a.hidden=!v,l.setAttribute("aria-expanded",String(v)),!v)return;const I=n.current();h.value=I?.url??"",c.value=I?.title??"",u.value=I?.author??"",p.value=I?.license??"",m.value=I?.source??"",b(),h.focus()}),a.addEventListener("submit",v=>{v.preventDefault(),h.value.trim()!==""&&(n.apply({url:h.value.trim(),title:c.value.trim(),author:u.value.trim(),license:p.value.trim(),source:m.value.trim()}),o())}),b()}}class ki{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=ki.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 _r{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 ae{static STEP_MS=100;static plan(e){const t=ae.routeOf(e),i=Te.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const o=new Set,l=(c,u,p,m)=>{if(Math.abs(c.radiusM-m)>=m*.1)return!1;const{x:f,z:g}=Es(u,p,c.lat,c.lng);return Math.hypot(f,g)<Te.rebuildDistanceFor(m)};for(let c=0;;c=Math.min(s,c+ae.STEP_MS)){const u=Q(e,c);if(u?.lat!==void 0&&u.lng!==void 0){const p=Te.groundRadiusFor(u.elevationM??0),m=Te.patchRadiusFor(p,u.elevationM??0),f=Math.max(m,i);(!r||!l(r,u.lat,u.lng,f))&&(r=n.find(g=>l(g,u.lat,u.lng,f)),r||n.push(r={lat:u.lat,lng:u.lng,radiusM:f})),f<p&&o.add(r)}if(c>=s)break}const a=e.weatherTrack.allKeyframes.map(c=>c.weather.visibilityKm).filter(c=>c!==void 0),d=Te.farRingRadiusFor(a.length>0?Math.max(...a):void 0);for(const c of o)n.push({lat:c.lat,lng:c.lng,radiusM:d,far:!0});if(d>Te.FAR_RING_RADIUS_M)for(const c of[...n])!c.far&&!o.has(c)&&c.radiusM<d&&n.push({lat:c.lat,lng:c.lng,radiusM:d,far:!0});const h=Is.map(c=>At.of(c)).filter(c=>c.reachM&&At.eventsOf(e.skyEvents,c).length>0);if(h.length>0){const c=u=>Math.max(...h.map(p=>p.reachM(At.eventsOf(e.skyEvents,p),u)));for(const u of[...n])u.far||o.has(u)||n.some(p=>p.far&&p.lat===u.lat&&p.lng===u.lng)||Te.needsFarRing(u.radiusM,0,c(u))&&n.push({lat:u.lat,lng:u.lng,radiusM:d,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),o=l=>n?.(l,i.length);switch(e){case"relief":{const l=ae.routeOf(t),a=[];for(const[c,u]of i.entries()){try{const p=await s.elevation.getElevationGrid(lt.boundsOf(u),{width:Pi,height:Pi},{route:l});a.push({...u,grid:p})}catch(p){console.warn("Relief not snapshots for a patch:",p)}o(c+1)}if(a.length===0)return;const d=s.elevationCredit;return{bytes:await an.encode({takenOn:r,attribution:d,patches:a}),attribution:d,takenOn:r,answered:a.length,patches:i.length}}case"imagery":{const l=new Ci,a=z(at,s.imagery),d=a.create(l.fetch);let h=0;for(const[p,m]of i.entries()){try{await d.getImageryTexture(lt.boundsOf(m),{width:Oi,height:Oi}),h++}catch(f){console.warn("Imagery not snapshots for a patch:",f)}o(p+1)}if(l.tiles.size===0)return;const c=d.attribution;return{bytes:await Ri.encode({takenOn:r,source:a.id,attribution:c,patches:[...i],tiles:l.tiles}),attribution:c,takenOn:r,answered:h,patches:i.length}}case"roads":return ae.vector(s.roads,i,r,o,(l,a)=>l.getRoads(a),l=>l.contemporary);case"water":return ae.vector(s.water,i,r,o,(l,a)=>l.getWater(a));case"railways":return ae.vector(s.railways,i,r,o,(l,a)=>l.getRailways(a),l=>l.contemporary)}}static mapGround(e){const t=ln.of(e);return t&&Bi.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=ae.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Ci,r=z(at,t),o=r.create(n.fetch),l=Bi.IMAGERY_PX;try{await o.getImageryTexture(i,{width:l,height:l})}catch(h){console.warn("Map imagery not snapshots:",h);return}const a=o.attribution;return{bytes:await Ri.encode({takenOn:s,source:r.id,attribution:a,patches:[],map:{bounds:i,pixels:l},tiles:n.tiles}),attribution:a,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const o=[];for(const[d,h]of t.entries()){if(h.radiusM<=Te.ROADS_MAX_RADIUS_M)try{o.push({...h,items:await n(e,lt.boundsOf(h))})}catch(c){console.warn("Not snapshots for a patch:",c)}s(d+1)}if(o.length===0)return;const l={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:o};return{bytes:new TextEncoder().encode(JSON.stringify(l)),attribution:e.attribution,takenOn:i,answered:o.length,patches:t.length}}}class j{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:j.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&j.isInline(t.src)}annex(e){const t=this.host.sighting().snapshots?.[e];return t?.src!==void 0?t:void 0}isLive(e){return X.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 X.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,o=r&&j.isInline(i.src);this.sourceInput.url=r?o?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&&!o?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!j.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 M(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:r}},__vite__mapDeps([12,13,14]),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 j.describe(e,n)}}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}de.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}F.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await M(async()=>{const{InputFileElement:s}=await import("./rr0-ufoathome.mjs").then(n=>n.J);return{InputFileElement:s}},[],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 j.describe(e,t)}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}const o=n!==void 0&&j.isInline(n.src),l=o?j.dataUrl(e,t):n?.src??X.annexName(this.host.base(),e);o||de.hold(this.address(l),t),s[e]={...s[e]?.live?{live:!0}:{},src:l,...r},F.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${l}`),this.setSnapshots(s)}async setStorage(e,t){const i={...this.host.sighting().snapshots??{}},s=this.annex(e);if(!s||j.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=j.dataUrl(e,n):(r=X.annexName(this.host.base(),e),de.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=j.isInline(t.src)?X.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:j.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(j.isZip(e)){const{unzipSync:s}=await M(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 de.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:${j.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&&!j.isInline(i)?j.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,ae.plan(this.host.sighting()),this.host.sources(),s))?F.show(this.note,void 0):F.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 X.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||ae.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=h=>X.isLive(i,h),r=h=>i[h]?.src!==void 0?i[h]:void 0;for(const h of X.NAMES)!i.live&&i[h]?.live&&(i[h]={live:!0});const o=ae.plan(t);let l;for(const h of X.TERRAIN){if(n(h))continue;const c=r(h);if(o.length>0&&(!c||c.refresh||!await this.fits(h,c,o))&&await this.take(h,i,o,l??=this.host.sources(),e)){await this.keep(r(h),s);continue}c?.refresh&&(i[h]={...c,refresh:void 0}),r(h)&&await this.keep(r(h),s)}if(!n("map")){const h=r("map");ae.mapGround(t)!==void 0&&(!h||h.refresh||!await this.fitsMap(h))&&await this.takeMap(i,l??=this.host.sources(),e)?await this.keep(r("map"),s):h&&(h.refresh&&(i.map={...h,refresh:void 0}),await this.keep(r("map"),s))}const a=this.host.upperAirHeard(),d=r("upperAir");if(!n("upperAir")&&a&&(!d||d.refresh)){const h=new Date().toISOString().slice(0,10),c={version:1,takenOn:h,attribution:a.answer.source.name,answers:[a]},u=new TextEncoder().encode(JSON.stringify(c)),p=this.place("upperAir",d?.src,e,u);i.upperAir={src:p,takenOn:h,attribution:a.answer.source.name},j.isInline(p)||s.set(p,u)}else d&&!n("upperAir")&&(d.refresh&&(i.upperAir={...d,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),o=await ae.freeze(e,this.host.sighting(),i,s,(l,a)=>F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(l)).replaceAll("{of}",String(a))));return F.show(this.note,void 0),o?(t[e]={src:this.place(e,t[e]?.src,n,o.bytes),takenOn:o.takenOn,attribution:o.attribution},!0):!1}async takeMap(e,t,i){F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await ae.freezeMap(this.host.sighting(),t.imagery);return F.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=ae.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await de.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&<.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 de.zip(s))["index.json"])).patches:(await de.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(o=>o.radiusM<=Te.ROADS_MAX_RADIUS_M);return lt.samePatches(n.map(({lat:o,lng:l,radiusM:a})=>({lat:o,lng:l,radiusM:a})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&j.isInline(t))return j.dataUrl(e,s);const n=t??X.annexName(i,e);return de.hold(this.address(n),s),n}async keep(e,t){if(!j.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return de.bytes(this.address(e.src))}address(e){return de.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of X.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=X.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 jt{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,F.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[_.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 ct(ze.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:_.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=mi(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:$e.CURRENT.sighting,takenOn:i,attribution:s,..._.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)??_.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(l=>{if(!l.ok)throw new Error(String(l.status))})}catch{const l={...this.host.sighting().snapshots??{}};l[e]={...l[e]??{},src:t.url},F.show(this.note,void 0),this.write(e,l);return}let i;try{const{InputFileElement:l}=await M(async()=>{const{InputFileElement:d}=await import("./rr0-ufoathome.mjs").then(h=>h.J);return{InputFileElement:d}},[],import.meta.url),a=await l.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=$e.recording(JSON.parse(new TextDecoder().decode(a))),typeof i!="object"||i===null||_.KEYS[e].every(d=>i[d]===void 0))throw new Error("Not this section")}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...mi(s)};if(e==="decor")_.put(e,n,"timeline"in i?_.taken(e,i):i);else for(const l of _.KEYS[e])n[l]=i[l];const r=Ts(n);jt.copy(e,r,s);const o={...s.snapshots??{}};t.url?o[e]={...o[e]??{},src:t.url}:o[e]=o[e]??{},F.show(this.note,void 0),this.write(e,o)}write(e,t){this.host.sighting().snapshots=X.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 _.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 Hr{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 $r=he.point("timeZone").provide(he.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new Hr}]);class oi{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 K{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=K.select("observerOccupationKind");graduate=K.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=K.select("observersRelation");activity=K.select("observerActivity");factors=new Map(Kn.map(e=>[e,K.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){Ae.register(),e.append(this.label(this.occupationKind,d=>[d.occupationKind,d.occupationKindHint]),this.label(this.graduate,d=>[d.graduate]));const n=this.label(this.enquiryMinutes,d=>[d.enquiryMinutes,d.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,d=>[d.relation]),this.label(this.activity,d=>[d.activity]));const o=Object.assign(document.createElement("h3"),{className:"section-title"});o.append(this.strangenessTitle),i.append(o,this.strangenessIntro,...[...this.factors].map(([d,h])=>this.label(h,c=>[c.factors[d],c.factorHints[d]])));const l=[["yes","yes"],["no","no"]],a=d=>d.map(h=>[h,h]);K.choices(this.occupationKind,"",a(Object.keys(oi.OCCUPATIONS))),K.choices(this.graduate,"",l),K.choices(this.relation,"",a(oi.RELATIONS)),K.choices(this.activity,"",a(oi.ACTIVITIES));for(const d of this.factors.values())K.choices(d,"",l);for(const d of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])d.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,K.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),K.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),K.choices(this.relation,e.unknown,Object.entries(e.relations)),K.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)K.choices(i,K.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=K.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=K.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=K.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:K.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);Ae.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 It=new Set;Ms();In();Ls.register();const qe={width:48,height:28},Wr=2500,Tt=40,Mt=10,jr=30,Gr=10,fs=600,bs=900,Ze=2e-4,Kr=900,Vr=-1.46,qr=3,ai=.2,Zr=.5,Yr=3,Jr=.01,Xr=1.6,li=2e3,Qr=250,vs=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),eo=1,to=5,io=10,Pe=4,st="ufo-1",so={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function no(k){return k.kind==="oval"?"oval":"polygon"}const ro=-6,oo=21;class y extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=$r[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new _r;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;exportKmlButton;exportGeoJsonButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;saidInterviews;candidatesView;sectionFolds;snapshotsPanel;sectionFilePanel;eventsPanel;aroundPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;aircraftStatus=Object.assign(document.createElement("span"),{className:"source-status"});aircraftFlights;aircraftFlightsShownAt=0;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=Ur();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 it(Nr());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;static FIELDS_OF_PATH={time:["obs-time","obs-time-native"],"place.locations.0.lat":["lat"],"place.locations.0.lng":["lng"]};markBeyondKnown(e){for(const{field:t,title:i}of this.markedBeyondKnown)t.removeAttribute("aria-invalid"),i===null?t.removeAttribute("title"):t.setAttribute("title",i);this.markedBeyondKnown=[];for(const{path:t,why:i}of e)for(const s of y.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?dn.boundsOf(e.time):void 0;t?.setBounds(i?{...i,...e.hour?{adjust:e.hour}:{}}:void 0);for(const[s,n]of[["lat",e.lat],["lng",e.lng]]){const r=this.shadow.getElementById(s);if(r&&(this.numberBounds.set(r,n),r.min=n?String(n[0]):"",r.max=n?String(n[1]):"",!this.boundedFields.has(r))){this.boundedFields.add(r);const o=()=>{const l=this.numberBounds.get(r),a=Number(r.value);if(!l||r.value===""||!Number.isFinite(a))return;const d=Math.min(Math.max(a,l[0]),l[1]);d!==a&&(r.value=String(d))};r.addEventListener("change",o,{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 qt;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=We.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...so};currentSourceId=st;selectedSourceIds=new Set([st]);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(vs.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;vs.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>${ar}</style>${or}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const a of this.shadow.querySelectorAll(Ft))a.build();for(const a of this.shadow.querySelectorAll($t))a.build();for(const a of this.shadow.querySelectorAll(Si))a.build();for(const a of this.shadow.querySelectorAll(xi))a.build();this.sceneElement=document.createElement(hn),this.sceneElement.addEventListener("observermapchange",a=>{this.ufoElement.sighting.observerMap=a.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",a=>{const{lat:d,lng:h}=a.detail;this.latInput.value=String(Number(d.toFixed(6))),this.lngInput.value=String(Number(h.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 dt(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const a of[this.timeStartLabel,this.timeEndLabel])a.addEventListener("click",()=>this.switchTimeDisplay()),a.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($t),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 W(this.shadow);const t=this;this.witnessErrorView=new Ps({get sighting(){return t.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:a=>{const d=this.ufoElement.sighting,{conditions:h,...c}=d.account??{},u={...c,...a?{conditions:a}:{}};d.account=Object.values(u).some(p=>p!==void 0)?u:void 0},recordingJson:()=>this.sightingData,valueSources:()=>this.valueSources(),lawsChanged:()=>{this.sceneElement.confrontationTolerance=cn.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new wi(this.shadow.getElementById("timeline-tracks"),a=>this.goToMark(a),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",a=>{a.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new Bs(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",a=>{const d=a.target.id;y.SCENE_LINKED.includes(d)&&this.setActiveSceneField(d)}),this.shadow.addEventListener("focusout",a=>{const d=a.relatedTarget;(!d||!y.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 K(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${xi}[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(y.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 j(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:(a,d)=>this.download(a,d)}),this.sectionFilePanel=new jt(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,d)=>this.download(a,d),changed:a=>{if(this.touch(),this.ufoElement.refresh(),a==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),a==="place"&&this.syncPlaceNameField(),a==="lightPollution"){const d=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=d===void 0?"":String(d),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const i={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:a=>this.goToMark(a),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const a=this.ufoElement.sighting.timeline;return a.sourceIds.includes(this.currentSourceId)?a.topOf(this.currentSourceId):void 0},shapesLabel:a=>this.shapesLabel(a),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:a=>this.naming.point(a),lookedAt:()=>{const a=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return a?.headingDeg===void 0||a.pitchDeg===void 0?void 0:{azimuthDeg:a.headingDeg,altitudeDeg:a.pitchDeg}},bodyLabel:a=>{const d=this.ufoElement.sighting.interpretation?.bodies.find(h=>h.id===a);return this.said.read(d?.title)??a},valueSources:()=>this.valueSources()};this.eventsPanel=new Se(this.shadow.getElementById("events-section"),i,void 0),this.phenomenonEventsPanel=new Se(this.shadow.getElementById("phenomenon-events-section"),i,void 0,"phenomenon"),this.bodiesEventsPanel=new Se(this.shadow.getElementById("bodies-events-section"),i,void 0,"bodies"),this.aroundPanel=new tr(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 a=Number(this.samplingRateInput.value);i.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(a)&&a>0?a:void 0,ue.refresh(this.ufoElement.sighting),i.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.snapshotsPanel.localize(this.messages),this.sectionFilePanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",a=>{a.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 lr(this.shadow.getElementById("aircraft-flights"),a=>this.aimAtFlight(a),a=>this.naming.point(a)),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 fe({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:a=>`option-decor-${a}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectDecor(a),onAdd:a=>this.addDecor(a),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 fe({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:a=>this.selectObserver(a),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 ie(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:a=>this.setPlantedDecor(a),kindName:a=>this.decorList.kindLabel(a),cite:a=>this.citeSource(a),busy:(a,d)=>this.sceneElement.setBusy(a,d),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(a=>({lat:a.pose.lat,lng:a.pose.lng})).filter(a=>typeof a.lat=="number"&&typeof a.lng=="number")},this.messages,async(a,d)=>this.surroundingsProvider?this.surroundingsProvider.covers(a,d)?this.surroundingsProvider:void 0:(await M(async()=>{const{SurroundingsSources:h}=await import("./surroundingsSources-Dlyt6moH.js");return{SurroundingsSources:h}},__vite__mapDeps([15,1,3,4,5,6,7,8,9]),import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,a,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 a=this.scenerySource.value===y.FILE_SOURCE;if(this.setDecorFromFile(a),a){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===y.NO_SCENERY){this.surroundings.withdraw();return}const d=this.plantingCentre();d&&this.surroundings.survey(d.lat,d.lng)}),this.sceneryRadius.addEventListener("input",()=>{const a=Number(this.sceneryRadius.value);if(!Number.isFinite(a)||a<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const d=this.plantingCentre();this.surroundings.radiusChanged(a,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 ui(this.addReferenceButton,"reference-add-kind",a=>this.addReferenceOfKind(a),a=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[a]??`reference-add-${a}`),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 ht(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 rt(this.decorParametersHost,"en","decorParam.");const s={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new rt(this.decorBaseHost,"en","decorBase.",s,(a,d)=>this.enhanceDecorModelChoice(a,d)),this.decorStateForm=new rt(this.decorStateHost,"en","decorState.",s),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{this.focus({preventScroll:!0}),this.onPointerDown(a)}),this.ufoElement.canvasElement.addEventListener("pointermove",a=>this.onPointerMove(a));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{n={x:a.clientX,y:a.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",a=>{const d=n;n=void 0,!(!d?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(a.clientX-d.x,a.clientY-d.y)>y.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",a=>this.onContextMenu(a)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()});const r=this.shadow.getElementById("editor-mute"),o=this.shadow.getElementById("editor-volume");r.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",a=>{const d=a.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 a of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])a.addEventListener(a instanceof HTMLSelectElement||a.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 a=this.ufoElement.sighting;a.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),a.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),a.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",a=>{const{seconds:d,text:h}=a.detail;this.ufoElement.sighting.event.durationText=h,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 a of this.referenceFields)a.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",a=>void this.setReferenceSource(a.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 a=this.shadow.getElementById("trace-import-row");a.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",a=>void this.addTraces(a.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",a=>this.onReferenceWheel(a),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onBodyWheel(a),{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 a of[this.milestoneLabelInput,this.milestoneNoteInput])a.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(un,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(pn,()=>{const a=this.currentReference();a&&this.syncReferenceStatus(a)}),this.sceneElement.addEventListener(mn,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(gn,()=>{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 ui(this.addShapeButton,"add-shape-kind",a=>{const d=Me.byId(a);if(d){this.addModel(d);return}this.currentAppearance={...this.currentAppearance,presetId:a},this.addShape()},a=>`add-shape-${a}`),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 a of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])a.addEventListener("input",()=>this.updateObserver());for(const a of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])a.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",a=>{if(this.observerSaid=a.detail.said,!this.observerPosition.relative)return;const d=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(d,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",a=>this.writeObserverBasis(a.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("input",()=>this.refreshHeadingPoint()),this.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const a=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const d=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(h=>[h.t,Oe.fovOf(this.ufoElement.sighting,h.t)]));this.retuneFieldOfView(a),this.retuneExposure(a),Oe.reproject(this.ufoElement.sighting,a,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 l=a=>this.shadow.querySelector(`${Ft}[name="${a}"]`);this.startDate=l("obs-time"),this.endDate=l("obs-end-time"),this.birthDate=l("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=gt.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const a of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(a,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",a=>{const{time:d}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=d}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",a=>{this.birth=a.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",a=>{const{time:d}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=d})});for(const a of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])a.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(y.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const a of this.weatherFields){if(a===this.iceCrystalAlignmentInput||a===this.rareIceCrystalsInput){a.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}a.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const a of this.soundFields)a.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(a=>this.shadow.getElementById(a.getAttribute("aria-controls")));for(const a of this.groupTabs)a.addEventListener("click",()=>this.toggleGroup(a,!this.isGroupOpen(a)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const a of this.subgroupTabs)a.addEventListener("click",()=>this.openSubgroup(a));this.buildSkyParts(),Pt.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",a=>this.onParamSummaryClick(a)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(a=>a.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=Xn(this.shadow.getElementById("cloud-editor"),this.sceneElement,(a=!0)=>{a&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(a,d)=>{this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(d)),this.updateObserver()},hi(ze.preferencesFor(this),ci),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),ze.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),he.changes.addEventListener("change",this.onModulesChanged),M(async()=>{const{ModuleSession:t}=await import("./ModuleSession-Cdilmebx.js");return{ModuleSession:t}},__vite__mapDeps([16,1,3,4,5,6,7,8,9]),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=gt.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),he.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=$e.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]??st,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:()=>`${gi.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=q.issues(this.ufoElement.sighting);if(F.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=U.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=U.namesOf(this.sightingData);this.observerLastNameInput.value=U.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>U.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=U.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=U.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=U.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 _.NAMES){const o=this.sectionFilePanel.annex(r);o&&(/^[a-z][a-z0-9+.-]*:/i.test(o.src)||t.set(o.src,o.bytes),_.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:o}=await M(async()=>{const{zipSync:d,strToU8:h}=await import("./browser-CltifEM0.js");return{zipSync:d,strToU8:h}},[],import.meta.url),l={[s]:o(n)};for(const[d,h]of t)l[d]=h;const a=r(l,{level:0});this.download(new Blob([a],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.snapshotExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",j.size(a.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"),..._.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...X.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,y.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=X.NAMES.includes(e),i=_.NAMES.includes(e)?e:void 0,s=e===y.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 o=this.shadow.getElementById(r);o.hidden||fe.glue(o)}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)?jt.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 qt)||he.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 o=await e.moduleOf(r),l=o===void 0?void 0:he.installed().find(a=>a.id===o)?.url;!l||gs.names(n,l,s)||(n=[...n??[],gs.of(l,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??=M(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-CwgqBVUI.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([17,1,16,3,4,5,6,7,8,9,18,19,20,21,22,23,24]),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 _.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=z(ft,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:z(at,this.chosenSourceId.get("imagery")).id,roads:vn(),water:bn(),railways:fn()}}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 o=new FileReader;o.onload=()=>n(o.result),o.onerror=()=>r(o.error),o.readAsArrayBuffer(e)}));de.release();const i=await this.recordingText(t),s=JSON.parse(i);if(se.isCase(s)){if(se.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 M(async()=>{const{unzipSync:h,strFromU8:c}=await import("./browser-CltifEM0.js");return{unzipSync:h,strFromU8:c}},[],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(h=>h.endsWith(".json")&&!n.test(h));if(!r)throw new Error("No recording in this archive");const o=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[h,c]of Object.entries(s))h!==r&&h.startsWith(o)&&de.hold(de.address(h.slice(o.length),void 0),c);const l=i(s[r]),a=JSON.parse(l);let d=!1;for(const h of _.NAMES){const c=a.snapshots?.[h]?.src,u=c!==void 0?s[o+c]:void 0;if(!u)continue;const p=$e.recording(JSON.parse(i(u)));_.put(h,a,p),d=!0}return d?JSON.stringify(a):l}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 Je.recording(e);if(se.isCase(t)){se.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;de.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=_e.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(){F.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof Ot)return e.said(this.messages.formatVersionError);if(!(e instanceof Hs))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=wt[0].create();get narrativeSourceId(){return z(wt,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:y.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof ce&&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,o=ke.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,a=Fi(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=ke.apply(a,_t.loadable(r),o)}finally{this.patchingDraft=!1}this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.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:y.valueAt(Fi(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[ao[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 o=document.createElement(t==="stated"?"q":"span");o.textContent=s.rationale,n.append(r,o),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=z(wt,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(),o=r===""?void 0:s.suspect(r);n.classList.toggle("invalid",o!==void 0),n.title=o?this.said.read(o)??"":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 l of i.choices??[]){const a=document.createElement("option");a.value=l.value,a.textContent=this.said.read(l.label)??l.value,r.appendChild(a)}}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 o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),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 ce))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(){y.pageCredentials.clear(),Zt.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!==""?y.pageCredentials.set(t,i):y.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(y.NARRATIVE_KEY_STORAGE),localStorage.removeItem(y.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 y.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} `),y.creditLink(z(ri,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",Gn,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),y.creditLink(z(Et,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",wt,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",ri,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",Et,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",ft,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",at,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[y.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[y.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[y.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",Ni,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,s){const n=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;const o=()=>{r.replaceChildren(...t.map(f=>{const g=document.createElement("option");return g.value=f.id,g.textContent=f.name,g.title=f.credit,g})),s&&r.appendChild(new Option(this.messages.sourceFile,y.FILE_SOURCE))};o();const l=()=>{const f=this.chosenSourceId.get(e);return f!==void 0&&t.some(g=>g.id===f)?f:t[0].id};r.value=s?.fromFile()?y.FILE_SOURCE:l();const a=document.createElement("a");a.className="source-credit",a.target="_blank",a.rel="noopener noreferrer";const d=document.createElement("button");d.type="button",d.className="link source-file-link",d.addEventListener("click",()=>this.openFileItem(s.item));const h=document.createElement("label");h.className="source-key";const c=document.createElement("input");c.type="password",c.id=`${e}SourceKey`,c.autocomplete="off",c.spellcheck=!1,c.title=this.messages.sourceKeyHint;const u=document.createElement("a");u.className="source-credit",u.target="_blank",u.rel="noopener noreferrer",u.textContent=this.messages.sourceKeyGet,h.append(document.createTextNode(`${this.messages.sourceKey} `),c,document.createTextNode(" "),u),c.addEventListener("change",()=>{const f=z(t,r.value);Zt.set(f.id,c.value),i(f,!0)});const p=()=>{const f=r.value===y.FILE_SOURCE,g=z(t,f?l():r.value);h.hidden=f||!g.keyUrl,u.href=g.keyUrl??"",c.value=Zt.of(g.id)??"",r.title=f?s.where():g.credit,a.hidden=f,a.href=g.creditUrl,a.textContent=g.credit,d.hidden=!f,f&&(d.textContent=s.label(),d.title=s.where())};p(),r.addEventListener("change",()=>{const f=r.value===y.FILE_SOURCE;f||this.chosenSourceId.set(e,r.value),s?.setFromFile(f),p(),f||i(z(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?y.FILE_SOURCE:l(),p()});const m=()=>{const f=r.value,g=this.chosenSourceId.has(e)&&!t.some(b=>b.id===this.chosenSourceId.get(e));g&&this.chosenSourceId.delete(e),o(),r.value=f===y.FILE_SOURCE&&s?f:l(),p(),g&&r.value!==y.FILE_SOURCE&&i(z(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),a,d,h),n}aircraftPicker(){const e=this.sourcePicker("aircraft",zi,(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?F.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):F.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=X.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=y.LIVE_ROADS;static LIVE_RAILWAYS=y.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 o=document.createElement("select");o.id=t;const l=s.map(([d,h,c])=>{o.append(new Option(h,d));const u=document.createElement("span");return u.className="source-picker",u.dataset.kind=d,u.append(c),u});o.value=this.sourceKindShown.get(i)??s[0][0];const a=()=>{this.sourceKindShown.set(i,o.value);for(const d of l)d.hidden=d.dataset.kind!==o.value};o.addEventListener("change",a),a(),n.append(r,document.createTextNode(" "),o),e.replaceChildren(n,...l)}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} `),y.creditLink(z(ri,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),y.creditLink(z(Et,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:z(ft,this.chosenSourceId.get("elevation")).create(),imagery:z(at,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(z(zi,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new qt(z(Ni,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)<Ze&&Math.abs(i-this.namedCoordinates.lng)<Ze||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),bs))}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)<Ze&&Math.abs(i-s.lng)<Ze||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),bs))}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,o=this.ufoElement.sighting.event,l=this.ufoElement.sighting.observerTrack,a=this.ufoElement.currentTime,d=l.getInterpolatedPoseAt(a),h=d?.altitudeM!==void 0?r:void 0,c=h!==void 0?d.elevationM:Math.max(0,r-(this.groundElevationM??0)),u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),m=(u.frame&&p!==void 0?ye.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),f=this.numberOrUndefined(this.fNumberInput.value),g=this.filterSelect.value,b=le.byId(l.getLatestPoseAt(a-1)?.filter),v=g===le.NONE.id||g===""?b===le.NONE?void 0:le.NONE.id:g,I=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=I===u.exposureSeconds?void 0:I;const S=this.numberOrUndefined(this.focusDistanceInput.value),w=Math.abs(m-ye.fieldOfViewDeg(u))>.01||f!==u.fNumber||S!==void 0||v!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&c===0&&!w?l.removeKeyframeAt(a):l.addKeyframe(a,{lat:e,lng:t,elevationM:c,...h!==void 0?{altitudeM:h}:{},headingDeg:i,pitchDeg:s,rollDeg:n===0?void 0:n,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:m,fNumber:f,focusDistanceM:S,filter:v});const C=this.stringOrUndefined(this.placeNameInput.value.trim()),B=l.getInterpolatedPoseAt(0);o.place=e!==void 0&&t!==void 0?[{lat:B?.lat??e,lng:B?.lng??t,name:C}]:void 0;const A=this.plantingCentre();this.surroundings.placeChanged(A?.lat,A?.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&&!yt.isFirm(t))return;const s=yt.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&&yt.at(i,e)===t)return;const s=yt.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&&Bt({...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=q.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,q.renamed(e,s,q.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:gt.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??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...s]:s;e.sources=l.length>0?l: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={...re(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={...re(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;fe.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"||Re.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=Re.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=Re.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(F.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>kr?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,o={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)||kt))},l=this.registrationShown(n),a=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.fovDeg,d=this.referenceKindSelect.value;return d==="video"?{...a?Re.withKey(n,this.ufoElement.currentTime,o):n,kind:d,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:d,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:o,from:a?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=Q(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(Re.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=Q(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=Q(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:Er,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:kt},from:this.observerPositionNow(),...i};s.references=[...s.references,o],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((o,l)=>{const a=new FileReader;a.onload=()=>o(a.result),a.onerror=()=>l(a.error),a.readAsDataURL(r)})}else i=e.url;const s=this.ufoElement.sighting,n=Re.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??=M(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-DOSDjiOf.js");return{PictureRegistration:e}},__vite__mapDeps([25,3,1,4,5,6,7,8,9]),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:Re.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 o=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(o&&Math.hypot(o.x-e.x,o.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(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:this.pictureRegistration.aimOf(r)};const l=this.pictureRegistration.picturePointOf(r,s.registration,n);return l?{...o,picture:l}:o})),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)||kt,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 o=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,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 o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,n)+l,this.referenceLandmarksSelect.appendChild(o)}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);fe.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(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),s=i.findIndex(o=>o.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const o=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+o}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(o=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o,s,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,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(o=>o!==void 0)?n:void 0,r.filter(o=>o.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,o=h=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:h.x/n.width,v:h.y/n.height},r,i)),l=[];for(const h of n.pairs){const c=o(h.ghost),u=o(h.light),p=o({x:h.ghost.x+h.ghost.radius,y:h.ghost.y});!c||!u||l.push({ghost:c,light:u,ghostRadius:p?Math.hypot(p.x-c.x,p.y-c.y):0})}const a=n.centre?o(n.centre):void 0,d=n.cropped?o({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(l,a,d)}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(Re.rollOfPicture(s)??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(a=>a.t===n);if(r<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[a,d]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${a}`,{basis:"derived",rationale:o,of:this.rounded(d)})}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=Q(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 M(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,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}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:kt}})}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;fe.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:d}=await M(async()=>{const{TraceImport:h}=await import("./TraceImport-CntRHXoJ.js");return{TraceImport:h}},__vite__mapDeps([26,1]),import.meta.url);i=await d.fromBytes(await $s.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(d=>d.id));let r=1;const o=this.said.write(void 0,i.documentName??t,this.writingLanguage),l=i.traces.map(d=>{for(;n.has(`trace-${r}`);)r++;const h=`trace-${r}`;return n.add(h),{...d,id:h,title:d.title===void 0?void 0:this.said.write(void 0,d.title,this.writingLanguage),source:o}});s.traces=[...s.traces,...l],this.currentTraceId=l[0].id,this.refreshTraceList();const a=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(l.length)).replace("{name}",t)+a,this.ufoElement.refresh()}async exportFigures(e){const t=this.fileBase(),{GEO_EXPORT_TEXTS:i}=await M(async()=>{const{GEO_EXPORT_TEXTS:o}=await import("./GeoExportTexts-3a51cuxQ.js");return{GEO_EXPORT_TEXTS:o}},__vite__mapDeps([27,1]),import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:o}=await M(async()=>{const{KmlExport:a}=await import("./KmlExport-wWr2S8H-.js");return{KmlExport:a}},__vite__mapDeps([28,29,5,6,1,4,3,7,8,9]),import.meta.url),l=o.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([l],{type:"application/vnd.google-earth.kml+xml"}),`${t}.kml`);return}const{GeoJsonExport:n}=await M(async()=>{const{GeoJsonExport:o}=await import("./GeoJsonExport-wUgEVyel.js");return{GeoJsonExport:o}},__vite__mapDeps([30,29,5,6,1,4,3,7,8,9]),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 Rn){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(),Wr)}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=Pn(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 it(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===y.FILE_SOURCE;if(!e){const t=z(Ee,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new it(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(_.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=X.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=Ee.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==z(Ee,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new it(e.create())}else!e&&t!==void 0&&!Ee.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new it(z(Ee,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...Ee.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,y.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!xt(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?y.FILE_SOURCE:i?i.id:z(Ee,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=z(Ee,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&&!xt(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),fs))}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||!xt(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 o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput&&o!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title=this.fieldHints.get(o.id)??"");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&xt(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&&be(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=!_.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=Et[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(),fs)}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 o=await s.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${s.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.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=Bt(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=Bn(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?Yt.MUTED:Yt.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(),D.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(ot.opensPrecise(e.time)),this.endDate.setPrecise(ot.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)>qr;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),Kr))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ze&&Math.abs(e.lng-i)<Ze}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=z(ft,this.chosenSourceId.get("elevation")),n=await new ki(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 o=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime)?.altitudeM;this.syncElevationField(r,o)}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=Q(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(y.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(ot.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=re(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??fi)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??Fn)),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=Qi(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!==y.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 M(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:t}},__vite__mapDeps([12,13,14]),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"){F.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of _.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&_.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of _.NAMES){const n=_.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||_.put(s,e,_.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return ss.of(e,t,t==="thin"?Oe.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(y.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(y.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Ts(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=ss.of(this.ownJson(mi(e)),t,t==="thin"?Oe.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(y.weatherOf(this.fileTextApplied)),o={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 l=this.ufoElement.sighting.weatherSource;l===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):Ee.some(a=>a.id===l.id)&&this.askAboutWeather(o,l.name??l.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(l){this.showFileNote(l instanceof Ot?l.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=o=>this.rounded(o).toLocaleString(this.language,{maximumFractionDigits:1}),s=o=>o.x>=-.05&&o.x<=1.05&&o.y>=-.05&&o.y<=1.05;let n;if(e!==void 0){const o=(e%360+360)%360,l=[];for(let a=0;a<360;a+=y.COMPASS_STEP_DEG){const d=this.sceneElement.horizonPointAt(a);d&&s(d)&&l.push({...d,label:this.naming.point(a)})}n={label:this.messages.overlayHeading.replaceAll("{deg}",i(o)).replaceAll("{point}",this.naming.point(o)),compass:l}}let r;if(t!==void 0){const o=[[]];for(let l=0;l<=360;l+=y.HORIZON_STEP_DEG){const a=this.sceneElement.horizonPointAt(l);a&&Math.abs(a.x-.5)<1.5&&Math.abs(a.y-.5)<1.5?o[o.length-1].push(a):o[o.length-1].length>0&&o.push([])}r={line:o,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,o=a=>this.numberOrUndefined(a.value),l=(a,d=1)=>a===void 0?"?":a.toLocaleString(this.language,{maximumFractionDigits:d});if(t==="pitch")this.showOrientation(void 0,o(this.pitchInput)??0);else if(t==="heading")this.showOrientation(o(this.headingInput)??0,void 0);else if(t==="focalLength"){const a=Oe.fovOf(i,s),h=2*Jt.of(i.instrument,n.height,a).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",l(a)).replaceAll("{h}",l(h)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const a=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!a){e.hide();return}const d=a.bounds,c=[[o(this.apparentWidthInput),"°",1],[o(this.realWidthInput)," m",1],[o(this.objectDistanceInput)," m",0]].filter(([u])=>u!==void 0).map(([u,p,m])=>`${l(u,m)}${p}`).join(" · ");e.measure((d.x+d.width/2)/n.width,(d.y+d.height/2)/n.height,Math.max(d.width,d.height)*1.3/n.width,c)}else if(t==="windDirection"||t==="windSpeed"){const a=o(this.windDirectionInput)??0,d=a-(o(this.headingInput)??0);e.wind(d,r.overlayWind.replaceAll("{point}",this.naming.point(a)).replaceAll("{speed}",l(o(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=a=>{let d=-1;return a.forEach((h,c)=>{h<=i()&&(d=c)}),d===-1&&a.length>0?0:d};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const a=n(t().observerTrack.allKeyframes.map(d=>d.t));return a===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${a}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const a=t().timeline.allKeyframes,d=n(a.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId)).map(p=>p.t));if(d===-1||this.apparentWidthInput.value==="")return;const h=a.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId))[d],c=a.indexOf(h),u=h.shapes.findIndex(p=>p.sourceId===this.currentSourceId);return`timeline.keyframes.${c}.shapes.${u}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const o=document.createElement("div");o.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(o);const l=a=>a?.closest("label")??void 0;this.candidatesView=new ne({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const a=this.ufoElement.sighting.event,d=a.place?.[0];if(!d||a.time?.year===void 0||a.time.hour===void 0)return;const h=be(a.time,d.lng,a.utcOffsetHours);return h?{date:h,observer:{lat:d.lat,lng:d.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:a=>Ke(a,this.instrumentGain()),fieldLabels:()=>({time:l(s),heading:l(this.headingInput),size:l(this.apparentWidthInput),duration:l(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:a=>{const d=`${a}/${this.language}`;return this.poherMatrix?.key!==d&&(this.poherMatrix={key:d,loaded:Ue.load(a,this.language,h=>Je.json(h))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const a=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,d=this.sceneElement.satellitePassesDuring(a);return d.length>0?{passes:d,positionsAt:h=>this.sceneElement.satellitePositionsAt(h)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const a=this.ufoElement.sighting.interpretation;return[...a&&(a.bodies.length>0||Lt.computes(a,Dt.kinds()))?[{id:"own",label:this.said.read(a.title)??this.principalObserverLabel(),interpretation:a}]:[],...this.readings]},computed:a=>this.sceneElement.computedInterpretation(a),starName:a=>this.naming.star({name:a}),projectionAt:(a,d)=>this.sceneElement.bodyProjectionAt(a,d),variants:()=>this.ufoElement.sighting.variants,keep:a=>this.editVariants(d=>[...d,a]),remove:a=>this.editVariants(d=>d.filter((h,c)=>c!==a))},o)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,s=i.place?.[0];if(s&&i.time?.year!==void 0&&i.time.hour!==void 0){const d=be(i.time,s.lng,i.utcOffsetHours);d&&(t.sunAltitudeDeg=V("Sun",d,{lat:s.lat,lng:s.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const d=re(e,0);t.cloudCover=d.cloudCover,t.lightning=d.storm,t.lowVisibility=d.precipitationType!=="none"&&d.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const d=n.allKeyframes.filter(u=>u.shapes.some(p=>p.sourceId===r)),h=d.map(u=>({t:u.t,shape:n.getShapeAt(u.t,r)})).filter(u=>u.shape?.aim),c=n.getInterpolatedShapeAt(d[0]?.t??0,r);if(c?.aim&&(t.elevationDeg=c.aim.altitudeDeg),c?.angular){t.widthDeg=c.angular.widthDeg;const u=c.angular.heightDeg>0?c.angular.widthDeg/c.angular.heightDeg:1;t.round=c.kind==="oval"&&u>.8&&u<1.25}if(c?.brightness!==void 0&&(t.brightness=c.brightness),h.length>1){const u=(g,b)=>{const v=Math.PI/180,I=Math.sin(g.altitudeDeg*v)*Math.sin(b.altitudeDeg*v)+Math.cos(g.altitudeDeg*v)*Math.cos(b.altitudeDeg*v)*Math.cos((g.azimuthDeg-b.azimuthDeg)*v);return Math.acos(Math.max(-1,Math.min(1,I)))/v},p=h.slice(1).map((g,b)=>({deg:u(h[b].shape.aim,g.shape.aim),s:(g.t-h[b].t)/1e3}));t.sweepDeg=u(h[0].shape.aim,h[h.length-1].shape.aim);const m=p.reduce((g,b)=>g+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const f=(h[h.length-1].t-h[0].t)/1e3;if(f>0){t.speedDegPerS=m/f;const g=Math.max(...p.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const o=new Set(n.sourceIds.map(d=>n.groupMembers(d)?.[0]??d));o.size>0&&(t.count=o.size);const l=[...o].map(d=>n.getInterpolatedShapeAt(0,d)?.aim).filter(d=>d!==void 0);if(l.length>=3){const d=Math.PI/180,h=l.map(m=>({x:(((m.azimuthDeg-l[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*d),y:m.altitudeDeg}));let[c,u]=[h[0],h[1]];for(const m of h)for(const f of h)Math.hypot(m.x-f.x,m.y-f.y)>Math.hypot(c.x-u.x,c.y-u.y)&&([c,u]=[m,f]);const p=Math.hypot(c.x-u.x,c.y-u.y);t.aligned=p>0&&h.every(m=>Math.abs((u.x-c.x)*(c.y-m.y)-(c.x-m.x)*(u.y-c.y))/p<=Math.max(.5,p*.1))}const a=new Set([...o].map(d=>n.getInterpolatedShapeAt(0,d)?.color).filter(d=>d!==void 0));return a.size>0&&(t.colors=[...a]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(d=>d.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}static SCENE_HEIGHT_KEY="rr0-editor-scene-height";resizeScene(e){const t=this.shadow.querySelector(".app"),i=this.sceneElement,s=n=>{n===void 0?t.style.removeProperty("--rr0-scene-max-height"):t.style.setProperty("--rr0-scene-max-height",`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,n)))}px`);try{n===void 0?localStorage.removeItem(y.SCENE_HEIGHT_KEY):localStorage.setItem(y.SCENE_HEIGHT_KEY,t.style.getPropertyValue("--rr0-scene-max-height"))}catch{}};try{const n=localStorage.getItem(y.SCENE_HEIGHT_KEY);n&&/^\d+px$/.test(n)&&t.style.setProperty("--rr0-scene-max-height",n)}catch{}e.addEventListener("pointerdown",n=>{n.preventDefault();const r=n.clientY,o=i.getBoundingClientRect().height;e.setPointerCapture?.(n.pointerId),e.classList.add("dragging");const l=d=>s(o+d.clientY-r),a=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",l),e.removeEventListener("pointerup",a),e.removeEventListener("pointercancel",a)};e.addEventListener("pointermove",l),e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a)}),e.addEventListener("keydown",n=>{n.key!=="ArrowUp"&&n.key!=="ArrowDown"||(n.preventDefault(),s(i.getBoundingClientRect().height+(n.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>s(void 0))}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=o=>{const l=this.groupTabs.find(a=>a.getAttribute("aria-controls")===o);l&&this.toggleGroup(l,!0)},s=o=>()=>{this.touch(),this.armHistory(),o(),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:o=>this.pickEvent(Number(o)),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:o=>this.pickEvent(Number(o)),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:o=>this.pickEvent(Number(o)),add:s(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(o=>o.t),open:()=>i("group-weather"),add:s(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(o=>o.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"?ue.observerTrackIsExpanded(t):ue.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(d=>d.t)};const n=this.ufoElement.seekableDuration,r=d=>e==="observer"?q.isObserver(t,d):q.isPhenomenon(t,d),o=(t.events??[]).map((d,h)=>({event:d,index:h})).filter(({event:d})=>r(d)),l=new Set(o.map(({event:d})=>d.who)).size>1,a=o.map(({event:d,index:h})=>{const c=this.messages.events.kinds[d.eventType]??d.eventType;return{id:String(h),t:d.t,until:d.until??n,label:e==="phenomenon"&&l?`${this.shapesLabel(d.who??"")} · ${c}`:c}});return{times:[],spans:a}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(l=>l.id)),s=l=>q.partOf(l)?.element??l??"",n=(e.events??[]).map((l,a)=>({event:l,index:a})).filter(({event:l})=>i.has(s(l.who)));if(n.length===0||!ue.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(l=>l.track.map(a=>a.t)))].sort((l,a)=>l-a)};const r=this.ufoElement.seekableDuration,o=n.map(({event:l,index:a})=>{const d=t.find(p=>p.id===s(l.who)),h=q.partOf(l.who)?.part,c=this.messages.events.kinds[l.eventType]??l.eventType,u=[...t.length>1?[this.said.read(d?.title)??s(l.who)]:[],...h?[h]:[]];return{id:String(a),t:l.t,until:l.until??r,label:[...u,c].join(" · ")}});return{times:[],spans:o}}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??q.observerId(t);if(q.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 q.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(q.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=(l,a)=>[...a].map(d=>({t:d,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>{if(this.showsBodies){const d=this.eventMarks("bodies");return d.spans?d.spans.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.bodiesTrack,d.times)}const{spans:a}=this.eventMarks("phenomenon");return a?a.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(d=>!l||d.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(d=>d.t))},s=()=>{const{times:l,spans:a}=this.eventMarks("observer");return a?a.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.observerTrack,l)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=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 l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,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=Yt.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=Dt.kinds();if(Lt.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Lt.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(a=>a.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:o,opensMostLacking:l}=this;this.openSubgroup(r),this.sectionChosen=o,this.opensMostLacking=l}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){if(!this.paramSummaryBuilder)return;const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|"),s=JSON.stringify(this.ufoElement.sighting.account??null);if(i===this.paramSummarySignature){s!==this.assessedAccount?(this.assessedAccount=s,this.assessSoon()):this.assessmentsOwed&&this.ufoElement.playbackState!=="playing"&&this.assessSoon();return}this.assessedAccount=s,this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.assessSoon()}assessmentsOwed=!1;assessSoon(){if(this.ufoElement.playbackState==="playing"){this.assessmentsOwed=!0;return}this.assessmentsOwed=!1,this.runAssessments()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=y.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==s.group&&(i=void 0),e.includes(s.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=s.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=s.group==="assessment"?this.messages.assessmentGroup:s.group==="summary"?this.messages.summaryGroup:y.tabLabel(this.groupTabs[this.summaryPanelIndex(s.group)]),r.append(o),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),xs.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return this.panelIndex(e==="phenomenon"?"shape":e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]},"bg-information":{panel:"observer",fields:["accountSource"]},"bg-occupation":{panel:"observer",fields:["observerOccupationKind"]},"bg-relation":{panel:"observer",fields:["observersRelation"]},"bg-activity":{panel:"observer",fields:["observerActivity"]},"bg-age":{panel:"observer",fields:["observerAge"]},"bg-appearance":{panel:"observer",fields:["strangeness-appearance"]},"bg-movement":{panel:"observer",fields:["strangeness-movement"]},"bg-incongruity":{panel:"observer",fields:["strangeness-incongruity"]},"bg-close":{panel:"observer",fields:["strangeness-close"]},"bg-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-occupants":{panel:"observer",fields:["strangeness-beings"]}};assessmentChips=[];assessmentToken=0;assessedAccount="";async runAssessments(){const e=++this.assessmentToken,t=await new wn(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=s=>{const n=s.querySelector(".tab-badge");return n&&!n.hidden?Number(n.textContent):0},t=this.groupTabs.find(s=>this.isGroupOpen(s));let i=t&&e(t)>0?t:void 0;for(const s of this.groupTabs)e(s)>(i?e(i):0)&&(i=s);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
|
|
2700
|
+
`)}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=y.QUESTION_FIELDS[n];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[n,r]of Object.entries(y.QUESTION_FIELDS))for(const o of y.QUESTION_FIELDS[n].fields){const l=this.shadow.getElementById(o);if(!l)continue;const a=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",a),(a||l.title===this.messages.questionUnanswered)&&(l.title=a?this.messages.questionUnanswered:this.fieldHints.get(o)??"")}const i=new Map;let s;for(const[n,r]of Object.entries(y.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const a=l.classList.contains("missing-required");!a&&!l.classList.contains("wanted")||(a&&(s=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const n of this.groupTabs){const r=this.panelOf(n),o=i.get(r)??0,l=r===s,a=y.badgeOn(n);a.hidden=o===0,a.textContent=String(o),a.classList.toggle("optional",!l);const d=o===0?void 0:l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o));d?n.dataset.unanswered=d:delete n.dataset.unanswered,y.titleGroupTab(n)}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field,e.detail&&(t.title=e.detail);const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const n=document.createElement("span");n.className="param-chip-swatch",n.style.background=e.color,t.append(n)}const s=document.createElement("span");return s.className="param-chip-value",s.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(s),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(o=>o.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 o=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(l=>l.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&&fe.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:no(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(y.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,ge.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,ge.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(ge.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(ge.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),o=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),l={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-o)/2,width:r,height:o},a=n.ofBounds(l),d=s.kind==="oval"?{...s,bounds:l,angular:a}:{...s,bounds:l,angular:a,points:this.scalePoints(s,l)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:d}]),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={[le.NONE.id]:this.messages.filterNone,[le.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[le.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==le.ALL.length||le.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||le.NONE.id;this.filterSelect.replaceChildren();for(const r of le.ALL){const o=document.createElement("option");o.value=r.id,o.textContent=t(r),this.filterSelect.appendChild(o)}this.filterSelect.value=n}const s=this.ufoElement?.sighting?.instrument;for(const n of this.filterSelect.options){const r=!s||le.usableWith(le.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,s={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,video:this.messages.instrumentCategoryVideo,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},n=r=>{const o=this.naming.instrument(r),l=ye.unavailability(r,t);if(!l)return{id:r.id,label:o};const a=(l.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(l.from)).replace("{to}",String(l.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",o),hint:a}:{id:r.id,label:o,disabledReason:a}};this.instrumentSelect.choices=ye.CATEGORIES.map(r=>({label:s[r],children:Nn.filter(o=>o.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=y.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const n=Number(i[1]),r=Number(i[2]);return r>0?n/r:void 0}const s=Number(t);return Number.isFinite(s)&&s>0?s:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=Q(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??ye.fieldOfViewDeg(t),r=s?ye.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),Pt.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 o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),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 l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":y.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const h of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(h,yn.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const a=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const d=bt.byId(e.film);this.isoInput.placeholder=a?a.autoExposure?"auto":String(d?.iso??a.iso):"",this.setRowVisible(this.isoInput,a!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,a?.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=le.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=ye.fieldOfViewDeg(e),s=ye.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>Jr||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 Q(e,this.ufoElement.currentTime)?.fovDeg??ye.fieldOfViewDeg(e.instrument)}currentProjection(){return Jt.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=ge.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=Q(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?ye.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,o=s?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const a=2*En*e/l*i.heightMm,d=r*r/(o*a)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(d))}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),o=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))+o+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,f)=>Number(m.toFixed(f)),n=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??Gr,o=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),l=o!==void 0&&o<r,a=s(r,1),d=i?.angular?.widthDeg,h=i?.angular?.heightDeg,c=d!==void 0&&h!==void 0&&d>0&&h>0?{widthM:s(ge.sizeMAt(a,d),2),lengthM:s(ge.sizeMAt(a,d),2),heightM:s(ge.sizeMAt(a,h),2)}:void 0,u={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},p={t,...u,distanceM:a,...l?{onGround:!0}:{},...c?{sizeM:c}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:p}:{keyframe:p}}loadBodyEditor(){return this.bodyEditorLoading??=M(async()=>{const{BodyEditor:e}=await import("./BodyEditor-23Dua2K5.js");return{BodyEditor:e}},__vite__mapDeps([31,3,1,4,5,6,7,8,9,18,20]),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=Dt.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=Is.map(i=>At.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,o)=>{this.headingInput.value=String(this.rounded(r)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()},changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language))}));return[...e,...t]}buildSkyParts(){const e=this.shadow.getElementById("weather-tabs"),t=this.shadow.getElementById("sky-event-parts");if(!e||!t)return;const i=this.wantedSkyParts();for(const[s,n]of this.skyParts)if(!i.some(r=>r.key===s&&r.kind===n.kind)){if(n.tab.getAttribute("aria-expanded")==="true"){const r=this.subgroupTabs.find(o=>o.parentElement===e&&o!==n.tab);r&&this.openSubgroup(r)}n.tab.remove(),n.panel.remove(),this.subgroupTabs.splice(this.subgroupTabs.indexOf(n.tab),1),this.skyParts.delete(s)}for(const s of i){if(this.skyParts.has(s.key))continue;const n=document.createElement("button");n.className="subgroup-tab",n.type="button",n.setAttribute("aria-controls",s.id),n.setAttribute("aria-expanded","false");const r=document.createElement("span");r.id=`label-${s.id}`,this.nameSkyPart(r,s.titles),n.append(r),n.addEventListener("click",()=>this.openSubgroup(n)),e.append(n),this.subgroupTabs.push(n);const o=document.createElement("section");o.className="subgroup-panel",o.id=s.id,o.hidden=!0,o.setAttribute("aria-labelledby",r.id);const l=document.createElement("div");l.className="toolbar";const a=document.createElement("div");a.id=`${s.id}-editor`,l.append(a),o.append(l),t.before(o),this.skyParts.set(s.key,{...s,tab:n,label:r,panel:o})}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(gt.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:ge.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=Jt.of(i.instrument,ge.CANVAS_HEIGHT_PX,Oe.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const o=Oe.aimOf(i,e,r.shape.bounds),l=s.ofBounds(r.shape.bounds),{aim:a,...d}=r.shape;return{...r,shape:o?{...d,aim:o,angular:l}:{...d,angular:l}}}))}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},...Me.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(d=>d.value===e.id).label,o=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",l={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},a=s.map((d,h)=>{const c=e.partNames[h],u=c?`${r} ${o}, ${l[c]}`:`${r} ${o}`;return{sourceId:n[h],shape:{...d,title:this.said.write(void 0,u,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,a),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 o=r.shapes.filter(l=>t.includes(l.sourceId)).map(l=>{const{bounds:a}=l.shape;return{sourceId:i[t.indexOf(l.sourceId)],shape:{...l.shape,bounds:{...a,x:a.x+s,y:a.y+s}}}});o.length>0&&this.commitShapes(r.t,o)}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]??st,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:Ui.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:As}:{},windows:Cs(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(y.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(y.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(y.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(y.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await M(()=>import("./surroundingsSources-Dlyt6moH.js"),__vite__mapDeps([15,1,3,4,5,6,7,8,9]),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=y.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(o=>{const l=document.createElement("option");return l.value=o.id,l.textContent=o.name,l.title=o.credit,l}),r=new Option(this.messages.sourceFile,y.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(s,...n,r),this.surveyIds=t.map(o=>o.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==y.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?y.FILE_SOURCE:this.sceneryChoice===y.NO_SCENERY?y.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===y.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=X.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?Nt.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*li,t=Math.round(e/Qr*1e3);return{lights:Ui.byId("airliner")?.create(),track:[{t:0,eastM:-li,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:li,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=Wn(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?es[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(l=>l.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 o={...n.sizeM,...Object.fromEntries(Object.entries(s.sizeM).filter(([,l])=>l!==void 0).map(([l,a])=>[l,this.roundedMeters(a)]))};this.updateDecor({sizeM:o})}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=_i([...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=_i(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;fe.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=y.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!==y.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!==y.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 M(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([32,33]),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=bt.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=(l,a,d=!1)=>{const h=document.createElement("option");h.value=l,h.textContent=a,h.disabled=d,this.filmStockSelect.appendChild(h)};r("",this.messages.filmStockAny);const o=i.map(l=>({stock:l,gap:bt.gap(l,t,s)}));for(const{stock:l}of o.filter(a=>!a.gap))r(l.id,l.name);for(const{stock:l,gap:a}of o.filter(d=>d.gap)){const d=a.kind==="before"?this.messages.filmStockNotYet.replace("{from}",String(a.from)):this.messages.filmStockNoLonger.replace("{to}",String(a.to));r(l.id,`${l.name} (${d})`,l.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(bt.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 Rt(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?tt.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(nt.resolve(me.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(nt.resolve(me.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}=ts(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=Hi.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:$i.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Hi.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:me.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:es[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(o=>o.id===e.id?n:o),n}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(a=>a.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=tt.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const o=this.ufoElement.sighting;o.decor=o.decor.map(a=>a.id===s.id?tt.apply(a,r,t,n):a),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const l=o.decor.find(a=>a.id===s.id);t==="title"&&this.decorList.rename(l.id,this.decorLabel(l)),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?Ss.of(e,this.publishedParametersOf(e)):void 0,i=t&&nt.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(o=>o.key).join(",")}`;if(s===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=s;const n=e.id,r=new Rt(()=>this.ufoElement.sighting.decor.find(o=>o.id===n),o=>{const l=this.ufoElement.sighting;l.decor=l.decor.map(a=>{if(a.id!==n)return a;const d=structuredClone(a);return o(d),d})});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?be(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=V("Sun",i,t).altitudeDeg;return Ke(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new jn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Wi;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new ct(["en"]);tagNames=new ji({});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?be(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,re(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},o=e.skySources!==!1,l=[this.starsClause(s,r),o?this.showerClause(s,r):this.messages.skyByHand,this.cometClause(s,r),this.novaClause(s,r),this.eclipseClause(s,r),this.moonClause(s,r),o?this.satelliteClause(s,r):void 0,o?this.reentryClause(s,r):void 0,o?this.fireballClause(s,r):void 0,this.opticsClause(s,r),this.rainbowClause(s,r),this.glowClause(s,r)].filter(a=>a!==void 0);o||(this.showMeteorButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0),this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",l.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 kn.gainFor(e.instrument,{fNumber:Q(e,0)?.fNumber,fieldOfViewDeg:Oe.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=V("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Ke(i,s,n),o=d=>d.toLocaleString(void 0,{maximumFractionDigits:1});if(r<Vr)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,a=Math.abs(s)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(s>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(s))).replace("{eye}",o(Ke(i,0,n)));return r<=Gi?a:a+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Gi))}showerClause(e,t){const i=Ki.observedRatePerHour(Ki.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=Xt.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 o=Xt.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:Xt.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.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=Qt.brightestAt(e,t);if(!i||i.magnitude>Vi){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=qi.brightestAt(e,t);if(!i||i.magnitude>Vi){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=Sn.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=V("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),o=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} 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=V("Moon",e,t);if(i.altitudeDeg<=0||Ye(e).illuminatedFraction<.97)return;const s=[],n=Ve.distanceKm(e,t),r=Ve.relativeToMean(Ve.radiusAtKm(n)),o=n<=Ve.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Ve.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return o&&s.push(o.replace("{distance}",(Math.round(n/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(Ve.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Wt.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=ve.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=Ke(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(h=>h.peakMagnitude<=n),o=this.listed(r.map(h=>this.naming.satelliteClass(h)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),a=(i.trackedObjects??0).toLocaleString(),d=h=>h.replace("{height}",l).replace("{count}",a);return i.lowOrbitLit?r.length===0?d(this.messages.skySatellitesLit):d(this.messages.skySatellitesLitWith).replace("{eras}",o):d(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 a={key:n,status:"loading"};this.reentries=a,y.reentryArchive.candidates(i,s,t).then(d=>{a.status=d?"ready":"unavailable",a.candidates=d,this.reentries===a&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=ve.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(a=>a.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(a=>this.reentryText(a));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.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 o=s.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}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(a=>a.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(a=>a.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,o=(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)),l=this.starlinkTrain(i);return l?`${o}, ${l}`:o}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=V("Sun",i.peak.date,t);return s<=Ke(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:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,s]=[...t.entries()].sort((r,o)=>o[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=Q(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=be(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=>Zi.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Zi.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=be(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=re(this.ufoElement.sighting,0),s=V("Sun",e,t),n=V("Moon",e,t),r=vt.deckLitUntilDeg(vt.DECK_HEIGHT_M),o=s.altitudeDeg>-r,l=o?s:n;if(l.altitudeDeg<=-r)return;const a=i.highCloudCover;if(a===void 0||a<=0)return this.messages.skyOpticsNoIce;if(vt.strength(a,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const d=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,h=this.listed(vt.formsAt(l.altitudeDeg,r).map(u=>this.opticsFormName(u))),c=i.iceCrystalAlignment??fi;return this.messages.skyOpticsPossible.replace("{forms}",h).replace("{source}",d)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(c*100)))}rainbowClause(e,t){const i=re(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=V("Sun",e,t),n=V("Moon",e,t),r=s.altitudeDeg>0,o=r?s:n;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(ei.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const a=ei.formsAt(o.altitudeDeg);if(a.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(ei.primary().radiusDeg)));const d=this.listed(a.map(c=>this.bowFormName(c)));if(r)return this.messages.skyBowPossible.replace("{forms}",d);const h=Math.round(Ye(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",d).replace("{lit}",String(h))}glowClause(e,t){const i=V("Sun",e,t);if(i.altitudeDeg>ro)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 u=s.zodiacal.sunSeparationDeg<=O.CONE_SEPARATION_DEG;n.push((u?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),o=V("Moon",e,t),l=s.darkestSkyMagPerArcsec2<oo,a=this.ufoElement.sighting.lightPollution,d=pe.scatteringAt(90-o.altitudeDeg)*pe.moonOutput(pe.phaseAngleOf(Ye(e).illuminatedFraction),o.altitudeDeg)*pe.scatteredFraction(90),h=pe.artificialZenithNanolamberts(a)>d;if(l&&o.altitudeDeg>0&&!h){const u=Math.round(Ye(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(u)).replace("{sky}",r)}const c=pe.artificialZenithNanolamberts(a)>pe.twilightExcessNanolamberts(i.altitudeDeg);return l&&h&&c?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=V("Sun",e,t),s=V("Moon",e,t);return pe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(Ye(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new O;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<Qt.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=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Qt.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=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=qi.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(a=>a.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}=ts(e,this.ufoElement.currentTime),r=Math.hypot(i,s);if(r===0&&n===0)return;const o=Math.atan2(i,s)*180/Math.PI,l=Math.atan2(n-Xr-(Q(this.ufoElement.sighting,this.ufoElement.currentTime)?.elevationM??0),r)*180/Math.PI;this.headingInput.value=String(Math.round(o*10)/10),this.pitchInput.value=String(Math.round(l*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??y.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return Qi(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-qe.width/2,y:e.height/2-qe.height/2,width:qe.width,height:qe.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 Ei(this.ufoElement.sighting.timeline,new dr(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"})),D.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=ze.preferencesFor(this);this.preferences=t;const i=hi(t,ci),s=this.decidedLanguage===void 0;if(this.decidedLanguage=i,s){for(const h of this.skyParts.values())this.nameSkyPart(h.label,h.titles);this.applyPerceptionLabels()}const n=this.narrativeProvider.localize?.(i),[r,o,l,a]=await Promise.all([ys.load(i),i==="en"?{}:Ws(i),js(i),ir.load(i)]);if(await n,e!==this.localeToken)return;const d=i!==this.language;this.language=i,this.decorParameterTexts=a,this.naming=new Wi(l),this.said=new ct(t),this.tagNames=new ji(o),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new Yi(r,this.naming,this.said,this.tagNames,{messages:r,locale:this.language},this.decorParameterTexts),this.refreshParamSummary()),d?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===st&&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,o)=>{this.shadow.getElementById(n).setAttribute(r,o),r==="title"&&this.fieldHints.set(n,o)};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(y.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(y.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(Si))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,Ae.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 o=this.shadow.getElementById(n);o&&(o.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 o=this.shadow.getElementById(`label-${n}-settings`);o&&(o.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 Yi(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,Ae.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,r]of this.soundKindOptions)r.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e),this.refreshFileItems(),this.refreshSkyCandidates()}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])Ne.popover(this.shadow.getElementById(s),e.close);Ne.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),Ne.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),Ne.button(this.contextMenu,e.close,()=>this.hideContextMenu()),Ne.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,y.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 h=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,c=h?this.sceneElement.pickAt(h.x,h.y):void 0;this.beginCameraDrag(t,c?.kind==="decor"?c.id:void 0,c?.kind==="body"?c.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,o=this.ufoElement.playbackState==="playing",l=i==="shape";if(l)if(this.selectedSourceIds.size>1){const h=new ti(this.selectedMembers()),c=J.hitTestHandle({bounds:h.bounds(),angle:0},t);if(c==="rotate"){if(o)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(c){if(o)return;this.dragState={kind:"group-resize",group:h,handle:c},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(r,this.currentSourceId),c=h?.kind==="polygon"?J.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&c!==void 0){if(o)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:c},this.startDragListening();return}const u=h&&J.hitTestHandle(h,t);if(h&&u){if(o)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const a=this.ufoElement.shapeAt(t.x,t.y,It);if(!a){const h=s==="ground"?this.ndcOf(e):void 0,c=h?this.sceneElement.pickAt(h.x,h.y):void 0;if(c?.kind==="body"&&c.id!==void 0){o?this.showBody(c.id):this.beginCameraDrag(t,void 0,c.id);return}const u=c?.kind==="decor"?c.id:void 0;if(u!==void 0){o?(this.selectDecor(u),this.revealDecorPanel()):this.beginCameraDrag(t,u);return}o||this.beginCameraDrag(t);return}if(this.revealShapePanel(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(a.sourceId):this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),o||!l)return;const d=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===a.sourceId?a.shape:n.getInterpolatedShapeAt(r,h)??a.shape}));this.dragState={kind:"move",sources:d,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,o)=>n.indexOf(r)-n.indexOf(o)).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,o=n?.kind==="polygon"&&J.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId,shape:n}:this.ufoElement.shapeAt(t.x,t.y,It);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),a=l?this.ufoElement.sighting.decor.find(d=>d.id===l):void 0;a&&this.showDecorContextMenu(e.clientX,e.clientY,a)}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(u=>this.selectedSourceIds.has(u)),n=i.length<=s.length,r=s.length>0&&i.slice(i.length-s.length).every(u=>this.selectedSourceIds.has(u)),o=s.length>0&&i.slice(0,s.length).every(u=>this.selectedSourceIds.has(u));this.contextBringToFrontButton.disabled=n||r,this.contextSendToBackButton.disabled=n||o,this.contextBringToFrontButton.title=n?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=n?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const a=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),d=this.selectedSourceIds.size===1&&a?.kind==="polygon";this.contextAddVertexButton.disabled=!d,this.contextAddVertexButton.title=d?"":this.messages.notAPolygon;const h=d&&this.contextMenuPoint?J.hitTestVertex(a,this.contextMenuPoint):void 0,c=d&&a.points.length<=xn;this.contextDeleteVertexButton.disabled=!d||h===void 0||c,this.contextDeleteVertexButton.title=d?c?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 o=this.said.read(s.title)??s.id,l=this.messages;r.textContent=`${o} — ${n>=.995?l.masksBodyFully:n>.005?l.masksBodyPartly.replace("{share}",String(Math.round(n*100))):l.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(o=>o!==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=J.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=J.hitTestVertex(i,e);if(s===void 0)return;const n=J.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(Tt,(e.maxX-e.minX)/2*t.width),s=Math.max(Tt,(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,f)=>Math.max(m,(i.bottom-f.top)*s),0),o=Mt,l=Mt+jr,a=t.width-Mt,d=t.height-r-Mt,h=Math.max(e.x,o),c=Math.max(e.y,l),u=Math.min(e.x+e.width,a),p=Math.min(e.y+e.height,d);return u-h<Tt||p-c<Tt?e:{x:h,y:c,width:u-h,height:p-c}}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=J.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 c=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,u=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,p=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:p.headingDeg,pitchDeg:p.pitchDeg+u,rollDeg:p.rollDeg+c}:{headingDeg:p.headingDeg+c,pitchDeg:p.pitchDeg,rollDeg:p.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:s,startPointer:n,startSizeM:r,handle:o}=t,l=(c,u)=>Math.max(.05,Math.abs(c)/Math.max(1,Math.abs(u))),a=o==="e"||o==="w",d=o==="n"||o==="s",h=a?l(i.x-s.x,n.x-s.x):d?l(i.y-s.y,n.y-s.y):l(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:d?r.widthM:r.widthM*h,lengthM:d?r.lengthM:r.lengthM*h,heightM:a?r.heightM:r.heightM*h})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:ai};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:Zr};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=$i.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:tt.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(o=>o.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,It)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=tt.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),o=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,l=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,o);return!n||!l?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:l,grabHeightM:o,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&&is(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&is(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,o=t.y-n.y,l=s.map(({sourceId:a,original:d})=>({sourceId:a,shape:{...d,bounds:{...d.bounds,x:d.bounds.x+r,y:d.bounds.y+o}}}));this.commitShapes(i,l)}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,o=J.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:o}])}else{const{kind:s,sourceId:n,original:r,handle:o}=this.dragState,l=s==="resize"?J.resizeShape(r,o,t):J.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:l}])}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)<Yr)return;this.cameraDragState.moved=!0}const o=s+(t.x-i.x)*ai,l=Math.max(-90,Math.min(90,n-(t.y-i.y)*ai));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver(),this.rounded(o)!==this.rounded(s)&&(this.cameraDragState.headingTurned=!0),this.rounded(l)!==this.rounded(n)&&(this.cameraDragState.pitchTurned=!0),this.showOrientation(this.cameraDragState.headingTurned?o:void 0,this.cameraDragState.pitchTurned?l:void 0),this.showViewDragHint(e.altKey);const a=this.ufoElement.sighting.observerTrack,d=this.ufoElement.currentTime,h=a.allKeyframes.find(c=>c.t===d);h&&h.viewOnly===!0!==e.altKey&&(a.setViewOnly(d,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?io: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)*to*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)*eo*t,o=i*Math.PI/180,l=Ys(Math.sin(o)*r,-Math.cos(o)*r,s,n);this.latInput.value=l.lat.toFixed(7),this.lngInput.value=l.lng.toFixed(7);const a=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(a,this.plantingCentre()),this.surroundings.walked(l.lat,l.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=Es(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(l,a)=>Math.round((l-a)*1e3)/1e3,o=this.ufoElement.sighting;o.decor=o.decor.map(l=>({...l,eastM:r(l.eastM,s),northM:r(l.northM,n),...l.track?{track:l.track.map(a=>({...a,eastM:r(a.eastM,s),northM:r(a.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(Ji,i.width-Pe);break;case"ArrowRight":i.width+=Pe;break;case"ArrowUp":i.height=Math.max(Ji,i.height-Pe);break;case"ArrowDown":i.height+=Pe;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Pe;break;case"ArrowRight":i.x+=Pe;break;case"ArrowUp":i.y-=Pe;break;case"ArrowDown":i.y+=Pe;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 ti(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 l=r?this.bodyCanvasBounds():void 0,a=l&&J.hitTestHandle({bounds:l,angle:0},t);if(a)return this.cursorForHandle(a,0);const d=this.ndcOf(e),h=d&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(d.x,d.y):void 0;return r&&h?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const l=this.decorCanvasBounds(),a=l&&J.hitTestHandle({bounds:l,angle:0},t);if(a)return this.cursorForHandle(a,0);const d=this.editableDecor();if(d&&!this.ufoElement.shapeAt(t.x,t.y,It)&&this.grabsDecor(e,t,d))return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=J.hitTestHandle({bounds:new ti(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=s.getInterpolatedShapeAt(n,this.currentSourceId);if(l?.kind==="polygon"&&J.hitTestVertex(l,t)!==void 0)return"vertex";const a=l&&J.hitTestHandle(l,t);if(l&&a)return this.cursorForHandle(a,l.angle)}return s.hitTest(n,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${J.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(Ds(this.buildPrototype({x:0,y:0,width:qe.width,height:qe.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 ao={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},ws="rr0-sighting-editor";function zs(){Os(),ks(),_s(),mr(),ur(),br(),Ms(),customElements.get(ws)||customElements.define(ws,y)}const bi="rr0-case-editor",lo=`
|
|
2700
2701
|
<style>
|
|
2701
2702
|
/* What the layout adapts to: the width this editor is given, never the window's. */
|
|
2702
2703
|
:host { display: block; container-type: inline-size; }
|
|
@@ -3046,4 +3047,4 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
|
|
|
3046
3047
|
</form>
|
|
3047
3048
|
</dialog>
|
|
3048
3049
|
`;class Le extends HTMLElement{shadow=this.attachShadow({mode:"open"});editor;session;current;listShown=!0;currentInterview;interviewElement;interviewReady;group="events";fileEditor;fileEditorLoading;fileApplied="";editorMessages;messages=We.none();ready=Promise.resolve();said=new ct(["en"]);localeToken=0;language="en";dialogMode="add";pendingLoad;dirtyTimer;caseDate;dateModeFor;constructor(){super(),zs(),Os(),Ls.register(),this.shadow.innerHTML=lo,customElements.upgrade(this.shadow),this.shadow.getElementById("case-date").build();for(const t of this.shadow.querySelectorAll("rr0-input-file"))t.build();this.editor=this.shadow.getElementById("editor"),this.interviewElement=this.shadow.getElementById("interview"),this.interviewElement.addEventListener(Js,t=>this.interviewChanged(t.detail)),this.interviewElement.addEventListener(Xs,t=>void this.followToObservation(t.detail)),this.editor.addEventListener("caseloaded",t=>{t.preventDefault();const{json:i,url:s}=t.detail;this.openCase(i,s??location.href,s!==void 0&&!_e.local(s))}),this.editor.addEventListener("recordingloaded",()=>this.closeCase()),this.editor.addEventListener("sightingchange",()=>{clearTimeout(this.checkReadingTimer),this.checkReadingTimer=setTimeout(()=>this.checkReading(),Le.CHECK_READING_AFTER_MS)}),this.editor.guardsLeaving=!1,this.editor.addEventListener("beforeload",t=>{this.dirty&&(t.preventDefault(),this.pendingLoad=t.detail.proceed,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion))});for(const t of["input","change","datechange","click","pointerup","keyup"])this.shadow.addEventListener(t,()=>this.scheduleDirtyCheck(),!0);for(const[t,i]of[["case-id","id"],["case-title","title"]])this.input(t).addEventListener("input",()=>this.writeCaseField(i,this.input(t).value));this.caseDate=this.byId("case-date"),this.caseDate.addEventListener("datechange",t=>{const{time:i}=t.detail;this.writeCaseField("time",i?Le.rr0TimeOf(zn(i)):"")}),this.byId("track").addEventListener("change",()=>{this.byId("cited").hidden=!0,this.listShown=!1,this.refreshOverview();const t=this.session?this.items(this.session)[Number(this.byId("track").value)]:void 0;t&&(t.interview?this.showInterview(t.interview):this.showTrack(t.track))});const e=this.input("recording-id");e.addEventListener("input",()=>this.writeRecordingId()),e.addEventListener("blur",()=>{this.showRecordingIdError(void 0),this.refreshRow()});for(const t of this.shadow.querySelectorAll("#case-tabs .group-tab"))t.addEventListener("click",()=>this.openGroup(t.getAttribute("aria-controls")==="group-case-file"?"file":"events"));this.inputFile("import").addEventListener("filepick",t=>{const i=t.detail;i.file?this.importFromFile(i.file):this.importFromUrl(i.url)}),this.byId("add").addEventListener("click",()=>this.askAdd()),this.byId("group-readings").addEventListener("click",()=>{this.grouping=!this.grouping,Be.rememberGrouping(this.grouping),this.refreshOverview()}),this.byId("cited-back").addEventListener("click",()=>{const t=this.citedFrom;if(!t||!this.session)return;const i=this.items(this.session).findIndex(s=>s.interview===t);i>=0&&this.openEvent(i)}),this.byId("back-to-case").addEventListener("click",()=>{this.listShown=!0,this.refreshRow()}),this.byId("previous-event").addEventListener("click",()=>this.stepEvent(-1)),this.byId("next-event").addEventListener("click",()=>this.stepEvent(1)),this.shareDialog=this.byId("share-dialog"),Qs.register(),this.byId("report-export").source=async()=>{const t=this.session;if(!t)throw new Error("No case");this.commit(),await Promise.all(t.tracks.filter(s=>!s.recording).map(s=>this.loadTrack(s).catch(()=>{})));const i=new Map;for(const s of t.tracks)s.recording&&i.set(s.url,s.recording);return{caseJson:t.json,caseUrl:t.url,recordings:i}},this.shareDialog.subject=this.shareSubject,this.byId("share-case").addEventListener("click",()=>this.openShare()),this.byId("read-case").addEventListener("click",()=>this.read()),this.byId("save-case").addEventListener("click",()=>void this.exportCase(this.input("save-also").checked).then(()=>this.refreshDirty())),this.byId("make-case").addEventListener("click",()=>this.makeCase()),this.byId("delete").addEventListener("click",()=>this.askDelete()),this.byId("event-author").addEventListener("input",()=>this.writeEventAuthor()),this.byId("thaw").addEventListener("click",()=>{const t=this.current;!this.session||!t||(this.session.seal(t,!1),this.refreshRow())}),this.byId("export").addEventListener("click",()=>this.askExport()),this.byId("source").addEventListener("change",()=>this.syncSourceFields()),this.byId("kind").addEventListener("change",()=>this.syncSourceFields()),this.byId("of").addEventListener("change",()=>this.syncSourceFields()),this.byId("cancel").addEventListener("click",()=>this.closeDialog()),this.byId("dialog").addEventListener("close",()=>{this.pendingLoad=void 0}),this.byId("form").addEventListener("submit",t=>{t.preventDefault(),this.submitDialog()})}static get observedAttributes(){return["src",mt]}attributeChangedCallback(e,t,i){e===mt&&(i!==null&&!this.switcher&&new Gs(s=>this.after(s),this,s=>this.dispatchEvent(new CustomEvent(Ks,{detail:s,bubbles:!0,composed:!0}))),this.refreshCaseState()),e==="src"&&i&&this.editor.setAttribute("src",i)}warnBeforeLeaving=e=>{this.leaving||!this.dirty||(e.preventDefault(),e.returnValue="")};disconnectedCallback(){document.removeEventListener("click",this.askBeforeFollowing,!0),window.removeEventListener("beforeunload",this.warnBeforeLeaving),window.clearTimeout(this.dirtyTimer)}get dirty(){return this.session?(this.commit(),this.session.dirty):this.editor.dirty}scheduleDirtyCheck(){window.clearTimeout(this.dirtyTimer),this.dirtyTimer=window.setTimeout(()=>this.refreshDirty(),600)}refreshDirty(){const e=this.session;e&&this.commit(),this.byId("dirty").hidden=!(e&&e.dirty),this.refreshCaseState();const t=e?this.current!==void 0&&e.changed(this.current):this.editor.dirty;this.byId("recording-dirty").hidden=!t}leaving=!1;askBeforeFollowing=e=>{if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const t=e.composedPath().find(s=>s instanceof HTMLAnchorElement);if(!t||!t.href||t.target&&t.target!=="_self"||t.hasAttribute("download"))return;const i=new URL(t.href,location.href);i.href===location.href||i.origin===location.origin&&i.pathname===location.pathname&&i.search===location.search&&i.hash!==""||this.dirty&&(e.preventDefault(),e.stopPropagation(),this.pendingLoad=()=>{this.leaving=!0,location.assign(i.href)},this.openDialog("discard",this.messages.discardTitle,this.messages.leaveQuestion,this.messages.leaveOk))};connectedCallback(){document.addEventListener("click",this.askBeforeFollowing,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.editor.getAttribute("src")!==e&&this.editor.setAttribute("src",e),this.ready=this.loadLocale()}get sightingData(){return this.editor.sightingData}set sightingData(e){const t=$e.recording(e);this.closeCase(),this.editor.sightingData=t}get sightingEditor(){return this.editor}get caseSession(){return this.session}byId(e){return this.shadow.getElementById(e)}async loadLocale(){const e=++this.localeToken,t=ze.preferencesFor(this),i=hi(t,ci),[s,n,r]=await Promise.all([Vs.load(i),ys.load(i),Tn.load(i)]);if(e!==this.localeToken)return;this.said=new ct(t),this.language=i,this.messages=s,this.readingCheck=new Xi(r),this.bestCases=new Mn(r),this.caseDate.messages=n,this.editorMessages=n,this.applyMessages(),this.refreshRow(),this.showInterviewSources();const o=await this.shareDialog.useLanguage(i);!o||e!==this.localeToken||(this.shareMessages=o,this.byId("label-share-case").textContent=o.share,this.refreshCaseState())}applyMessages(){Ne.dialog(this.dialog,this.messages.cancel,()=>this.closeDialog());const e=this.messages,t=(r,o)=>{this.byId(r).textContent=o};t("case-kicker",e.caseHeading),t("label-back-to-case",e.caseHeading),t("label-events-in-time",e.eventsInTime),t("label-back-to-interview",e.backToInterview),t("label-add",e.addTitle),t("label-save-also",e.exportAlso),t("label-save-case",e.exportButton),t("label-read-case",e.readButton),this.byId("read-case").title=e.readTitle;for(const[r,o]of[["previous-event",e.previousEvent],["next-event",e.nextEvent]])this.byId(r).title=o,this.byId(r).setAttribute("aria-label",o);t("label-case-id",e.caseId),t("label-case-title",e.caseTitle),t("label-case-time",e.caseTime),t("label-events-group",e.eventsTab),t("label-case-file-group",e.fileTab),t("label-import-file",e.importFile),this.byId("track").setAttribute("aria-label",e.event),t("label-kind",e.kindField),t("label-witness",e.witnessField),t("label-medium",e.mediumField),t("label-recording-id",e.recordingId),t("make-case",e.addToCase);for(const r of["dirty","recording-dirty"])this.byId(r).title=e.unsavedChanges,this.byId(r).setAttribute("aria-label",e.unsavedChanges);t("export",e.exportButton),t("label-export-recordings",e.exportAlso),t("label-title",e.titleField),t("label-author",e.authorField),t("label-date",e.caseTime),t("label-of",e.interpretationOf),t("label-source",e.sourceField),t("label-observer",e.observerField),t("label-file",e.fileField);for(const r of this.shadow.querySelectorAll("rr0-input-file"))r.messages=e;t("ok",e.ok),t("cancel",e.cancel);const i=this.byId("source");[e.sourceBlank,e.sourceFile].forEach((r,o)=>{i.options[o].textContent=r});const s=this.byId("kind");[e.kindObservation,e.kindReading,e.kindInterview].forEach((r,o)=>{s.options[o].textContent=r});const n=this.byId("group-readings");n.title=e.groupReadings,n.setAttribute("aria-label",e.groupReadings),this.byId("add").title=e.addHint,this.byId("add").setAttribute("aria-label",e.addHint),this.byId("delete").title=e.deleteRecording,this.byId("label-thaw").textContent=e.thawButton,this.byId("delete").setAttribute("aria-label",e.deleteRecording)}openGroup(e){this.group=e;for(const t of this.shadow.querySelectorAll("#case-tabs .group-tab"))t.setAttribute("aria-expanded",String(t.getAttribute("aria-controls")===(e==="file"?"group-case-file":"group-events")));e==="file"?this.loadFileEditor().then(()=>this.syncFileEditor(),()=>this.showFileNote(this.messages.loadFailed,"error")):this.leaveFile(),this.refreshRow()}applySections(){const e=this.session,t=e===void 0||this.group==="events";this.byId("events-row").hidden=e===void 0,this.byId("group-events").hidden=!t,this.byId("group-case-file").hidden=e===void 0||this.group!=="file",this.byId("recording").hidden=this.currentInterview!==void 0,this.byId("interview-section").hidden=this.currentInterview===void 0,this.byId("history-slot").hidden=this.currentInterview!==void 0}showFileNote(e,t="info"){F.show(this.byId("case-file-note"),e,t)}fileText(){return this.session?JSON.stringify(this.session.json,null,2)+`
|
|
3049
|
-
`:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{await this.ready,this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([M(()=>import("./SightingFileEditor-Cllslp2u.js"),__vite__mapDeps([12,13,14]),import.meta.url),M(()=>import("./caseSchema-ChUB1-9j.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,s=>this.onFileEdited(s),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid,"error");return}if(!se.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{se.check(i)}catch(s){this.showFileNote(s instanceof Ot?s.said(this.messages.formatVersionError):this.messages.fileInvalid,"error");return}this.fileApplied=e,this.showFileNote(void 0),JSON.stringify(i)!==JSON.stringify(t.json)&&(t.replaceJson(i),this.current&&!t.tracks.includes(this.current)&&(this.current=void 0),this.currentInterview&&!t.interviews.includes(this.currentInterview)&&(this.currentInterview=void 0),this.refreshRow(),this.scheduleDirtyCheck())}leaveFile(){const e=this.session;if(e)if(this.current===void 0&&this.currentInterview===void 0){const t=e.tracks.find(i=>i.kind==="observer")??e.tracks[0];t&&this.showTrack(t)}else this.currentInterview&&(this.interviewElement.event=this.currentInterview)}guarded(e){if(!this.dirty){e();return}this.pendingLoad=e,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion)}async importFromFile(e){try{const t=JSON.parse(await e.text());this.guarded(()=>void this.importCase(t,new URL("case.json",location.href).href,!1))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importFromUrl(e){try{const t=new URL(e,location.href).href,i=await Je.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!se.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof Ot?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){se.check(e);const s=new oe(e,t);if(this.sourceUrl=i?t:void 0,s.tracks.length===0)throw new Error("A case with no recording has nothing to edit");this.session=s,this.current=void 0;const n=this.getAttribute("track"),r=n?new URL(n,t).href:void 0,o=s.tracks.find(l=>l.url===r)??s.tracks.find(l=>l.kind==="observer")??s.tracks[0];this.listShown=r===void 0,await this.showTrack(o)}closeCase(){this.session&&(this.session=void 0,this.current=void 0,this.currentInterview=void 0,this.editor.reading=!1,this.editor.accountShapeIds=void 0,this.refreshRow())}commit(){this.session&&this.current&&this.editor.edited&&this.session.keep(this.current,this.editor.sightingData)}async loadTrack(e){e.recording||(e.recording=$e.recording(await Je.recording(e.url)),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.editor.passages=void 0,this.editor.holdForNewScene();try{const i=!e.recording;await this.loadTrack(e);const s=t.accountOf(e);s&&await this.loadTrack(s),this.layMostFavourable(e),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&s?.recording?Le.shapesOf(s.recording):void 0;const n=e.kind==="observer"?t.readingsOf(e):[];for(const r of n)await this.loadTrack(r).catch(()=>{}),this.layMostFavourable(r);this.editor.readings=n.filter(r=>r.recording?.interpretation?.bodies.length||Lt.computes(r.recording?.interpretation,Dt.kinds())).map(r=>({id:r.event.id??t.proposedId(r),label:this.labelOf(r,t.tracks.indexOf(r)),interpretation:r.recording.interpretation})),this.editor.sightingData=structuredClone(e.recording),this.checked=void 0,this.checkReading(),i&&t.keep(e,this.editor.sightingData,!0),s&&s.loaded===void 0&&t.keep(s,s.recording,!0)}catch{this.showError(this.messages.loadFailed)}this.refreshRow(),this.showPassages(e),this.showInterviewSources()}}passagesToken=0;sourcesToken=0;async showInterviewSources(){const e=this.session,t=++this.sourcesToken;if(this.editor.interviewSources=void 0,!e||e.interviews.length===0)return;const{InterviewFile:i}=await M(async()=>{const{InterviewFile:o}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:o}},__vite__mapDeps([34,1]),import.meta.url),s=this.items(e),n=e.interviews.length===1,r=[];for(const o of e.interviews){const l=await this.transcriptOf(o);if(!l||!Array.isArray(l.segments))continue;const a=o.id;r.push({...n||a===void 0?{}:{id:a},label:this.optionLabel({interview:o},s.findIndex(d=>d.interview===o)),segments:l.segments.map((d,h)=>{const c=i.said(d)??"",u=c.length>80?`${c.slice(0,77)}…`:c;return{index:h,label:c===""?"":`${i.speakerName(l,d.speaker)}${this.messages.colon}${u}`}})})}t!==this.sourcesToken||r.length===0||(this.editor.interviewSources=r)}static CHECK_READING_AFTER_MS=250;checkReadingTimer;checked;checkReading(){clearTimeout(this.checkReadingTimer);const e=this.current,t=e&&this.session?this.session.accountOf(e):void 0;if(!e||e.kind!=="reading"||!t?.recording){this.checked=void 0,this.editor.markBeyondKnown([]),this.editor.setReadingBounds({});return}const i=this.editor.sightingData,s=JSON.stringify(i);if(this.checked&&this.checked.track===e&&this.checked.account===t.recording&&this.checked.text===s)return;this.checked={track:e,account:t.recording,text:s};const n=di.strip(t.recording).provenance,r=c=>n.at(c)?.range,o=r("time"),l=r("place.locations.0.lat"),a=r("place.locations.0.lng"),d=di.strip(t.recording).recording.lighting;this.editor.setReadingBounds({...typeof o=="string"?{time:o}:{},...d?{hour:c=>Xi.nearestLit(d,c,this.editor.sightingData)}:{},...Array.isArray(l)?{lat:l}:{},...Array.isArray(a)?{lng:a}:{}});const h=(this.readingCheck?.findingsOf(t.recording,i)??[]).filter(c=>c.outcome==="fails"&&c.path);this.editor.markBeyondKnown(h.map(c=>({path:c.path==="lighting"?"time":c.path,why:this.said.read(c.text)??""})))}async transcriptOf(e){const t=this.session;if(t)try{const{InterviewFile:i}=await M(async()=>{const{InterviewFile:n}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:n}},__vite__mapDeps([34,1]),import.meta.url),s=t.transcriptText(e);if(s!==void 0)return i.read(JSON.parse(s));if(e.url)return i.read(await Je.json(new URL(e.url,t.url??location.href).href))}catch{}}async showPassages(e){const t=this.session,i=++this.passagesToken;if(this.editor.passages=void 0,!t||e.kind!=="observer"||t.interviews.length===0)return;const{InterviewFile:s}=await M(async()=>{const{InterviewFile:l}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:l}},__vite__mapDeps([34,1]),import.meta.url);if(i!==this.passagesToken)return;const n=e.event.id??t.proposedId(e),r=[];for(const l of t.interviews){const a=await this.transcriptOf(l);if(!a||!Array.isArray(a.segments))continue;const d={...a,interviewOf:a.interviewOf??l.interviewOf};for(const h of s.passagesAbout(d,n))r.push({interview:l,json:a,passage:h})}if(i!==this.passagesToken||this.current!==e||r.length===0)return;const o=this.items(t);this.editor.passages=r.sort((l,a)=>l.passage.at-a.passage.at).map(({interview:l,json:a,passage:d})=>{const h=`${this.messages.passagesHeading} ${this.optionLabel({interview:l},o.findIndex(u=>u.interview===l))}`,c=d.text===void 0?"":d.range?d.text.slice(d.range[0],d.range[1]):d.text;return{at:d.at,clock:s.clock(d.at,!0),said:c===""?h:`${s.speakerName(a,d.speaker)}${this.messages.colon}${this.messages.quoted.replace("{text}",c.length>120?`${c.slice(0,117)}…`:c)}`,where:h,open:()=>void this.showInterview(l).then(()=>this.interviewElement.revealSegment(d.index))}})}async followToObservation(e){const t=this.session;if(!t)return;const i=t.tracks.find(n=>n.kind==="observer"&&(n.event.id??t.proposedId(n))===e.sighting)??t.tracks.find(n=>n.kind==="observer");if(!i)return;const s=this.currentInterview;this.listShown=!1,await this.showTrack(i),this.editor.openSection("group-temporal"),this.editor.seekTo(e.at),this.showCited(s,i,e),this.editor.showRender()}static shapesOf(e){const t=new Set;for(const i of e.timeline?.keyframes??[])for(const s of i.shapes??[])t.add(s.sourceId);return[...t]}items(e){return[...e.tracks.map(t=>({track:t})),...e.interviews.map(t=>({interview:t}))]}optionLabel(e,t){const i=this.session;if(e.interview){const r=i.intervieweesOf(e.interview),o=r.length>0?r.map(d=>this.labelOf(d,i.tracks.indexOf(d))).join(", "):this.said.read(e.interview.title);if(!o)return this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1));const l=e.interview.title?this.said.read(e.interview.title):"";return r.length>0&&i.interviews.some(d=>d!==e.interview&&i.intervieweesOf(d).some(h=>r.includes(h)))&&l?`${this.messages.interviewOf} ${o} (${l})`:`${this.messages.interviewOf} ${o}`}const s=e.track,n=this.labelOf(s,t);return s.kind==="observer"?`${this.messages.accountOf} ${n}`:n}async showInterview(e){const t=this.session;if(t&&(this.commit(),this.current=void 0,this.passagesToken++,this.editor.passages=void 0,this.currentInterview=e,this.refreshRow(),await this.ensureInterview(),this.currentInterview===e)){for(const i of t.intervieweesOf(e))await this.loadTrack(i).catch(()=>{});this.currentInterview===e&&(this.interviewElement.witnesses=t.tracks.filter(i=>i.kind==="observer").map(i=>({id:i.event.id??t.proposedId(i),label:this.labelOf(i,t.tracks.indexOf(i)),moments:this.momentsOf(i)})),this.interviewElement.documentUrl=t.url,this.interviewElement.transcriptText=t.transcriptText(e),this.interviewElement.event=e)}}ensureInterview(){return this.interviewReady??=M(async()=>{const{register:e}=await import("./InterviewEditorElement-BSXLlt4e.js");return{register:e}},__vite__mapDeps([35,1,3,4,5,6,7,8,9,36,19,37,34,18,20,21,22,23,24]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,s=this.currentInterview;if(!(!i||!s)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(s,e.text);for(const n of[s.interviewOf].flat()){const r=i.tracks.find(o=>o.kind==="observer"&&(o.event.id??i.proposedId(o))===n);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}eventsInTime(e){const t=this.items(e);return Be.inTime(t,{when:i=>String((i.track?.event??i.interview)?.time??""),kind:i=>this.kindOf(i),read:i=>{const s=i.track?.kind==="reading"?e.accountOf(i.track):void 0;return s?[{track:s}]:[]}})}momentsOf(e){return(e.recording?.milestones??[]).map(t=>{const i=this.said.read(t.note);return{at:t.t/1e3,label:this.said.read(t.label)??"",...i?{note:i}:{}}})}citedFrom;showCited(e,t,i){const s=this.byId("cited");if(this.citedFrom=e,!e||!this.session){s.hidden=!0;return}const n=this.momentsOf(t).find(o=>Math.abs(o.at-i.at)<.05),r=(i.quote??"").length>120?`${i.quote.slice(0,117)}…`:i.quote??"";this.byId("cited-text").textContent=this.messages.citedMoment.replace("{k}",n?.label??`${Math.round(i.at)} s`).replace("{title}",this.optionLabel({interview:e},0)).replace("{quote}",r),s.hidden=!1}kindOf(e){return e.interview?"interview":e.track.kind==="reading"?"reading":"observation"}kindLabel(e){return Be.kindLabel(e,this.messages)}refreshOverview(){const e=this.session,t=this.byId("case-overview"),i=this.byId("event-crumbs");if(t.hidden=!e||!this.listShown,i.hidden=!e||this.listShown,this.byId("event-item").hidden=e!==void 0&&this.listShown,this.byId("group-events").classList.toggle("one-open",e!==void 0&&!this.listShown),this.byId("events-count").textContent=e?String(this.items(e).length):"",this.byId("case-heading").textContent=e&&String(e.json.title??"")||this.messages.caseHeading,!e)return;const s=this.eventsInTime(e);this.renderEvents(e,s),this.compareReadings(e);const n=s.findIndex(({item:o})=>o.interview?o.interview===this.currentInterview:o.track===this.current),r=s[n];if(r){const o=this.kindOf(r.item),l=this.byId("crumb-kind");l.textContent=this.kindLabel(o),l.dataset.kind=o,this.byId("crumb-title").textContent=this.optionLabel(r.item,r.index)}this.byId("previous-event").disabled=n<=0,this.byId("next-event").disabled=n<0||n>=s.length-1}authorName(e){if("people"in e)return e.people;if("org"in e)return e.org;const t=e;return this.said.read(t.title)??t.id??""}authorsText(e){return(e??[]).map(t=>this.authorName(t)).filter(t=>t!=="").join(", ")}authorsSaid(e){const t=(e??[]).map(i=>this.authorName(i)).filter(i=>i!=="");return t.length<2?t.join(""):`${t.slice(0,-1).join(", ")} ${this.messages.linkAnd} ${t[t.length-1]}`}authorsFrom(e,t){const i=e.split(",").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.map(s=>(t??[]).find(n=>this.authorName(n)===s)??{title:s})}grouping=Be.groupingRemembered();folded=new Set;kindsShown=new Set(["observation","interview","reading"]);renderFilter(e){const t=this.messages,i=this.byId("event-filter"),s=["observation","reading","interview"].map(n=>({kind:n,count:e.filter(({item:r})=>this.kindOf(r)===n).length})).filter(({count:n})=>n>0);i.hidden=s.length<2,!i.hidden&&i.replaceChildren(...s.map(({kind:n,count:r})=>{const o=this.kindsShown.has(n),l=document.createElement("button");l.type="button",l.className="filter-chip",l.dataset.kind=n,l.setAttribute("aria-pressed",String(o));const a=document.createElement("span");a.textContent={observation:t.kindObservations,reading:t.kindReadings,interview:t.kindInterviews}[n];const d=document.createElement("span");return d.className="filter-count",d.textContent=String(r),l.append(a,d),l.addEventListener("click",()=>{const h=this.kindsShown.has(n);h&&!s.some(c=>c.kind!==n&&this.kindsShown.has(c.kind))||(h?this.kindsShown.delete(n):this.kindsShown.add(n),this.refreshOverview())}),l}))}renderEvents(e,t){const i=this.messages,s=this.byId("event-list"),n=t.filter(({item:p})=>this.kindsShown.has(this.kindOf(p)));this.renderFilter(t),this.byId("events-count").textContent=String(n.length);const r=p=>{const m=[p.track?.event.interpretationOf].flat().filter(f=>f!==void 0);return n.map(({item:f})=>f).filter(f=>f.track?.kind==="observer"&&m.some(g=>f.track.event.id===g||f.track.recording?.id===g))},o=n.some(({item:p})=>this.kindOf(p)==="reading"),l=this.byId("group-readings");l.hidden=!o,l.setAttribute("aria-pressed",String(this.grouping));const a=this.grouping?Be.grouped(n,{kind:p=>this.kindOf(p),read:r}):n,d=new Map(n.map(({item:p,index:m})=>[p,m])),h=p=>!this.listShown&&(p.interview?p.interview===this.currentInterview:p.track===this.current),u=a.filter(({item:p,under:m})=>m===void 0||!this.folded.has(d.get(m))||h(p)).map(({item:p,index:m,under:f})=>{const g=this.kindOf(p),b=p.track?.event??p.interview,v={at:m,kind:g,title:this.optionLabel(p,m),meta:[b.time?String(b.time).replace("T"," "):"",b.id??""].filter(Boolean).join(" · "),by:g==="observation"?"":this.authorsSaid(b.by),open:h(p),...f?{nested:!0}:{}},I=this.grouping&&g==="observation"?a.filter(S=>S.under===p).length:0;if(I>0&&(v.readings={count:I,folded:this.folded.has(m)}),p.track?.kind==="observer"){const S=e.interviews.filter(w=>e.intervieweesOf(w).includes(p.track)).map(w=>({at:e.tracks.length+e.interviews.indexOf(w),title:this.optionLabel({interview:w},0)}));S.length>0&&(v.links={heading:i.passagesHeading,to:S})}else if(p.track){const S=[p.track.event.interpretationOf].flat().filter(w=>w!==void 0).map(w=>e.tracks.find(x=>x.kind==="observer"&&(x.event.id===w||x.recording?.id===w))).filter(w=>w!==void 0).filter(w=>w!==f?.track).map(w=>({at:e.tracks.indexOf(w),title:this.labelOf(w,e.tracks.indexOf(w))}));S.length>0&&(v.links={heading:f?i.alsoAbout:i.interpretationOf,to:S})}return v});new Be(s,p=>this.openEvent(p),p=>this.openEvent(p),void 0,p=>{this.folded.delete(p)||this.folded.add(p),this.refreshOverview()}).render(u,i,(p,{card:m,body:f,links:g})=>this.dress(e,t.find(({index:b})=>b===p.at).item,p.at,m,f,g))}dress(e,t,i,s,n,r){const o=this.messages,l=r.textContent!=="",a=t.track?.kind==="reading"?this.findingsOf(t.track):void 0,d=Ln.of(a);if(d){s.dataset.verdict=d;const p=document.createElement("span");p.className="verdict",p.textContent=o.readingVerdict[d],r.prepend(p,...l?[document.createTextNode(" · ")]:[])}const h=t.track!==void 0&&oe.sealed(t.track.event);if(h){const p=r.textContent!=="";s.dataset.sealed="";const m=document.createElement("span");m.className="sealed-chip",m.textContent=o.sealedChip,r.prepend(m,...p?[document.createTextNode(" · ")]:[])}const c=document.createElement("span");if(c.className="event-tools",t.track){const p=document.createElement("button");p.type="button",p.className="icon-btn event-tool event-copy",p.innerHTML=D.COPY,p.title=o.cloneEvent,p.setAttribute("aria-label",o.cloneEvent),p.addEventListener("click",()=>void this.cloneFromList(i));const m=document.createElement("button");m.type="button",m.className="icon-btn event-tool event-freeze",m.innerHTML=h?D.LOCK:D.LOCK_OPEN,m.title=h?o.unfreezeEvent:o.freezeEvent,m.setAttribute("aria-label",m.title),m.setAttribute("aria-pressed",String(h)),m.addEventListener("click",()=>void this.toggleFrozen(i)),c.append(p,m)}const u=document.createElement("button");if(u.type="button",u.className="icon-btn event-delete",u.innerHTML=D.TRASH,u.title=h?o.deleteFrozen:o.deleteRecording,u.setAttribute("aria-label",u.title),u.disabled=h,u.addEventListener("click",()=>void this.deleteFromList(i)),c.append(u),a&&a.length>0&&n.append(this.findingsList(a)),t.track?.kind==="reading"&&t.track.recording){const p=Dn.create();p.show(e.accountOf(t.track)?.recording,t.track.recording),n.append(p)}s.append(c)}findingsOf(e){const t=this.session?.accountOf(e),i=[e,t].filter(r=>r!==void 0&&!r.recording);if(i.length>0){for(const r of i)this.fetchingFindings.has(r)||(this.fetchingFindings.add(r),this.loadTrack(r).then(()=>this.refreshOverview(),()=>{}));if(!e.recording)return}const s=e.recording.interpretation?.findings??[],n=t?.recording&&this.readingCheck?this.readingCheck.findingsOf(t.recording,e.recording):[];return[...s,...n]}fetchingFindings=new WeakSet;readingCheck;bestCases;laid=new WeakSet;layMostFavourable(e){if(e.kind!=="reading"||!e.recording||this.laid.has(e)||!this.bestCases)return;const t=this.session?.accountOf(e)?.recording;if(!t)return;this.laid.add(e);const i=this.bestCases.bestSceneOf(t,e.recording);i&&(e.recording=i,e.loaded=JSON.stringify(i))}findingsList(e){const t=this.messages,i=document.createElement("ul");i.className="findings";for(const s of e){const n=document.createElement("li");n.dataset.outcome=s.outcome;const r=document.createElement("span");r.className="finding-mark",r.textContent={holds:"✓",fails:"✗",untested:"?"}[s.outcome],r.title=t.findingOutcome[s.outcome],r.setAttribute("aria-label",t.findingOutcome[s.outcome]);const o=document.createElement("span");if(o.textContent=this.said.read(s.text)??"",n.append(r,o),s.outcome==="fails"){const l=document.createElement("span");l.className="finding-against",l.textContent=` (${t.findingAgainst[s.against??"established"]})`,n.append(l)}i.append(n)}return i}openEvent(e){const t=this.byId("track");t.value=String(e),t.dispatchEvent(new Event("change")),requestAnimationFrame(()=>this.bringEditorIntoView())}bringEditorIntoView(){const e=this.editor;if(!e.checkVisibility?.())return;const t=e.getBoundingClientRect();Math.abs(t.top)>1&&e.scrollIntoView?.({block:"start",behavior:"smooth"})}async cloneFromList(e){const t=this.session,s=(t?this.items(t)[e]:void 0)?.track;if(!t||!s)return;try{await this.loadTrack(s)}catch{this.showError(this.messages.loadFailed);return}const n=t.clone(s);if(!n)return;this.refreshRow();const r=this.items(t).findIndex(o=>o.track===n);r>=0&&this.openEvent(r)}async toggleFrozen(e){const t=this.session,s=(t?this.items(t)[e]:void 0)?.track;!t||!s||(!oe.sealed(s.event)&&this.current===s&&this.commit(),t.seal(s,!oe.sealed(s.event)),this.refreshRow())}refreshEventAuthor(){const e=this.currentInterview?void 0:this.current,t=this.currentInterview??(e?.kind==="reading"?e.event:void 0),i=this.byId("row-event-author");if(i.hidden=t===void 0,!t)return;this.byId("label-event-author").textContent=this.currentInterview?this.messages.interviewerField:this.messages.authorField;const s=this.input("event-author");this.shadow.activeElement!==s&&(s.value=this.authorsText(t.by)),s.disabled=e!==void 0&&oe.sealed(e.event)}writeEventAuthor(){const e=this.session,t=this.currentInterview?void 0:this.current,i=this.currentInterview??(t?.kind==="reading"?t.event:void 0);if(!e||!i||t&&oe.sealed(t.event))return;const s=this.authorsFrom(this.input("event-author").value,i.by);s?i.by=s:delete i.by;const n=t?.recording?.interpretation;n&&(s?n.by=s:delete n.by),e.touch(),this.refreshOverview(),this.refreshDirty()}showFrozen(e){this.byId("frozen-note").hidden=!e,this.byId("frozen-text").textContent=e?this.messages.frozenNote:"",this.editor.toggleAttribute("inert",e)}async deleteFromList(e){const t=this.session,i=t?this.items(t)[e]:void 0;i&&(this.byId("track").value=String(e),i.interview?await this.showInterview(i.interview):await this.showTrack(i.track),this.askDelete())}stepEvent(e){const t=this.session;if(!t)return;const i=this.eventsInTime(t),s=i.findIndex(({item:r})=>r.interview?r.interview===this.currentInterview:r.track===this.current),n=i[s+e];n&&this.openEvent(n.index)}refreshCaseState(){this.byId("save-case").disabled=!(this.session?.dirty??!1);const e=this.byId("share-case");e.disabled=this.sourceUrl===void 0,e.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"";const t=this.byId("read-case");t.hidden=!this.hasAttribute(mt)&&this.readAddress()===void 0,this.session&&t.parentElement!==e.parentElement?e.before(t):!this.session&&t.parentElement!==this.editor&&(t.slot="head-actions",this.editor.append(t))}switcher;readAddress(){return this.session?this.sourceUrl:this.editor.address}read(){const e=this.readAddress();if(this.hasAttribute(mt)){const i=this.holdForReading();if(qs.ask(this,Zs,i))return;_e.releaseCopies()}if(e===void 0)return;const t=this.session?this.sharedTrack:void 0;window.open(`${gi.home()}/play/?file=${encodeURIComponent(e)}${t?`&events=${encodeURIComponent(Le.fileKey(t))}`:""}`,"_blank","noopener")}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}holdForReading(){const e=new Map,t=this.session;if(t){this.commit();const n=this.sourceUrl===void 0;e.set(t.url,{json:t.json,changed:t.dirty,local:n});for(const r of t.tracks)r.recording&&e.set(r.url,{json:r.recording,changed:t.changed(r),local:n});return _e.releaseCopies(),_e.hold(e),{src:t.url,...this.sharedTrack?{track:this.sharedTrack}:{}}}const i=this.editor.address,s=i??new URL("recording.json",location.href).href;return e.set(s,{json:this.editor.sightingData,changed:this.editor.dirty,local:i===void 0}),_e.releaseCopies(),_e.hold(e),{src:s}}askBeforeReplacing(e){this.guarded(()=>{this.leaving=!0,e()})}async openTrack(e){const t=this.session;if(!t)return;const i=new URL(e,location.href).href,s=t.tracks.find(n=>n.url===i);!s||s===this.current&&!this.listShown&&!this.currentInterview||(this.listShown=!1,await this.showTrack(s))}sourceUrl;shareDialog;shareMessages;get sharedTrack(){return this.currentInterview?void 0:this.current?.url}shareSubject={module:"rr0-sighting-editor",link:()=>{const e=this.sharedTrack;return`${gi.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}${e?`&track=${encodeURIComponent(e)}`:""}`},element:()=>{const e=this.sharedTrack;return`<rr0-case-editor src="${this.sourceUrl??""}"${e?` track="${e}"`:""}></rr0-case-editor>`}};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.session?.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}compareReadings(e){en.register();const t=this.byId("readings-comparison");t.toggleAttribute("data-filtered",!this.kindsShown.has("reading"));const i=()=>e.tracks.flatMap((s,n)=>{if(s.kind!=="reading")return[];const r=e.accountOf(s);return[{title:this.labelOf(s,n),witness:r?this.labelOf(r,e.tracks.indexOf(r)):"",...s.recording?{reading:s.recording}:{},...r?.recording?{account:r.recording}:{},open:()=>this.openFromTable(e,s)}]});t.show(i(),async()=>{const s=e.tracks.filter(n=>n.kind==="reading").flatMap(n=>[n,e.accountOf(n)]).filter(n=>n!==void 0&&!n.recording);return await Promise.all([...new Set(s)].map(n=>this.loadTrack(n).catch(()=>{}))),i()})}openFromTable(e,t){const i=this.items(e).findIndex(n=>n.track===t);if(i<0)return;const s=this.byId("track");s.value=String(i),s.dispatchEvent(new Event("change"))}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const s=this.session.tracks.filter(n=>n.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(s||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time,i=typeof t=="object"?t.value:t,s=i?Le.rr0TimeOf(i):void 0,n=this.said.read(e.observer?.title),r=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=oe.around(e,s,n,r,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:Un(Le.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const s=this.input("case-time");s.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&ot.opensPrecise(i)),this.dateModeFor=e)}refreshRow(){const e=this.session;if(this.applySections(),this.byId("case-panel").hidden=e===void 0,this.refreshOverview(),this.byId("make-case-row").hidden=e!==void 0,this.byId("case").classList.toggle("in-case",e!==void 0),this.byId("event-item").classList.toggle("in-case",e!==void 0),this.holdEditor(e!==void 0),!e){this.refreshDirty();return}const t=this.shadow.activeElement;for(const[o,l]of[["case-id","id"],["case-title","title"]]){const a=this.input(o);a!==t&&(a.value=String(e.json[l]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),s=this.items(e);i.replaceChildren(...s.map((o,l)=>new Option(this.optionLabel(o,l),String(l))));const n=this.currentInterview?s.findIndex(o=>o.interview===this.currentInterview):this.current?s.findIndex(o=>o.track===this.current):0;i.value=String(Math.max(0,n));const r=this.currentInterview===void 0&&this.current!==void 0&&oe.sealed(this.current.event);this.byId("delete").disabled=r||this.currentInterview===void 0&&e.tracks.length<=1,this.showFrozen(r),this.refreshEventAuthor(),this.refreshRecordingId(e),this.refreshDirty()}holdEditor(e){this.editor.embedded=e,e&&this.byId("history-slot").append(this.editor.historyControls),this.shadow.querySelector(".event-id-row").hidden=!e}refreshRecordingId(e){const t=this.current,i=t!==void 0&&t.kind==="observer";if(this.byId("row-recording-id").hidden=!i,i){const l=this.input("recording-id");this.shadow.activeElement!==l&&(l.value=t.event.id??""),l.placeholder=e.proposedId(t),l.disabled=oe.sealed(t.event),l.title=l.disabled?this.messages.frozenNote:""}const{duplicateIds:s,unresolved:n}=e.problems(),r=[...s.map(l=>this.messages.idDuplicated.replace("{id}",l)),...n.map(({reference:l})=>this.messages.readingUnresolved.replace("{id}",l))],o=this.byId("case-problems");o.hidden=r.length===0,o.textContent=r.join(" ")}showRecordingIdError(e){const t=this.byId("recording-id-error");t.textContent=e??"",t.hidden=e===void 0}writeRecordingId(){const e=this.session,t=this.current;if(!e||!t)return;const i=e.setId(t,this.input("recording-id").value.trim());this.showRecordingIdError(i==="ok"?void 0:{empty:this.messages.idNeeded,invalid:this.messages.idInvalid,taken:this.messages.idTaken}[i]),this.scheduleDirtyCheck()}get dialog(){return this.byId("dialog")}openDialog(e,t,i,s,n){this.dialogMode=e,this.byId("dialog-title").textContent=t;const r=this.byId("dialog-message");if(r.textContent=i??"",r.hidden=i===void 0,this.showError(void 0),this.byId("fields-add").hidden=e!=="add",this.byId("fields-export").hidden=e!=="export",this.byId("ok").hidden=!1,this.byId("ok").textContent=s??(e==="discard"?this.messages.discardOk:this.messages.ok),this.dialog.classList.toggle("anchored",n!==void 0),n){const o=n.getBoundingClientRect();this.dialog.style.top=`${Math.round(o.bottom+6)}px`,this.dialog.style.right=`${Math.max(8,Math.round(window.innerWidth-o.right))}px`,this.dialog.style.left="auto",typeof this.dialog.show=="function"?this.dialog.show():this.dialog.setAttribute("open",""),this.beside??=l=>{const a=l.composedPath();(l instanceof KeyboardEvent?l.key==="Escape":!a.includes(this.dialog)&&!a.includes(this.anchor))&&this.closeDialog()},this.anchor=n,document.addEventListener("pointerdown",this.beside,!0),document.addEventListener("keydown",this.beside,!0);return}this.dialog.style.removeProperty("top"),this.dialog.style.removeProperty("right"),this.dialog.style.removeProperty("left"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open","")}beside;anchor;closeDialog(){this.beside&&(document.removeEventListener("pointerdown",this.beside,!0),document.removeEventListener("keydown",this.beside,!0)),this.pendingLoad=void 0,typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}showError(e){const t=this.byId("dialog-error");t.textContent=e??"",t.hidden=e===void 0}input(e){return this.byId(e)}inputFile(e){return this.byId(e)}today(){return new Date().toISOString().slice(0,10)}askAdd(){const e=this.session;if(!e)return;this.openDialog("add",this.messages.addTitle,void 0,void 0,this.byId("add"));const t=this.byId("of");t.replaceChildren(...e.tracks.filter(n=>n.kind==="observer").map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n)))));const i=this.byId("kind");i.value="observation",i.options[1].disabled=t.options.length===0;const s=e.tracks.filter(n=>n.kind==="observer");this.byId("witness").replaceChildren(...s.map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n))))),this.byId("medium").replaceChildren(),this.byId("source").value="blank";for(const n of["observer","title","author"])this.input(n).value="";this.inputFile("add-source").clear(),this.input("date").value="",this.syncSourceFields()}async fillMedia(){const{InterviewMedia:e}=await M(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value,t=e==="interview",i=this.byId("source").value,s=e==="reading";this.byId("row-source").hidden=t,this.byId("row-of").hidden=!s,this.byId("row-witness").hidden=!t,this.byId("row-medium").hidden=!t,t&&this.fillMedia(),this.byId("row-file").hidden=t||i!=="file",this.byId("row-observer").hidden=t||s,this.byId("row-title").hidden=!(t||s),this.byId("row-author").hidden=!(t||s),this.byId("label-title").textContent=t?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=t?this.messages.interviewerField:this.messages.investigatorField;const n=this.input("date");n.disabled=s,s&&(n.value=this.today())}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const c=e.tracks[Number(this.byId("witness").value)],u=this.input("title").value.trim(),p=this.input("author").value.trim(),m=e.addInterview(c,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?p.split(",").map(f=>({people:f.trim()})).filter(f=>f.people!==""):void 0,this.byId("medium").value);return await this.showInterview(m),!0}const t=this.byId("of").value,i=this.byId("kind").value==="reading"&&t!==""?e.tracks[Number(t)]:void 0,s=this.byId("source").value;if(i&&s==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const c=this.input("title").value.trim(),u=this.input("author").value.trim(),p=e.addReading(i,this.input("date").value||this.today(),c!==""?c:void 0,u!==""?[{title:u}]:void 0);return this.showTrack(p),!0}const n=this.input("observer").value.trim(),r=this.input("date").value.trim();let o;try{if(s==="blank"){const c=(n||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";o={version:4,id:`${r?`${r}-`:""}${c}`,...n?{observer:{title:n}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const c=await this.readFile();if(se.isCase(c))return this.showError(this.messages.isACase),!1;o=c,n&&!o.observer?.title&&(o={...o,observer:{...o.observer,title:n}})}}catch{return this.showError(this.messages.loadFailed),!1}const l=(i?this.input("title").value:n).trim(),a=l!==""?l:this.said.read(o.observer?.title),d=this.input("author").value.trim(),h=e.addObservation(o,r!==""?r:void 0,a,i?{account:i,by:d!==""?[{title:d}]:void 0}:void 0);return this.showTrack(h),!0}async readFile(){const e=this.inputFile("add-source").value;if(!e)throw new Error("No file");if(e.url)return Je.recording(new URL(e.url,location.href).href);const t=e.file,i=await new Promise((s,n)=>{const r=new FileReader;r.onload=()=>s(r.result),r.onerror=()=>n(r.error),r.readAsText(t)});return JSON.parse(i)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(o=>o.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const s=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,s&&this.showTrack(s))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const o of t.tracks)await this.loadTrack(o)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:s,strToU8:n}=await M(async()=>{const{zipSync:o,strToU8:l}=await import("./browser-CltifEM0.js");return{zipSync:o,strToU8:l}},[],import.meta.url),r={};for(const o of i)r[o.path]=n(o.content);return this.download(new Blob([s(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}}function ho(){zs(),customElements.get(bi)||customElements.define(bi,Le)}const So=Object.freeze(Object.defineProperty({__proto__:null,CASE_EDITOR_ELEMENT_NAME:bi,CaseEditorElement:Le,register:ho},Symbol.toStringTag,{value:"Module"}));export{So as C,De as I,gs as M};
|
|
3050
|
+
`:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{await this.ready,this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([M(()=>import("./SightingFileEditor-Cllslp2u.js"),__vite__mapDeps([12,13,14]),import.meta.url),M(()=>import("./caseSchema-ChUB1-9j.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,s=>this.onFileEdited(s),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid,"error");return}if(!se.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{se.check(i)}catch(s){this.showFileNote(s instanceof Ot?s.said(this.messages.formatVersionError):this.messages.fileInvalid,"error");return}this.fileApplied=e,this.showFileNote(void 0),JSON.stringify(i)!==JSON.stringify(t.json)&&(t.replaceJson(i),this.current&&!t.tracks.includes(this.current)&&(this.current=void 0),this.currentInterview&&!t.interviews.includes(this.currentInterview)&&(this.currentInterview=void 0),this.refreshRow(),this.scheduleDirtyCheck())}leaveFile(){const e=this.session;if(e)if(this.current===void 0&&this.currentInterview===void 0){const t=e.tracks.find(i=>i.kind==="observer")??e.tracks[0];t&&this.showTrack(t)}else this.currentInterview&&(this.interviewElement.event=this.currentInterview)}guarded(e){if(!this.dirty){e();return}this.pendingLoad=e,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion)}async importFromFile(e){try{const t=JSON.parse(await e.text());this.guarded(()=>void this.importCase(t,new URL("case.json",location.href).href,!1))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importFromUrl(e){try{const t=new URL(e,location.href).href,i=await Je.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!se.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof Ot?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){se.check(e);const s=new oe(e,t);if(this.sourceUrl=i?t:void 0,s.tracks.length===0)throw new Error("A case with no recording has nothing to edit");this.session=s,this.current=void 0;const n=this.getAttribute("track"),r=n?new URL(n,t).href:void 0,o=s.tracks.find(l=>l.url===r)??s.tracks.find(l=>l.kind==="observer")??s.tracks[0];this.listShown=r===void 0,await this.showTrack(o)}closeCase(){this.session&&(this.session=void 0,this.current=void 0,this.currentInterview=void 0,this.editor.reading=!1,this.editor.accountShapeIds=void 0,this.refreshRow())}commit(){this.session&&this.current&&this.editor.edited&&this.session.keep(this.current,this.editor.sightingData)}async loadTrack(e){e.recording||(e.recording=$e.recording(await Je.recording(e.url)),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.editor.passages=void 0,this.editor.holdForNewScene();try{const i=!e.recording;await this.loadTrack(e);const s=t.accountOf(e);s&&await this.loadTrack(s),this.layMostFavourable(e),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&s?.recording?Le.shapesOf(s.recording):void 0;const n=e.kind==="observer"?t.readingsOf(e):[];for(const r of n)await this.loadTrack(r).catch(()=>{}),this.layMostFavourable(r);this.editor.readings=n.filter(r=>r.recording?.interpretation?.bodies.length||Lt.computes(r.recording?.interpretation,Dt.kinds())).map(r=>({id:r.event.id??t.proposedId(r),label:this.labelOf(r,t.tracks.indexOf(r)),interpretation:r.recording.interpretation})),this.editor.sightingData=structuredClone(e.recording),this.checked=void 0,this.checkReading(),i&&t.keep(e,this.editor.sightingData,!0),s&&s.loaded===void 0&&t.keep(s,s.recording,!0)}catch{this.showError(this.messages.loadFailed)}this.refreshRow(),this.showPassages(e),this.showInterviewSources()}}passagesToken=0;sourcesToken=0;async showInterviewSources(){const e=this.session,t=++this.sourcesToken;if(this.editor.interviewSources=void 0,!e||e.interviews.length===0)return;const{InterviewFile:i}=await M(async()=>{const{InterviewFile:o}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:o}},__vite__mapDeps([34,1]),import.meta.url),s=this.items(e),n=e.interviews.length===1,r=[];for(const o of e.interviews){const l=await this.transcriptOf(o);if(!l||!Array.isArray(l.segments))continue;const a=o.id;r.push({...n||a===void 0?{}:{id:a},label:this.optionLabel({interview:o},s.findIndex(d=>d.interview===o)),segments:l.segments.map((d,h)=>{const c=i.said(d)??"",u=c.length>80?`${c.slice(0,77)}…`:c;return{index:h,label:c===""?"":`${i.speakerName(l,d.speaker)}${this.messages.colon}${u}`}})})}t!==this.sourcesToken||r.length===0||(this.editor.interviewSources=r)}static CHECK_READING_AFTER_MS=250;checkReadingTimer;checked;checkReading(){clearTimeout(this.checkReadingTimer);const e=this.current,t=e&&this.session?this.session.accountOf(e):void 0;if(!e||e.kind!=="reading"||!t?.recording){this.checked=void 0,this.editor.markBeyondKnown([]),this.editor.setReadingBounds({});return}const i=this.editor.sightingData,s=JSON.stringify(i);if(this.checked&&this.checked.track===e&&this.checked.account===t.recording&&this.checked.text===s)return;this.checked={track:e,account:t.recording,text:s};const n=di.strip(t.recording).provenance,r=c=>n.at(c)?.range,o=r("time"),l=r("place.locations.0.lat"),a=r("place.locations.0.lng"),d=di.strip(t.recording).recording.lighting;this.editor.setReadingBounds({...typeof o=="string"?{time:o}:{},...d?{hour:c=>Xi.nearestLit(d,c,this.editor.sightingData)}:{},...Array.isArray(l)?{lat:l}:{},...Array.isArray(a)?{lng:a}:{}});const h=(this.readingCheck?.findingsOf(t.recording,i)??[]).filter(c=>c.outcome==="fails"&&c.path);this.editor.markBeyondKnown(h.map(c=>({path:c.path==="lighting"?"time":c.path,why:this.said.read(c.text)??""})))}async transcriptOf(e){const t=this.session;if(t)try{const{InterviewFile:i}=await M(async()=>{const{InterviewFile:n}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:n}},__vite__mapDeps([34,1]),import.meta.url),s=t.transcriptText(e);if(s!==void 0)return i.read(JSON.parse(s));if(e.url)return i.read(await Je.json(new URL(e.url,t.url??location.href).href))}catch{}}async showPassages(e){const t=this.session,i=++this.passagesToken;if(this.editor.passages=void 0,!t||e.kind!=="observer"||t.interviews.length===0)return;const{InterviewFile:s}=await M(async()=>{const{InterviewFile:l}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:l}},__vite__mapDeps([34,1]),import.meta.url);if(i!==this.passagesToken)return;const n=e.event.id??t.proposedId(e),r=[];for(const l of t.interviews){const a=await this.transcriptOf(l);if(!a||!Array.isArray(a.segments))continue;const d={...a,interviewOf:a.interviewOf??l.interviewOf};for(const h of s.passagesAbout(d,n))r.push({interview:l,json:a,passage:h})}if(i!==this.passagesToken||this.current!==e||r.length===0)return;const o=this.items(t);this.editor.passages=r.sort((l,a)=>l.passage.at-a.passage.at).map(({interview:l,json:a,passage:d})=>{const h=`${this.messages.passagesHeading} ${this.optionLabel({interview:l},o.findIndex(u=>u.interview===l))}`,c=d.text===void 0?"":d.range?d.text.slice(d.range[0],d.range[1]):d.text;return{at:d.at,clock:s.clock(d.at,!0),said:c===""?h:`${s.speakerName(a,d.speaker)}${this.messages.colon}${this.messages.quoted.replace("{text}",c.length>120?`${c.slice(0,117)}…`:c)}`,where:h,open:()=>void this.showInterview(l).then(()=>this.interviewElement.revealSegment(d.index))}})}async followToObservation(e){const t=this.session;if(!t)return;const i=t.tracks.find(n=>n.kind==="observer"&&(n.event.id??t.proposedId(n))===e.sighting)??t.tracks.find(n=>n.kind==="observer");if(!i)return;const s=this.currentInterview;this.listShown=!1,await this.showTrack(i),this.editor.openSection("group-temporal"),this.editor.seekTo(e.at),this.showCited(s,i,e),this.editor.showRender()}static shapesOf(e){const t=new Set;for(const i of e.timeline?.keyframes??[])for(const s of i.shapes??[])t.add(s.sourceId);return[...t]}items(e){return[...e.tracks.map(t=>({track:t})),...e.interviews.map(t=>({interview:t}))]}optionLabel(e,t){const i=this.session;if(e.interview){const r=i.intervieweesOf(e.interview),o=r.length>0?r.map(d=>this.labelOf(d,i.tracks.indexOf(d))).join(", "):this.said.read(e.interview.title);if(!o)return this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1));const l=e.interview.title?this.said.read(e.interview.title):"";return r.length>0&&i.interviews.some(d=>d!==e.interview&&i.intervieweesOf(d).some(h=>r.includes(h)))&&l?`${this.messages.interviewOf} ${o} (${l})`:`${this.messages.interviewOf} ${o}`}const s=e.track,n=this.labelOf(s,t);return s.kind==="observer"?`${this.messages.accountOf} ${n}`:n}async showInterview(e){const t=this.session;if(t&&(this.commit(),this.current=void 0,this.passagesToken++,this.editor.passages=void 0,this.currentInterview=e,this.refreshRow(),await this.ensureInterview(),this.currentInterview===e)){for(const i of t.intervieweesOf(e))await this.loadTrack(i).catch(()=>{});this.currentInterview===e&&(this.interviewElement.witnesses=t.tracks.filter(i=>i.kind==="observer").map(i=>({id:i.event.id??t.proposedId(i),label:this.labelOf(i,t.tracks.indexOf(i)),moments:this.momentsOf(i)})),this.interviewElement.documentUrl=t.url,this.interviewElement.transcriptText=t.transcriptText(e),this.interviewElement.event=e)}}ensureInterview(){return this.interviewReady??=M(async()=>{const{register:e}=await import("./InterviewEditorElement-DiT6FZnj.js");return{register:e}},__vite__mapDeps([35,1,3,4,5,6,7,8,9,36,19,37,34,18,20,21,22,23,24]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,s=this.currentInterview;if(!(!i||!s)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(s,e.text);for(const n of[s.interviewOf].flat()){const r=i.tracks.find(o=>o.kind==="observer"&&(o.event.id??i.proposedId(o))===n);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}eventsInTime(e){const t=this.items(e);return Be.inTime(t,{when:i=>String((i.track?.event??i.interview)?.time??""),kind:i=>this.kindOf(i),read:i=>{const s=i.track?.kind==="reading"?e.accountOf(i.track):void 0;return s?[{track:s}]:[]}})}momentsOf(e){return(e.recording?.milestones??[]).map(t=>{const i=this.said.read(t.note);return{at:t.t/1e3,label:this.said.read(t.label)??"",...i?{note:i}:{}}})}citedFrom;showCited(e,t,i){const s=this.byId("cited");if(this.citedFrom=e,!e||!this.session){s.hidden=!0;return}const n=this.momentsOf(t).find(o=>Math.abs(o.at-i.at)<.05),r=(i.quote??"").length>120?`${i.quote.slice(0,117)}…`:i.quote??"";this.byId("cited-text").textContent=this.messages.citedMoment.replace("{k}",n?.label??`${Math.round(i.at)} s`).replace("{title}",this.optionLabel({interview:e},0)).replace("{quote}",r),s.hidden=!1}kindOf(e){return e.interview?"interview":e.track.kind==="reading"?"reading":"observation"}kindLabel(e){return Be.kindLabel(e,this.messages)}refreshOverview(){const e=this.session,t=this.byId("case-overview"),i=this.byId("event-crumbs");if(t.hidden=!e||!this.listShown,i.hidden=!e||this.listShown,this.byId("event-item").hidden=e!==void 0&&this.listShown,this.byId("group-events").classList.toggle("one-open",e!==void 0&&!this.listShown),this.byId("events-count").textContent=e?String(this.items(e).length):"",this.byId("case-heading").textContent=e&&String(e.json.title??"")||this.messages.caseHeading,!e)return;const s=this.eventsInTime(e);this.renderEvents(e,s),this.compareReadings(e);const n=s.findIndex(({item:o})=>o.interview?o.interview===this.currentInterview:o.track===this.current),r=s[n];if(r){const o=this.kindOf(r.item),l=this.byId("crumb-kind");l.textContent=this.kindLabel(o),l.dataset.kind=o,this.byId("crumb-title").textContent=this.optionLabel(r.item,r.index)}this.byId("previous-event").disabled=n<=0,this.byId("next-event").disabled=n<0||n>=s.length-1}authorName(e){if("people"in e)return e.people;if("org"in e)return e.org;const t=e;return this.said.read(t.title)??t.id??""}authorsText(e){return(e??[]).map(t=>this.authorName(t)).filter(t=>t!=="").join(", ")}authorsSaid(e){const t=(e??[]).map(i=>this.authorName(i)).filter(i=>i!=="");return t.length<2?t.join(""):`${t.slice(0,-1).join(", ")} ${this.messages.linkAnd} ${t[t.length-1]}`}authorsFrom(e,t){const i=e.split(",").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.map(s=>(t??[]).find(n=>this.authorName(n)===s)??{title:s})}grouping=Be.groupingRemembered();folded=new Set;kindsShown=new Set(["observation","interview","reading"]);renderFilter(e){const t=this.messages,i=this.byId("event-filter"),s=["observation","reading","interview"].map(n=>({kind:n,count:e.filter(({item:r})=>this.kindOf(r)===n).length})).filter(({count:n})=>n>0);i.hidden=s.length<2,!i.hidden&&i.replaceChildren(...s.map(({kind:n,count:r})=>{const o=this.kindsShown.has(n),l=document.createElement("button");l.type="button",l.className="filter-chip",l.dataset.kind=n,l.setAttribute("aria-pressed",String(o));const a=document.createElement("span");a.textContent={observation:t.kindObservations,reading:t.kindReadings,interview:t.kindInterviews}[n];const d=document.createElement("span");return d.className="filter-count",d.textContent=String(r),l.append(a,d),l.addEventListener("click",()=>{const h=this.kindsShown.has(n);h&&!s.some(c=>c.kind!==n&&this.kindsShown.has(c.kind))||(h?this.kindsShown.delete(n):this.kindsShown.add(n),this.refreshOverview())}),l}))}renderEvents(e,t){const i=this.messages,s=this.byId("event-list"),n=t.filter(({item:p})=>this.kindsShown.has(this.kindOf(p)));this.renderFilter(t),this.byId("events-count").textContent=String(n.length);const r=p=>{const m=[p.track?.event.interpretationOf].flat().filter(f=>f!==void 0);return n.map(({item:f})=>f).filter(f=>f.track?.kind==="observer"&&m.some(g=>f.track.event.id===g||f.track.recording?.id===g))},o=n.some(({item:p})=>this.kindOf(p)==="reading"),l=this.byId("group-readings");l.hidden=!o,l.setAttribute("aria-pressed",String(this.grouping));const a=this.grouping?Be.grouped(n,{kind:p=>this.kindOf(p),read:r}):n,d=new Map(n.map(({item:p,index:m})=>[p,m])),h=p=>!this.listShown&&(p.interview?p.interview===this.currentInterview:p.track===this.current),u=a.filter(({item:p,under:m})=>m===void 0||!this.folded.has(d.get(m))||h(p)).map(({item:p,index:m,under:f})=>{const g=this.kindOf(p),b=p.track?.event??p.interview,v={at:m,kind:g,title:this.optionLabel(p,m),meta:[b.time?String(b.time).replace("T"," "):"",b.id??""].filter(Boolean).join(" · "),by:g==="observation"?"":this.authorsSaid(b.by),open:h(p),...f?{nested:!0}:{}},I=this.grouping&&g==="observation"?a.filter(S=>S.under===p).length:0;if(I>0&&(v.readings={count:I,folded:this.folded.has(m)}),p.track?.kind==="observer"){const S=e.interviews.filter(w=>e.intervieweesOf(w).includes(p.track)).map(w=>({at:e.tracks.length+e.interviews.indexOf(w),title:this.optionLabel({interview:w},0)}));S.length>0&&(v.links={heading:i.passagesHeading,to:S})}else if(p.track){const S=[p.track.event.interpretationOf].flat().filter(w=>w!==void 0).map(w=>e.tracks.find(x=>x.kind==="observer"&&(x.event.id===w||x.recording?.id===w))).filter(w=>w!==void 0).filter(w=>w!==f?.track).map(w=>({at:e.tracks.indexOf(w),title:this.labelOf(w,e.tracks.indexOf(w))}));S.length>0&&(v.links={heading:f?i.alsoAbout:i.interpretationOf,to:S})}return v});new Be(s,p=>this.openEvent(p),p=>this.openEvent(p),void 0,p=>{this.folded.delete(p)||this.folded.add(p),this.refreshOverview()}).render(u,i,(p,{card:m,body:f,links:g})=>this.dress(e,t.find(({index:b})=>b===p.at).item,p.at,m,f,g))}dress(e,t,i,s,n,r){const o=this.messages,l=r.textContent!=="",a=t.track?.kind==="reading"?this.findingsOf(t.track):void 0,d=Ln.of(a);if(d){s.dataset.verdict=d;const p=document.createElement("span");p.className="verdict",p.textContent=o.readingVerdict[d],r.prepend(p,...l?[document.createTextNode(" · ")]:[])}const h=t.track!==void 0&&oe.sealed(t.track.event);if(h){const p=r.textContent!=="";s.dataset.sealed="";const m=document.createElement("span");m.className="sealed-chip",m.textContent=o.sealedChip,r.prepend(m,...p?[document.createTextNode(" · ")]:[])}const c=document.createElement("span");if(c.className="event-tools",t.track){const p=document.createElement("button");p.type="button",p.className="icon-btn event-tool event-copy",p.innerHTML=D.COPY,p.title=o.cloneEvent,p.setAttribute("aria-label",o.cloneEvent),p.addEventListener("click",()=>void this.cloneFromList(i));const m=document.createElement("button");m.type="button",m.className="icon-btn event-tool event-freeze",m.innerHTML=h?D.LOCK:D.LOCK_OPEN,m.title=h?o.unfreezeEvent:o.freezeEvent,m.setAttribute("aria-label",m.title),m.setAttribute("aria-pressed",String(h)),m.addEventListener("click",()=>void this.toggleFrozen(i)),c.append(p,m)}const u=document.createElement("button");if(u.type="button",u.className="icon-btn event-delete",u.innerHTML=D.TRASH,u.title=h?o.deleteFrozen:o.deleteRecording,u.setAttribute("aria-label",u.title),u.disabled=h,u.addEventListener("click",()=>void this.deleteFromList(i)),c.append(u),a&&a.length>0&&n.append(this.findingsList(a)),t.track?.kind==="reading"&&t.track.recording){const p=Dn.create();p.show(e.accountOf(t.track)?.recording,t.track.recording),n.append(p)}s.append(c)}findingsOf(e){const t=this.session?.accountOf(e),i=[e,t].filter(r=>r!==void 0&&!r.recording);if(i.length>0){for(const r of i)this.fetchingFindings.has(r)||(this.fetchingFindings.add(r),this.loadTrack(r).then(()=>this.refreshOverview(),()=>{}));if(!e.recording)return}const s=e.recording.interpretation?.findings??[],n=t?.recording&&this.readingCheck?this.readingCheck.findingsOf(t.recording,e.recording):[];return[...s,...n]}fetchingFindings=new WeakSet;readingCheck;bestCases;laid=new WeakSet;layMostFavourable(e){if(e.kind!=="reading"||!e.recording||this.laid.has(e)||!this.bestCases)return;const t=this.session?.accountOf(e)?.recording;if(!t)return;this.laid.add(e);const i=this.bestCases.bestSceneOf(t,e.recording);i&&(e.recording=i,e.loaded=JSON.stringify(i))}findingsList(e){const t=this.messages,i=document.createElement("ul");i.className="findings";for(const s of e){const n=document.createElement("li");n.dataset.outcome=s.outcome;const r=document.createElement("span");r.className="finding-mark",r.textContent={holds:"✓",fails:"✗",untested:"?"}[s.outcome],r.title=t.findingOutcome[s.outcome],r.setAttribute("aria-label",t.findingOutcome[s.outcome]);const o=document.createElement("span");if(o.textContent=this.said.read(s.text)??"",n.append(r,o),s.outcome==="fails"){const l=document.createElement("span");l.className="finding-against",l.textContent=` (${t.findingAgainst[s.against??"established"]})`,n.append(l)}i.append(n)}return i}openEvent(e){const t=this.byId("track");t.value=String(e),t.dispatchEvent(new Event("change")),requestAnimationFrame(()=>this.bringEditorIntoView())}bringEditorIntoView(){const e=this.editor;if(!e.checkVisibility?.())return;const t=e.getBoundingClientRect();Math.abs(t.top)>1&&e.scrollIntoView?.({block:"start",behavior:"smooth"})}async cloneFromList(e){const t=this.session,s=(t?this.items(t)[e]:void 0)?.track;if(!t||!s)return;try{await this.loadTrack(s)}catch{this.showError(this.messages.loadFailed);return}const n=t.clone(s);if(!n)return;this.refreshRow();const r=this.items(t).findIndex(o=>o.track===n);r>=0&&this.openEvent(r)}async toggleFrozen(e){const t=this.session,s=(t?this.items(t)[e]:void 0)?.track;!t||!s||(!oe.sealed(s.event)&&this.current===s&&this.commit(),t.seal(s,!oe.sealed(s.event)),this.refreshRow())}refreshEventAuthor(){const e=this.currentInterview?void 0:this.current,t=this.currentInterview??(e?.kind==="reading"?e.event:void 0),i=this.byId("row-event-author");if(i.hidden=t===void 0,!t)return;this.byId("label-event-author").textContent=this.currentInterview?this.messages.interviewerField:this.messages.authorField;const s=this.input("event-author");this.shadow.activeElement!==s&&(s.value=this.authorsText(t.by)),s.disabled=e!==void 0&&oe.sealed(e.event)}writeEventAuthor(){const e=this.session,t=this.currentInterview?void 0:this.current,i=this.currentInterview??(t?.kind==="reading"?t.event:void 0);if(!e||!i||t&&oe.sealed(t.event))return;const s=this.authorsFrom(this.input("event-author").value,i.by);s?i.by=s:delete i.by;const n=t?.recording?.interpretation;n&&(s?n.by=s:delete n.by),e.touch(),this.refreshOverview(),this.refreshDirty()}showFrozen(e){this.byId("frozen-note").hidden=!e,this.byId("frozen-text").textContent=e?this.messages.frozenNote:"",this.editor.toggleAttribute("inert",e)}async deleteFromList(e){const t=this.session,i=t?this.items(t)[e]:void 0;i&&(this.byId("track").value=String(e),i.interview?await this.showInterview(i.interview):await this.showTrack(i.track),this.askDelete())}stepEvent(e){const t=this.session;if(!t)return;const i=this.eventsInTime(t),s=i.findIndex(({item:r})=>r.interview?r.interview===this.currentInterview:r.track===this.current),n=i[s+e];n&&this.openEvent(n.index)}refreshCaseState(){this.byId("save-case").disabled=!(this.session?.dirty??!1);const e=this.byId("share-case");e.disabled=this.sourceUrl===void 0,e.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"";const t=this.byId("read-case");t.hidden=!this.hasAttribute(mt)&&this.readAddress()===void 0,this.session&&t.parentElement!==e.parentElement?e.before(t):!this.session&&t.parentElement!==this.editor&&(t.slot="head-actions",this.editor.append(t))}switcher;readAddress(){return this.session?this.sourceUrl:this.editor.address}read(){const e=this.readAddress();if(this.hasAttribute(mt)){const i=this.holdForReading();if(qs.ask(this,Zs,i))return;_e.releaseCopies()}if(e===void 0)return;const t=this.session?this.sharedTrack:void 0;window.open(`${gi.home()}/play/?file=${encodeURIComponent(e)}${t?`&events=${encodeURIComponent(Le.fileKey(t))}`:""}`,"_blank","noopener")}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}holdForReading(){const e=new Map,t=this.session;if(t){this.commit();const n=this.sourceUrl===void 0;e.set(t.url,{json:t.json,changed:t.dirty,local:n});for(const r of t.tracks)r.recording&&e.set(r.url,{json:r.recording,changed:t.changed(r),local:n});return _e.releaseCopies(),_e.hold(e),{src:t.url,...this.sharedTrack?{track:this.sharedTrack}:{}}}const i=this.editor.address,s=i??new URL("recording.json",location.href).href;return e.set(s,{json:this.editor.sightingData,changed:this.editor.dirty,local:i===void 0}),_e.releaseCopies(),_e.hold(e),{src:s}}askBeforeReplacing(e){this.guarded(()=>{this.leaving=!0,e()})}async openTrack(e){const t=this.session;if(!t)return;const i=new URL(e,location.href).href,s=t.tracks.find(n=>n.url===i);!s||s===this.current&&!this.listShown&&!this.currentInterview||(this.listShown=!1,await this.showTrack(s))}sourceUrl;shareDialog;shareMessages;get sharedTrack(){return this.currentInterview?void 0:this.current?.url}shareSubject={module:"rr0-sighting-editor",link:()=>{const e=this.sharedTrack;return`${gi.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}${e?`&track=${encodeURIComponent(e)}`:""}`},element:()=>{const e=this.sharedTrack;return`<rr0-case-editor src="${this.sourceUrl??""}"${e?` track="${e}"`:""}></rr0-case-editor>`}};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.session?.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}compareReadings(e){en.register();const t=this.byId("readings-comparison");t.toggleAttribute("data-filtered",!this.kindsShown.has("reading"));const i=()=>e.tracks.flatMap((s,n)=>{if(s.kind!=="reading")return[];const r=e.accountOf(s);return[{title:this.labelOf(s,n),witness:r?this.labelOf(r,e.tracks.indexOf(r)):"",...s.recording?{reading:s.recording}:{},...r?.recording?{account:r.recording}:{},open:()=>this.openFromTable(e,s)}]});t.show(i(),async()=>{const s=e.tracks.filter(n=>n.kind==="reading").flatMap(n=>[n,e.accountOf(n)]).filter(n=>n!==void 0&&!n.recording);return await Promise.all([...new Set(s)].map(n=>this.loadTrack(n).catch(()=>{}))),i()})}openFromTable(e,t){const i=this.items(e).findIndex(n=>n.track===t);if(i<0)return;const s=this.byId("track");s.value=String(i),s.dispatchEvent(new Event("change"))}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const s=this.session.tracks.filter(n=>n.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(s||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time,i=typeof t=="object"?t.value:t,s=i?Le.rr0TimeOf(i):void 0,n=this.said.read(e.observer?.title),r=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=oe.around(e,s,n,r,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:Un(Le.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const s=this.input("case-time");s.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&ot.opensPrecise(i)),this.dateModeFor=e)}refreshRow(){const e=this.session;if(this.applySections(),this.byId("case-panel").hidden=e===void 0,this.refreshOverview(),this.byId("make-case-row").hidden=e!==void 0,this.byId("case").classList.toggle("in-case",e!==void 0),this.byId("event-item").classList.toggle("in-case",e!==void 0),this.holdEditor(e!==void 0),!e){this.refreshDirty();return}const t=this.shadow.activeElement;for(const[o,l]of[["case-id","id"],["case-title","title"]]){const a=this.input(o);a!==t&&(a.value=String(e.json[l]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),s=this.items(e);i.replaceChildren(...s.map((o,l)=>new Option(this.optionLabel(o,l),String(l))));const n=this.currentInterview?s.findIndex(o=>o.interview===this.currentInterview):this.current?s.findIndex(o=>o.track===this.current):0;i.value=String(Math.max(0,n));const r=this.currentInterview===void 0&&this.current!==void 0&&oe.sealed(this.current.event);this.byId("delete").disabled=r||this.currentInterview===void 0&&e.tracks.length<=1,this.showFrozen(r),this.refreshEventAuthor(),this.refreshRecordingId(e),this.refreshDirty()}holdEditor(e){this.editor.embedded=e,e&&this.byId("history-slot").append(this.editor.historyControls),this.shadow.querySelector(".event-id-row").hidden=!e}refreshRecordingId(e){const t=this.current,i=t!==void 0&&t.kind==="observer";if(this.byId("row-recording-id").hidden=!i,i){const l=this.input("recording-id");this.shadow.activeElement!==l&&(l.value=t.event.id??""),l.placeholder=e.proposedId(t),l.disabled=oe.sealed(t.event),l.title=l.disabled?this.messages.frozenNote:""}const{duplicateIds:s,unresolved:n}=e.problems(),r=[...s.map(l=>this.messages.idDuplicated.replace("{id}",l)),...n.map(({reference:l})=>this.messages.readingUnresolved.replace("{id}",l))],o=this.byId("case-problems");o.hidden=r.length===0,o.textContent=r.join(" ")}showRecordingIdError(e){const t=this.byId("recording-id-error");t.textContent=e??"",t.hidden=e===void 0}writeRecordingId(){const e=this.session,t=this.current;if(!e||!t)return;const i=e.setId(t,this.input("recording-id").value.trim());this.showRecordingIdError(i==="ok"?void 0:{empty:this.messages.idNeeded,invalid:this.messages.idInvalid,taken:this.messages.idTaken}[i]),this.scheduleDirtyCheck()}get dialog(){return this.byId("dialog")}openDialog(e,t,i,s,n){this.dialogMode=e,this.byId("dialog-title").textContent=t;const r=this.byId("dialog-message");if(r.textContent=i??"",r.hidden=i===void 0,this.showError(void 0),this.byId("fields-add").hidden=e!=="add",this.byId("fields-export").hidden=e!=="export",this.byId("ok").hidden=!1,this.byId("ok").textContent=s??(e==="discard"?this.messages.discardOk:this.messages.ok),this.dialog.classList.toggle("anchored",n!==void 0),n){const o=n.getBoundingClientRect();this.dialog.style.top=`${Math.round(o.bottom+6)}px`,this.dialog.style.right=`${Math.max(8,Math.round(window.innerWidth-o.right))}px`,this.dialog.style.left="auto",typeof this.dialog.show=="function"?this.dialog.show():this.dialog.setAttribute("open",""),this.beside??=l=>{const a=l.composedPath();(l instanceof KeyboardEvent?l.key==="Escape":!a.includes(this.dialog)&&!a.includes(this.anchor))&&this.closeDialog()},this.anchor=n,document.addEventListener("pointerdown",this.beside,!0),document.addEventListener("keydown",this.beside,!0);return}this.dialog.style.removeProperty("top"),this.dialog.style.removeProperty("right"),this.dialog.style.removeProperty("left"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open","")}beside;anchor;closeDialog(){this.beside&&(document.removeEventListener("pointerdown",this.beside,!0),document.removeEventListener("keydown",this.beside,!0)),this.pendingLoad=void 0,typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}showError(e){const t=this.byId("dialog-error");t.textContent=e??"",t.hidden=e===void 0}input(e){return this.byId(e)}inputFile(e){return this.byId(e)}today(){return new Date().toISOString().slice(0,10)}askAdd(){const e=this.session;if(!e)return;this.openDialog("add",this.messages.addTitle,void 0,void 0,this.byId("add"));const t=this.byId("of");t.replaceChildren(...e.tracks.filter(n=>n.kind==="observer").map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n)))));const i=this.byId("kind");i.value="observation",i.options[1].disabled=t.options.length===0;const s=e.tracks.filter(n=>n.kind==="observer");this.byId("witness").replaceChildren(...s.map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n))))),this.byId("medium").replaceChildren(),this.byId("source").value="blank";for(const n of["observer","title","author"])this.input(n).value="";this.inputFile("add-source").clear(),this.input("date").value="",this.syncSourceFields()}async fillMedia(){const{InterviewMedia:e}=await M(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value,t=e==="interview",i=this.byId("source").value,s=e==="reading";this.byId("row-source").hidden=t,this.byId("row-of").hidden=!s,this.byId("row-witness").hidden=!t,this.byId("row-medium").hidden=!t,t&&this.fillMedia(),this.byId("row-file").hidden=t||i!=="file",this.byId("row-observer").hidden=t||s,this.byId("row-title").hidden=!(t||s),this.byId("row-author").hidden=!(t||s),this.byId("label-title").textContent=t?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=t?this.messages.interviewerField:this.messages.investigatorField;const n=this.input("date");n.disabled=s,s&&(n.value=this.today())}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const c=e.tracks[Number(this.byId("witness").value)],u=this.input("title").value.trim(),p=this.input("author").value.trim(),m=e.addInterview(c,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?p.split(",").map(f=>({people:f.trim()})).filter(f=>f.people!==""):void 0,this.byId("medium").value);return await this.showInterview(m),!0}const t=this.byId("of").value,i=this.byId("kind").value==="reading"&&t!==""?e.tracks[Number(t)]:void 0,s=this.byId("source").value;if(i&&s==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const c=this.input("title").value.trim(),u=this.input("author").value.trim(),p=e.addReading(i,this.input("date").value||this.today(),c!==""?c:void 0,u!==""?[{title:u}]:void 0);return this.showTrack(p),!0}const n=this.input("observer").value.trim(),r=this.input("date").value.trim();let o;try{if(s==="blank"){const c=(n||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";o={version:4,id:`${r?`${r}-`:""}${c}`,...n?{observer:{title:n}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const c=await this.readFile();if(se.isCase(c))return this.showError(this.messages.isACase),!1;o=c,n&&!o.observer?.title&&(o={...o,observer:{...o.observer,title:n}})}}catch{return this.showError(this.messages.loadFailed),!1}const l=(i?this.input("title").value:n).trim(),a=l!==""?l:this.said.read(o.observer?.title),d=this.input("author").value.trim(),h=e.addObservation(o,r!==""?r:void 0,a,i?{account:i,by:d!==""?[{title:d}]:void 0}:void 0);return this.showTrack(h),!0}async readFile(){const e=this.inputFile("add-source").value;if(!e)throw new Error("No file");if(e.url)return Je.recording(new URL(e.url,location.href).href);const t=e.file,i=await new Promise((s,n)=>{const r=new FileReader;r.onload=()=>s(r.result),r.onerror=()=>n(r.error),r.readAsText(t)});return JSON.parse(i)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(o=>o.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const s=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,s&&this.showTrack(s))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const o of t.tracks)await this.loadTrack(o)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:s,strToU8:n}=await M(async()=>{const{zipSync:o,strToU8:l}=await import("./browser-CltifEM0.js");return{zipSync:o,strToU8:l}},[],import.meta.url),r={};for(const o of i)r[o.path]=n(o.content);return this.download(new Blob([s(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}}function ho(){zs(),customElements.get(bi)||customElements.define(bi,Le)}const So=Object.freeze(Object.defineProperty({__proto__:null,CASE_EDITOR_ELEMENT_NAME:bi,CaseEditorElement:Le,register:ho},Symbol.toStringTag,{value:"Module"}));export{So as C,De as I,gs as M};
|