@rr0/ufoathome 0.202.0 → 0.202.1

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.
Files changed (98) hide show
  1. package/dist-embed-scene/{AirshipEditor-BnRmKeVs.js → AirshipEditor-guE_ib3z.js} +1 -1
  2. package/dist-embed-scene/{AirshipFlight-C9DSPGwk.js → AirshipFlight-DzW0313e.js} +1 -1
  3. package/dist-embed-scene/{BalloonEditor-BehJs6H-.js → BalloonEditor-BIsCy_y4.js} +2 -2
  4. package/dist-embed-scene/{BalloonFlight-BYn4diw1.js → BalloonFlight-gunghgAq.js} +1 -1
  5. package/dist-embed-scene/{BirdEditor-dOp1sGsz.js → BirdEditor-CuLv4Ij5.js} +1 -1
  6. package/dist-embed-scene/{BirdFlock-CfJeXvWu.js → BirdFlock-L3dYU2K_.js} +1 -1
  7. package/dist-embed-scene/{DroneEditor-CBoR4fJ_.js → DroneEditor-BQWPhTyf.js} +1 -1
  8. package/dist-embed-scene/{DroneFlight-DSE1OXqh.js → DroneFlight-ERYah68l.js} +1 -1
  9. package/dist-embed-scene/{DroneParameters-D3EOg4oe.js → DroneParameters-CoWQympS.js} +1 -1
  10. package/dist-embed-scene/{LanternEditor-CbcA7K8y.js → LanternEditor-BpCyb79i.js} +1 -1
  11. package/dist-embed-scene/{ModuleSession-XnOI5Mcr.js → ModuleSession-bj7QHWjO.js} +2 -2
  12. package/dist-embed-scene/ModuleThree-DRsA8rtL.js +1 -0
  13. package/dist-embed-scene/SearchlightSystem-Ddws2hQY.js +1 -0
  14. package/dist-embed-scene/{SkyLantern-Dp_B40X0.js → SkyLantern-C3BSxHtq.js} +1 -1
  15. package/dist-embed-scene/rr0-scene.mjs +85 -64
  16. package/dist-embed-sighting/{CaseReportExport-CkWf0HNx.js → CaseReportExport-BtGCWD7H.js} +1 -1
  17. package/dist-embed-sighting/{ModuleSession-ChJsGuTn.js → ModuleSession-DztK084a.js} +2 -2
  18. package/dist-embed-sighting/{ModuleThree-whEZoXYF.js → ModuleThree-BLNSm2eY.js} +1 -1
  19. package/dist-embed-sighting/SearchlightSystem-PEMBDW1s.js +1 -0
  20. package/dist-embed-sighting/rr0-sighting.mjs +90 -69
  21. package/dist-embed-sighting-editor/{BallesterGuaspAssessor-Bylahnc2.js → BallesterGuaspAssessor-CJyRqwvh.js} +1 -1
  22. package/dist-embed-sighting-editor/{CaseElement-DPlro-7S.js → CaseElement-D80gHg4r.js} +1 -1
  23. package/dist-embed-sighting-editor/{CaseReportExport-C1g5C8hi.js → CaseReportExport-Bv6FWPs2.js} +1 -1
  24. package/dist-embed-sighting-editor/{ControlPasses-BMEmppip.js → ControlPasses-CaVHMhEY.js} +1 -1
  25. package/dist-embed-sighting-editor/{CoverageAssessor-uzQnTEH8.js → CoverageAssessor-CTfHqAd_.js} +1 -1
  26. package/dist-embed-sighting-editor/{GLTFLoader-2Zbfb3kh.js → GLTFLoader-CrRPu-Pt.js} +1 -1
  27. package/dist-embed-sighting-editor/{HeadlightSystem-CBmEcC9f.js → HeadlightSystem-BmPfcHt1.js} +1 -1
  28. package/dist-embed-sighting-editor/{HynekAssessor-uub2VxTi.js → HynekAssessor-nBidt6QV.js} +1 -1
  29. package/dist-embed-sighting-editor/{InterviewEditorElement-_1fa2bG7.js → InterviewEditorElement-CQWfYlGL.js} +2 -2
  30. package/dist-embed-sighting-editor/{ModuleConformance-Cr6fM28A.js → ModuleConformance-CpMYkYgb.js} +2 -2
  31. package/dist-embed-sighting-editor/{ModuleSession-WA6lqfV6.js → ModuleSession-b_pmjUfP.js} +2 -2
  32. package/dist-embed-sighting-editor/ModuleThree-B_FZVqsf.js +1 -0
  33. package/dist-embed-sighting-editor/{ModulesPanelElement-BsRg3mzl.js → ModulesPanelElement-D0gn9Z-y.js} +3 -3
  34. package/dist-embed-sighting-editor/{NearestApproach-Bnx9Ld5_.js → NearestApproach-Bxo_N7a9.js} +1 -1
  35. package/dist-embed-sighting-editor/{PoherAssessor-CNj_Nyci.js → PoherAssessor-CEVA26zd.js} +1 -1
  36. package/dist-embed-sighting-editor/{RailwaySystem-6bwbv8UB.js → RailwaySystem-Ceb0_MVz.js} +1 -1
  37. package/dist-embed-sighting-editor/{ReferenceSystem-8QgwbbAG.js → ReferenceSystem-B15kw0uH.js} +1 -1
  38. package/dist-embed-sighting-editor/SearchlightSystem-D7sdsRYn.js +1 -0
  39. package/dist-embed-sighting-editor/{SightingElement-BQdiez39.js → SightingElement-Bp-t_EAF.js} +1 -1
  40. package/dist-embed-sighting-editor/{TraceSystem-DZMUxSn-.js → TraceSystem-Bv4kLpie.js} +2 -2
  41. package/dist-embed-sighting-editor/{WaterSystem-CB5jE7qB.js → WaterSystem-Bbk_RJKg.js} +1 -1
  42. package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +193 -172
  43. package/dist-embed-ufoathome/{AdsbLolArchiveProvider-KbJPyJ97.js → AdsbLolArchiveProvider-v1sSwhN1.js} +1 -1
  44. package/dist-embed-ufoathome/{Aurora-C_mCH4JM.js → Aurora-Dc4u2vEw.js} +1 -1
  45. package/dist-embed-ufoathome/{AuroraEditor-Dzvgh6e0.js → AuroraEditor-CeLzRDPj.js} +1 -1
  46. package/dist-embed-ufoathome/{AuroraSimulation-BRUnHmlp.js → AuroraSimulation-BT1CdWX5.js} +1 -1
  47. package/dist-embed-ufoathome/{BallesterGuaspAssessor-DurdUgbG.js → BallesterGuaspAssessor-CPW-Omah.js} +1 -1
  48. package/dist-embed-ufoathome/{BeamEditor-Ccvx7l7x.js → BeamEditor-BS73mBZU.js} +1 -1
  49. package/dist-embed-ufoathome/{BeamSystem-CPM8m17q.js → BeamSystem-C5EpRhij.js} +1 -1
  50. package/dist-embed-ufoathome/{BodyEditor-BG--NjnZ.js → BodyEditor-BV8WwzAj.js} +1 -1
  51. package/dist-embed-ufoathome/{CaseEditorElement-0J_TCeiq.js → CaseEditorElement-HR8RFluQ.js} +6 -6
  52. package/dist-embed-ufoathome/{CaseElement-CRXPyMMR.js → CaseElement-vCbCfGOv.js} +3 -3
  53. package/dist-embed-ufoathome/{CaseReportExport-DKrBXPgZ.js → CaseReportExport-XLbFCkPg.js} +3 -3
  54. package/dist-embed-ufoathome/{ColumnResize-DV-byvDt.js → ColumnResize-CEXrq3KB.js} +3 -3
  55. package/dist-embed-ufoathome/{ControlPasses-CKvTCqTI.js → ControlPasses-CKOU_3lG.js} +1 -1
  56. package/dist-embed-ufoathome/{CoverageAssessor-MeOMUjkZ.js → CoverageAssessor-BYMf3Qhv.js} +1 -1
  57. package/dist-embed-ufoathome/{Flightradar24Provider-DxTfswSh.js → Flightradar24Provider-_QPbhh5s.js} +1 -1
  58. package/dist-embed-ufoathome/{GLTFLoader-pi-JKaNa.js → GLTFLoader-DQeHB-Bk.js} +1 -1
  59. package/dist-embed-ufoathome/{GeoJsonExport-iyhoKOUU.js → GeoJsonExport-Pq_pPvjK.js} +1 -1
  60. package/dist-embed-ufoathome/{GeographicFigures-DBmuFlvH.js → GeographicFigures-KII55iXE.js} +1 -1
  61. package/dist-embed-ufoathome/{HynekAssessor-Bda6csgM.js → HynekAssessor-wCDhgIB8.js} +1 -1
  62. package/dist-embed-ufoathome/{InterviewEditorElement-BA060rqJ.js → InterviewEditorElement-BSwkegEp.js} +4 -4
  63. package/dist-embed-ufoathome/{InterviewElement-DvqsCA3I.js → InterviewElement-CfkDtybc.js} +1 -1
  64. package/dist-embed-ufoathome/{KmlExport-DEPgRRWe.js → KmlExport-BMNwwys8.js} +1 -1
  65. package/dist-embed-ufoathome/{LaserBeam--dquPX_h.js → LaserBeam-B-tlAzNB.js} +1 -1
  66. package/dist-embed-ufoathome/{LaunchEditor-D3P0GkLr.js → LaunchEditor-Cy5D-gwU.js} +1 -1
  67. package/dist-embed-ufoathome/{LaunchPlume-w4l4TR4A.js → LaunchPlume-D-vSb8tJ.js} +1 -1
  68. package/dist-embed-ufoathome/{LaunchSimulation-BpZd-Nov.js → LaunchSimulation-CZ8Oba00.js} +1 -1
  69. package/dist-embed-ufoathome/{ModelSource-Csnm3RH_.js → ModelSource-HSiigkeO.js} +1 -1
  70. package/dist-embed-ufoathome/{ModelThumbnails-Cnt2GxTb.js → ModelThumbnails-DWvRMmj_.js} +1 -1
  71. package/dist-embed-ufoathome/{ModelViewer-DOfAkPgK.js → ModelViewer-CM7qTW8F.js} +1 -1
  72. package/dist-embed-ufoathome/{ModulesPanelElement-DH1oroWm.js → ModulesPanelElement-DsOa2zH0.js} +1 -1
  73. package/dist-embed-ufoathome/{NearestApproach-DJ98M81-.js → NearestApproach-PAsV5RlG.js} +1 -1
  74. package/dist-embed-ufoathome/{PoherAssessor-4zSdFnFp.js → PoherAssessor-CniYlhUl.js} +1 -1
  75. package/dist-embed-ufoathome/{QuestionnaireFeed-W69udpmT.js → QuestionnaireFeed-CpZqkxlt.js} +1 -1
  76. package/dist-embed-ufoathome/{QuestionnaireForm-U78nFPn5.js → QuestionnaireForm-LkllpNx-.js} +1 -1
  77. package/dist-embed-ufoathome/{QuestionnaireImport-Q5uHxQwU.js → QuestionnaireImport-CNROmkT2.js} +1 -1
  78. package/dist-embed-ufoathome/{ReentryEditor-DEi9nT0z.js → ReentryEditor-Qax1sT82.js} +1 -1
  79. package/dist-embed-ufoathome/{ReentrySimulation-CSO1vgro.js → ReentrySimulation-CTeCaxZl.js} +1 -1
  80. package/dist-embed-ufoathome/{ReferenceSystem--tiMGm4e.js → ReferenceSystem-CM27OCUo.js} +1 -1
  81. package/dist-embed-ufoathome/{ScenarioReadings-Dzdgopl3.js → ScenarioReadings-Is3HX0n0.js} +1 -1
  82. package/dist-embed-ufoathome/{ScenarioSweep-CMcleprC.js → ScenarioSweep-BbtX26Fi.js} +1 -1
  83. package/dist-embed-ufoathome/{SearchlightEditor--1uL8bTa.js → SearchlightEditor-PuLz84pp.js} +1 -1
  84. package/dist-embed-ufoathome/SearchlightSystem-B-tHvY1M.js +1 -0
  85. package/dist-embed-ufoathome/{ShareDialogElement-Dlfy9NCE.js → ShareDialogElement-EzLob2Tz.js} +92 -71
  86. package/dist-embed-ufoathome/{SightingElement-BJSNmFM6.js → SightingElement--qpGoyxL.js} +2 -2
  87. package/dist-embed-ufoathome/{TraceSystem-Cq2TgP-u.js → TraceSystem-8XQX03MS.js} +1 -1
  88. package/dist-embed-ufoathome/{VideoButton-MRJlVNm_.js → VideoButton-WNtEngz-.js} +1 -1
  89. package/dist-embed-ufoathome/rr0-ufoathome.mjs +2 -2
  90. package/dist-embed-ufoathome/{surroundingsSources--qffL_nJ.js → surroundingsSources-UHKGesPa.js} +1 -1
  91. package/dist-embed-ufoathome/{trafficRuntime-CTCGr90P.js → trafficRuntime-CgY_7-NH.js} +1 -1
  92. package/package.json +1 -1
  93. package/dist-embed-scene/ModuleThree-BTQgimAj.js +0 -1
  94. package/dist-embed-scene/SearchlightSystem-CX1_nBkz.js +0 -1
  95. package/dist-embed-sighting/SearchlightSystem-B2-MzG4x.js +0 -1
  96. package/dist-embed-sighting-editor/ModuleThree-CB_EjTOI.js +0 -1
  97. package/dist-embed-sighting-editor/SearchlightSystem-CEG52QDx.js +0 -1
  98. package/dist-embed-ufoathome/SearchlightSystem-7bntVtp_.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ScenarioSweep-CMcleprC.js","./rr0-ufoathome.mjs","./ShareDialogElement-Dlfy9NCE.js","./Sighting-B7bsiTIQ.js","./VisualAids-DI-hEL46.js","./three.module-CbaHqYFq.js","./SaidPosition-OJEYhVKN.js","./GeoProjection-DvqDbRIx.js","./Decor-Dn-cvniW.js","./RecordingIssue-BlWT8Xsu.js","./xyzImageryRaster-Dhxs0B26.js","./Obstacles-v9SkfBD7.js","./SatellitePasses-Pfro2-0Z.js","./ParameterForm-XbqxCLRn.js","./ColumnResize-DV-byvDt.js","./InterviewAttachments-BP6Prvdu.js","./TimelineTracks-Daaqw9ly.js","./ReentryArchive-CeXHrU7L.js","./ReferenceTimeline-2kBldQeG.js","./upperAirSources-BU0pD84c.js","./Account-C4jhsVtN.js","./ScenarioReadings-Dzdgopl3.js","./index-DqGmxMZD.js","./ModelThumbnails-Cnt2GxTb.js","./ModelSource-Csnm3RH_.js","./ModelViewer-DOfAkPgK.js","./SightingFileEditor-DS1DRU2p.js","./index-C8cdeM8E.js","./sightingSchema-9MogCcUd.js","./surroundingsSources--qffL_nJ.js","./ModuleSession-BKDWGSEo.js","./ModulesPanelElement-DH1oroWm.js","./PictureRegistration-BJeiCK8A.js","./TraceImport-CntRHXoJ.js","./GeoExportTexts-3a51cuxQ.js","./KmlExport-DEPgRRWe.js","./GeographicFigures-DBmuFlvH.js","./GeoJsonExport-iyhoKOUU.js","./BodyEditor-BG--NjnZ.js","./GhostSearchView-Dlhj3xWa.js","./PictureFetch-C3wgf1ZV.js","./interviewJson-D-i14LTf.js","./InterviewEditorElement-BA060rqJ.js","./InterviewMedia-CGVsMdje.js","./InterviewElement-DvqsCA3I.js","./QuestionnaireFeed-W69udpmT.js","./QuestionnaireImport-Q5uHxQwU.js"])))=>i.map(i=>d[i]);
2
- import{s as Ft,U as mt,H as Oe,e as Li,_ as T,C as ne,F as Ge,M as Ke,f as Vs,P as gi,g as ce,h as We,i as z,j as te,k as $,S as gt,r as qs,I as Ai,a as et,O as $e,m as zt,n as Zs,o as Ys,p as Rt,q as Pt,t as Ls,c as Js,d as Xs,u as vt,v as Qs,w as en,x as tn,y as sn,R as nn,z as rn}from"./rr0-ufoathome.mjs";import{P as at,I as A}from"./SaidPosition-OJEYhVKN.js";import{E as be,P as lt,a as _t,r as xi,B as it,N as Ut,A as fi,b as As,W as _e,c as Di}from"./ParameterForm-XbqxCLRn.js";import{C as je,a as Fe,c as on,Q as an,d as ln,I as dn,b as hn,R as cn}from"./ColumnResize-DV-byvDt.js";import{H as ye,k as Te,E as dt,l as Ci,W as Q,s as ve,m as G,n as un,o as pn,p as Oi,q as Jt,t as Xt,u as Ri,v as pe,w as q,x as bi,y as Pi,D as Ds,a as Cs,z as Qt,F as mn,Z as gn,N as me,G as Qe,I as Bi,J as Ni,K as fn,L as Le,Q as Os,U as Bt,V as Fi,X as _,Y as ht,_ as ct,$ as zi,a0 as _i,a1 as Ui,a2 as bn,a3 as vn,a4 as $i,a5 as he,a6 as vi,a7 as Rs,a8 as Ps,a9 as wn,aa as ei,b as yn,ab as En,ac as kn,ad as xn,ae as Sn,af as In,ag as Pe,ah as wt,A as wi,ai as yt,aj as Tn,ak as Mn,al as Ln,am as Hi,an as ti,ao as Wi,ap as ji,aq as de,P as ii,ar as si,as as Ze,i as An,at as Dn,au as Et,av as Cn,aw as Gi,ax as Ki,ay as Vi,az as qi,aA as nt,g as Zi,e as Yi,aB as On,aC as Ji,aD as Xi,aE as ni,aF as ri,aG as Qi,aH as es,aI as Rn,aJ as Ye,aK as ts,aL as kt,aM as oi,f as is,aN as ai,aO as ee,aP as Pn,aQ as ss,r as Bn,S as Bs,c as Nn,d as ns,B as Fn,h as zn,R as _n}from"./ShareDialogElement-Dlfy9NCE.js";import{K as Un,r as Nt,a as yi,b as oe,c as ie,A as fe,m as Ns,d as $n,e as Hn,D as Ee,s as $t,I as ke,S as Wn,f as jn,g as Gn,h as Kn,i as rs,j as Vn,k as qn,p as Zn}from"./Sighting-B7bsiTIQ.js";import{I as Ei}from"./InterviewAttachments-BP6Prvdu.js";import{T as Si}from"./TimelineTracks-Daaqw9ly.js";import{H as Yn,o as Jn,D as Fs,h as Xn,d as zs,a as Qn,b as os,r as as,c as ls}from"./Decor-Dn-cvniW.js";import{R as er}from"./ReentryArchive-CeXHrU7L.js";import{g as _s,l as tr}from"./GeoProjection-DvqDbRIx.js";import{R as Be}from"./ReferenceTimeline-2kBldQeG.js";import{U as ir}from"./upperAirSources-BU0pD84c.js";import{S as sr}from"./Account-C4jhsVtN.js";class ds{constructor(e,t,i){this.m=e,this.placeName=t,this.language=i}robustness(e){switch(e.robustness){case"robust-plausible":return this.m.robustPlausible;case"robust-exclusion":return this.m.robustExclusion;case"conditional":return this.m.conditional.replace("{where}",this.where(e.onlyIf))}}evolution(e){const t=e.asWritten==="plausible"?this.m.asWrittenPlausible:this.m.asWrittenExcluded;if(e.independent)return`${t}, ${this.m.independent}`;const i=e.asWritten==="plausible"?{"robust-plausible":this.m.becomesRobust,"robust-exclusion":this.m.excludedEverywhere,conditional:this.m.becomesConditional}[e.robustness]:{"robust-plausible":this.m.plausibleEverywhere,"robust-exclusion":this.m.becomesRobustExclusion,conditional:this.m.plausibleOnlyIf}[e.robustness];return`${t}, ${i}`}sentence(e){const t=e.independent?"":` (${this.m.holdsIn.replace("{holds}",String(e.holds)).replace("{played}",String(e.played))})`;return`${this.robustness(e)}${this.m.colon}${this.evolution(e)}${t}`}where(e){return e?.places?e.places.map(t=>t==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t))).join(this.m.or):e?.dates?e.dates.map(t=>this.m.onDates.replace("{dates}",this.date(t))).join(this.m.or):(e?.scenarios??[]).map(t=>this.m.inScenarios.replace("{scenarios}",this.scenarioId(t))).join(this.m.or)}static grouped(e){const t=new Map;for(const s of e){const n=`${s.candidate}|${s.robustness}|${JSON.stringify(s.onlyIf??{})}`,r=t.get(n)??{...s,accounts:[]};s.eventId&&r.accounts.push(s.eventId),t.set(n,r)}const i={"robust-plausible":0,conditional:1,"robust-exclusion":2};return[...t.values()].sort((s,n)=>i[s.robustness]-i[n.robustness])}alert(e){return(e.robustness==="robust-exclusion"?this.m.alertExcluded:e.robustness==="robust-plausible"?this.m.alertPlausible:this.m.alertConditional).replace("{name}",e.label).replace("{where}",this.where(e.onlyIf))}scenario(e){return`${this.placeName(e.placeId)}, ${this.instant(e.local)}`}scenarioId(e){const[t,i]=e.split("@");return`${this.placeName(t)}, ${this.instant(i)}`}title(e,t){const i=t.placeId==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t.placeId));return this.m.scenarioTitle.replace("{title}",e).replace("{place}",i).replace("{date}",this.instant(t.local))}date(e){return new Date(`${e}T12:00Z`).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"})}instant(e){return new Date(`${e.slice(0,16)}Z`).toLocaleString(this.language,{day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC"})}}class tt extends HTMLElement{static TAG="rr0-scenario-sweep";static CSS=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ScenarioSweep-BbtX26Fi.js","./rr0-ufoathome.mjs","./ShareDialogElement-EzLob2Tz.js","./Sighting-B7bsiTIQ.js","./VisualAids-DI-hEL46.js","./three.module-CbaHqYFq.js","./SaidPosition-OJEYhVKN.js","./GeoProjection-DvqDbRIx.js","./Decor-Dn-cvniW.js","./RecordingIssue-BlWT8Xsu.js","./xyzImageryRaster-Dhxs0B26.js","./Obstacles-v9SkfBD7.js","./SatellitePasses-Pfro2-0Z.js","./ParameterForm-XbqxCLRn.js","./ColumnResize-CEXrq3KB.js","./InterviewAttachments-BP6Prvdu.js","./TimelineTracks-Daaqw9ly.js","./ReentryArchive-CeXHrU7L.js","./ReferenceTimeline-2kBldQeG.js","./upperAirSources-BU0pD84c.js","./Account-C4jhsVtN.js","./ScenarioReadings-Is3HX0n0.js","./index-DqGmxMZD.js","./ModelThumbnails-DWvRMmj_.js","./ModelSource-HSiigkeO.js","./ModelViewer-CM7qTW8F.js","./SightingFileEditor-DS1DRU2p.js","./index-C8cdeM8E.js","./sightingSchema-9MogCcUd.js","./surroundingsSources-UHKGesPa.js","./ModuleSession-BKDWGSEo.js","./ModulesPanelElement-DsOa2zH0.js","./PictureRegistration-BJeiCK8A.js","./TraceImport-CntRHXoJ.js","./GeoExportTexts-3a51cuxQ.js","./KmlExport-BMNwwys8.js","./GeographicFigures-KII55iXE.js","./GeoJsonExport-Pq_pPvjK.js","./BodyEditor-BV8WwzAj.js","./GhostSearchView-Dlhj3xWa.js","./PictureFetch-C3wgf1ZV.js","./interviewJson-D-i14LTf.js","./InterviewEditorElement-BSwkegEp.js","./InterviewMedia-CGVsMdje.js","./InterviewElement-CfkDtybc.js","./QuestionnaireFeed-CpZqkxlt.js","./QuestionnaireImport-CNROmkT2.js"])))=>i.map(i=>d[i]);
2
+ import{s as Ft,U as mt,H as Oe,e as Li,_ as T,C as ne,F as Ge,M as Ke,f as Vs,P as gi,g as ce,h as We,i as z,j as te,k as $,S as gt,r as qs,I as Ai,a as et,O as $e,m as zt,n as Zs,o as Ys,p as Rt,q as Pt,t as Ls,c as Js,d as Xs,u as vt,v as Qs,w as en,x as tn,y as sn,R as nn,z as rn}from"./rr0-ufoathome.mjs";import{P as at,I as A}from"./SaidPosition-OJEYhVKN.js";import{E as be,P as lt,a as _t,r as xi,B as it,N as Ut,A as fi,b as As,W as _e,c as Di}from"./ParameterForm-XbqxCLRn.js";import{C as je,a as Fe,c as on,Q as an,d as ln,I as dn,b as hn,R as cn}from"./ColumnResize-CEXrq3KB.js";import{H as ye,k as Te,E as dt,l as Ci,W as Q,s as ve,m as G,n as un,o as pn,p as Oi,q as Jt,t as Xt,u as Ri,v as pe,w as q,x as bi,y as Pi,D as Ds,a as Cs,z as Qt,F as mn,Z as gn,N as me,G as Qe,I as Bi,J as Ni,K as fn,L as Le,Q as Os,U as Bt,V as Fi,X as _,Y as ht,_ as ct,$ as zi,a0 as _i,a1 as Ui,a2 as bn,a3 as vn,a4 as $i,a5 as he,a6 as vi,a7 as Rs,a8 as Ps,a9 as wn,aa as ei,b as yn,ab as En,ac as kn,ad as xn,ae as Sn,af as In,ag as Pe,ah as wt,A as wi,ai as yt,aj as Tn,ak as Mn,al as Ln,am as Hi,an as ti,ao as Wi,ap as ji,aq as de,P as ii,ar as si,as as Ze,i as An,at as Dn,au as Et,av as Cn,aw as Gi,ax as Ki,ay as Vi,az as qi,aA as nt,g as Zi,e as Yi,aB as On,aC as Ji,aD as Xi,aE as ni,aF as ri,aG as Qi,aH as es,aI as Rn,aJ as Ye,aK as ts,aL as kt,aM as oi,f as is,aN as ai,aO as ee,aP as Pn,aQ as ss,r as Bn,S as Bs,c as Nn,d as ns,B as Fn,h as zn,R as _n}from"./ShareDialogElement-EzLob2Tz.js";import{K as Un,r as Nt,a as yi,b as oe,c as ie,A as fe,m as Ns,d as $n,e as Hn,D as Ee,s as $t,I as ke,S as Wn,f as jn,g as Gn,h as Kn,i as rs,j as Vn,k as qn,p as Zn}from"./Sighting-B7bsiTIQ.js";import{I as Ei}from"./InterviewAttachments-BP6Prvdu.js";import{T as Si}from"./TimelineTracks-Daaqw9ly.js";import{H as Yn,o as Jn,D as Fs,h as Xn,d as zs,a as Qn,b as os,r as as,c as ls}from"./Decor-Dn-cvniW.js";import{R as er}from"./ReentryArchive-CeXHrU7L.js";import{g as _s,l as tr}from"./GeoProjection-DvqDbRIx.js";import{R as Be}from"./ReferenceTimeline-2kBldQeG.js";import{U as ir}from"./upperAirSources-BU0pD84c.js";import{S as sr}from"./Account-C4jhsVtN.js";class ds{constructor(e,t,i){this.m=e,this.placeName=t,this.language=i}robustness(e){switch(e.robustness){case"robust-plausible":return this.m.robustPlausible;case"robust-exclusion":return this.m.robustExclusion;case"conditional":return this.m.conditional.replace("{where}",this.where(e.onlyIf))}}evolution(e){const t=e.asWritten==="plausible"?this.m.asWrittenPlausible:this.m.asWrittenExcluded;if(e.independent)return`${t}, ${this.m.independent}`;const i=e.asWritten==="plausible"?{"robust-plausible":this.m.becomesRobust,"robust-exclusion":this.m.excludedEverywhere,conditional:this.m.becomesConditional}[e.robustness]:{"robust-plausible":this.m.plausibleEverywhere,"robust-exclusion":this.m.becomesRobustExclusion,conditional:this.m.plausibleOnlyIf}[e.robustness];return`${t}, ${i}`}sentence(e){const t=e.independent?"":` (${this.m.holdsIn.replace("{holds}",String(e.holds)).replace("{played}",String(e.played))})`;return`${this.robustness(e)}${this.m.colon}${this.evolution(e)}${t}`}where(e){return e?.places?e.places.map(t=>t==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t))).join(this.m.or):e?.dates?e.dates.map(t=>this.m.onDates.replace("{dates}",this.date(t))).join(this.m.or):(e?.scenarios??[]).map(t=>this.m.inScenarios.replace("{scenarios}",this.scenarioId(t))).join(this.m.or)}static grouped(e){const t=new Map;for(const s of e){const n=`${s.candidate}|${s.robustness}|${JSON.stringify(s.onlyIf??{})}`,r=t.get(n)??{...s,accounts:[]};s.eventId&&r.accounts.push(s.eventId),t.set(n,r)}const i={"robust-plausible":0,conditional:1,"robust-exclusion":2};return[...t.values()].sort((s,n)=>i[s.robustness]-i[n.robustness])}alert(e){return(e.robustness==="robust-exclusion"?this.m.alertExcluded:e.robustness==="robust-plausible"?this.m.alertPlausible:this.m.alertConditional).replace("{name}",e.label).replace("{where}",this.where(e.onlyIf))}scenario(e){return`${this.placeName(e.placeId)}, ${this.instant(e.local)}`}scenarioId(e){const[t,i]=e.split("@");return`${this.placeName(t)}, ${this.instant(i)}`}title(e,t){const i=t.placeId==="own"?this.m.atOwnPlace:this.m.atPlaces.replace("{places}",this.placeName(t.placeId));return this.m.scenarioTitle.replace("{title}",e).replace("{place}",i).replace("{date}",this.instant(t.local))}date(e){return new Date(`${e}T12:00Z`).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"})}instant(e){return new Date(`${e.slice(0,16)}Z`).toLocaleString(this.language,{day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC"})}}class tt extends HTMLElement{static TAG="rr0-scenario-sweep";static CSS=`
3
3
  :host { display: block; font-size: 13px; line-height: 1.4; margin-top: 14px; }
4
4
  :host([hidden]) { display: none; }
5
5
  summary { cursor: pointer; list-style-position: inside; font: 600 12px/1.4 var(--rr0-sans, system-ui, sans-serif); letter-spacing: .08em; text-transform: uppercase; opacity: .8; }
@@ -22,7 +22,7 @@ tr[data-plausible="false"] td { opacity: .7; }
22
22
  ul.alerts { margin: 4px 0; padding-left: 18px; }
23
23
  .note { opacity: .75; }
24
24
  ${ye.CSS}
25
- `;messages;language="en";host;result;state="idle";progress={done:0,total:0};error;note;opened=!1;ticked=new Set;wind;static register(){customElements.get(tt.TAG)||customElements.define(tt.TAG,tt)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}show(e){this.host=e,this.draw()}async loadLocale(){const e=Ft(Oe.preferencesFor(this),mt);this.messages=await Li.load(e),this.language=e,this.draw()}words(e,t=this.language){const i=new Map((this.host?.caseJson().conditions?.places?.candidates??[]).map(s=>[s.id,s.place.name??s.id]));return new ds(e,s=>s==="own"?e.ownPlace:i.get(s)??s,t)}async run(){const e=this.host;if(!(!e||this.state==="running")){this.state="running",this.progress={done:0,total:0},this.draw();try{const[{ScenarioSweep:t},{OpenMeteoWindProfiles:i},{TleArchive:s},{visibleMagnitudeLimit:n},{InterpretationKinds:r},{INTERPRETATION_SOURCES:o}]=await Promise.all([T(()=>import("./ScenarioSweep-CMcleprC.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(p=>p.Z),[],import.meta.url),T(()=>import("./ShareDialogElement-Dlfy9NCE.js").then(p=>p.bB),__vite__mapDeps([2,1,3,4,5,6,7,8,9,10,11]),import.meta.url),T(()=>import("./ShareDialogElement-Dlfy9NCE.js").then(p=>p.bA),__vite__mapDeps([2,1,3,4,5,6,7,8,9,10,11]),import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(p=>p.Y),[],import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(p=>p.$),[],import.meta.url)]),a=new Map,d=new i({cache:{get:async p=>a.get(p),set:async(p,m)=>{a.set(p,m)}}});this.wind=d;const l=new s,h=this.messages,c=new t({wind:d,load:p=>e.load(p),limitAt:p=>n(p),kinds:o.map(p=>r.of(p)),satellites:async p=>(await l.at(p))?.objects,names:p=>h.bodies[p]});let u=0;this.result=await c.sweep(e.caseJson(),{progress:(p,m)=>{this.progress={done:p,total:m},(p===m||performance.now()-u>250)&&(u=performance.now(),this.draw())}}),this.ticked.clear();for(const p of this.result.accounts)for(const m of p.readings)for(const f of m.kept)this.ticked.add(this.key(m,f));this.state="done",this.note=void 0}catch(t){this.state="failed",this.error=t.message}this.draw()}}key(e,t){return`${e.url}|${t.id}`}async keepTicked(){const e=this.host,t=this.result;if(!e||!t)return;const[{ScenarioReadings:i},{InterpretationKinds:s},{INTERPRETATION_SOURCES:n}]=await Promise.all([T(()=>import("./ScenarioReadings-Dzdgopl3.js"),__vite__mapDeps([21,1,0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(h=>h.Y),[],import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(h=>h.$),[],import.meta.url)]),r=n.map(h=>s.of(h)),o=await Promise.all(mt.map(async h=>({language:h,m:await Li.load(h)}))),a=e.caseJson(),d=[];for(const h of t.accounts)for(const c of h.readings){const u=a.events?.find(m=>m.url===c.url),p=await e.load(c.url);for(const m of c.outcomes){if(!this.ticked.has(this.key(c,m.scenario)))continue;const f=m.scenario,g=c.depends.includes("wind")&&this.wind?await this.wind.profile(f.lat,f.lng,f.date):void 0,b=u?.title??p.interpretation?.title,v=Object.fromEntries(o.map(({language:k,m:I})=>{const C=typeof b=="string"?b:b?.[k]??b?.en??c.url;return[k,this.words(I,k).title(C,f)]})),y=a.conditions?.places?.candidates?.find(k=>k.id===f.placeId),S=i.recording(p,c.url,f,g,r,{title:v,verdict:c.verdict.robustness,...y?.rationale?{placeRationale:y.rationale}:{},...a.conditions?.time?.rationale?{timeRationale:a.conditions.time.rationale}:{}});d.push({recording:S,title:v,readingUrl:c.url})}}const l=e.keep(d);this.note=this.messages.kept.replace("{n}",String(l)),this.draw()}draw(){const e=this.messages,t=this.host?.caseJson().conditions;if(this.hidden=!t,!e||!t){this.shadowRoot.replaceChildren();return}const i=document.createElement("style");i.textContent=tt.CSS;const s=document.createElement("details");s.open=this.opened,s.addEventListener("toggle",()=>{this.opened=s.open});const n=document.createElement("summary");n.append(e.heading,ye.of(e.hint));const r=this.words(e),o=t.places?.candidates?.length??0,a=t.time?`${r.instant(t.time.from)} – ${r.instant(t.time.to)}`:"–",d=Object.assign(document.createElement("p"),{textContent:e.open.replace("{places}",String(o)).replace("{dates}",a)}),l=document.createElement("div");l.className="actions";const h=Object.assign(document.createElement("button"),{type:"button",className:"pill",textContent:e.run,disabled:this.state==="running"});h.addEventListener("click",()=>void this.run()),l.append(h),this.state==="running"&&l.append(Object.assign(document.createElement("span"),{textContent:e.running.replace("{done}",String(this.progress.done)).replace("{total}",String(this.progress.total||"…"))})),this.state==="failed"&&l.append(Object.assign(document.createElement("span"),{className:"note",textContent:e.failed.replace("{error}",this.error??"")})),s.append(n,d,l),this.result&&this.state!=="running"&&s.append(...this.results(this.result,e,r)),this.shadowRoot.replaceChildren(i,s)}results(e,t,i){const s=[],n=this.host.caseJson(),r=u=>typeof u=="string"?u:typeof u=="object"&&u!==null?String(u[this.language]??Object.values(u)[0]??""):"",o=u=>r(n.events?.find(p=>p.url===u)?.title)||u,a=u=>u.compared===0?"–":t.summary.replace("{agreed}",String(u.agreedDirection)).replace("{compared}",String(u.compared)).replace("{median}",u.medianDeg===void 0?"–":`${u.medianDeg.toFixed(1)}°`);for(const u of e.accounts)if(u.readings.length!==0){s.push(Object.assign(document.createElement("h4"),{textContent:`${t.account}${t.colon}${r(u.title)||u.eventId||u.url}`}));for(const p of u.readings){const m=document.createElement("div");m.className="reading",m.dataset.robustness=p.verdict.robustness,m.append(Object.assign(document.createElement("div"),{textContent:o(p.url)}),Object.assign(document.createElement("div"),{className:"verdict",textContent:i.sentence(p.verdict)})),p.depends.includes("wind")&&m.append(Object.assign(document.createElement("div"),{className:"note",textContent:t.dependsWind})),p.verdict.independent||m.append(this.scenarioTable(p,t,i,a)),s.push(m)}}const d=document.createElement("ul");d.className="alerts";const l=ds.grouped(e.alerts);for(const u of l)d.append(Object.assign(document.createElement("li"),{textContent:`${i.alert(u)}${t.colon}${u.accounts.join(", ")}`}));s.push(Object.assign(document.createElement("h4"),{textContent:t.alertsHeading}),l.length>0?d:Object.assign(document.createElement("p"),{textContent:t.noAlert}));const h=document.createElement("div");h.className="actions";const c=Object.assign(document.createElement("button"),{type:"button",className:"pill",textContent:t.keep,disabled:this.ticked.size===0});return c.addEventListener("click",()=>void this.keepTicked()),h.append(c),this.note&&h.append(Object.assign(document.createElement("span"),{className:"note",textContent:this.note})),s.push(h),s}scenarioTable(e,t,i,s){const n=document.createElement("table"),r=n.createTHead().insertRow();for(const l of["",t.scenario,t.said,t.drawn,t.wind])r.append(Object.assign(document.createElement("th"),{scope:"col",textContent:l}));const o=n.createTBody();o.insertRow().append(document.createElement("td"),Object.assign(document.createElement("td"),{textContent:t.asWritten}),Object.assign(document.createElement("td"),{className:"number",textContent:s(e.asWritten.said)}),Object.assign(document.createElement("td"),{className:"number",textContent:s(e.asWritten.drawn)}),document.createElement("td"));for(const l of e.outcomes){const h=o.insertRow();h.dataset.plausible=String(l.plausible);const c=Object.assign(document.createElement("input"),{type:"checkbox",checked:this.ticked.has(this.key(e,l.scenario)),disabled:!!l.error});c.setAttribute("aria-label",i.scenario(l.scenario)),c.addEventListener("change",()=>{const m=this.key(e,l.scenario);c.checked?this.ticked.add(m):this.ticked.delete(m),this.draw()});const u=document.createElement("td");u.append(c);const p=l.groundWind?t.windValue.replace("{toward}",String(Math.round(l.groundWind.towardDeg))).replace("{speed}",l.groundWind.speedMS.toFixed(1)):"";h.append(u,Object.assign(document.createElement("td"),{textContent:`${l.plausible?"✓":"✗"} ${i.scenario(l.scenario)}`}),Object.assign(document.createElement("td"),{className:"number",textContent:l.error??s(l.said)}),Object.assign(document.createElement("td"),{className:"number",textContent:l.error?"":s(l.drawn)}),Object.assign(document.createElement("td"),{className:"number",textContent:p}))}const d=document.createElement("div");return d.className="scroll",d.append(n),d}}class J{static DEFAULT="geipan-qt-2025";static IMAGES={"geipan-qt-2025":{"azimuth.png":new URL(""+new URL("azimuth-CvjiPmz0.png",import.meta.url).href,import.meta.url).href,"elevation.png":new URL(""+new URL("elevation-DPr5S6Jt.png",import.meta.url).href,import.meta.url).href,"angular-size.png":new URL(""+new URL("angular-size-CxoysZle.png",import.meta.url).href,import.meta.url).href,"protractor.png":new URL(""+new URL("protractor-DyE30B87.png",import.meta.url).href,import.meta.url).href}};static LOADERS={"geipan-qt-2025":()=>T(()=>import("./geipan-qt-2025-B_RUiH8B.js"),[],import.meta.url).then(e=>J.withImages(structuredClone(e.default),t=>J.IMAGES["geipan-qt-2025"][t]??t))};static withImages(e,t){const i=s=>s?.forEach(n=>{n.src=t(n.src)});for(const s of e.sections){i(s.images);for(const n of s.fields)i(n.images)}return e}static added=new Map;static ids(){return[...new Set([...Object.keys(J.LOADERS),...J.added.keys()])]}static add(e){J.added.set(e.id,e)}static fetched=new Map;static async load(e){const t=J.added.get(e)??await J.LOADERS[e]?.();if(t||!/[/:]|\.json$/i.test(e))return t;let i=J.fetched.get(e);return i||(i=fetch(e).then(s=>s.ok?s.json():void 0).then(s=>{if(!(!s||typeof s.id!="string"||!Array.isArray(s.sections)))return J.add(J.withImages(s,n=>new URL(n,e).href)),s}).catch(()=>{}),J.fetched.set(e,i)),i}static fields(e){return e.sections.flatMap(t=>t.fields)}static field(e,t){return J.fields(e).find(i=>i.id===t)}static text(e,t){if(e===void 0)return"";if(typeof e=="string")return e;const i=e;return(t&&i[t])??Object.values(i)[0]??""}static interview(e,t={},i){const s=t.witnesses?.length===1?t.witnesses[0]:void 0;return{version:1,...e.language?{language:e.language}:{},title:e.title,medium:"questionnaire",questionnaire:{id:e.id,...e.version?{version:e.version}:{},...i?{recipient:i}:{}},...s?{interviewOf:s.id}:{},speakers:{interviewer:{role:"interviewer",...t.by?.[0]!==void 0?{by:{people:t.by[0]}}:{}},witness:{role:"witness",...s?{title:s.label,of:s.id}:{}}},transcription:{method:"manual"},proofreading:{interviewer:{status:"pending"},witness:{status:"pending"}},segments:J.fields(e).map(n=>({speaker:"interviewer",field:n.id,text:J.text(n.question,e.language)}))}}static answerOf(e,t){return J.answerTurn(e,t)?.text}static filesOf(e,t){return J.answerTurn(e,t)?.files??[]}static answerTurn(e,t){return e.segments.find(i=>i.field===t&&e.speakers[i.speaker]?.role==="witness")}static fileName(e){return Ei.fileName(e)}static answerFiles(e,t,i,s){J.answer(e,t,i.map(n=>J.fileName(n)).join("; "),s,void 0,i)}static answer(e,t,i,s,n,r){const o=Object.entries(e.speakers).find(([,c])=>c.role==="witness")?.[0]??"witness";e.speakers[o]||(e.speakers[o]={role:"witness"});const a=e.segments.findIndex(c=>c.field===t&&e.speakers[c.speaker]?.role==="witness"),d=i.trim(),l=c=>{const{text:u,redacted:p,files:m,...f}=c;return n?{...f,redacted:n}:{...f,text:d,...r?.length?{files:r}:{}}};if(a>=0){d===""?e.segments.splice(a,1):e.segments[a]=l(e.segments[a]);return}if(d==="")return;let h=e.segments.findIndex(c=>c.field===t&&e.speakers[c.speaker]?.role!=="witness");if(h<0){const c=Object.entries(e.speakers).find(([,u])=>u.role==="interviewer")?.[0]??"interviewer";e.speakers[c]||(e.speakers[c]={role:"interviewer"}),e.segments.push({speaker:c,field:t,text:s??t}),h=e.segments.length-1}e.segments.splice(h+1,0,l({speaker:o,field:t}))}}const hs=Object.freeze(Object.defineProperty({__proto__:null,QuestionnaireTemplates:J},Symbol.toStringTag,{value:"Module"}));class ae{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===ne.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:ne.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},a=new ae(o,new URL("case.json",n).href),d=a.tracks[0];return d.recording=e,d.base={url:s},d.event.id=a.proposedId(d),a.caseChanged=!0,a}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===ne.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 a=1;for(;r.has(`interview-${o}-${a}`);)a++;const d={type:"event",eventType:ne.INTERVIEW_EVENT,id:`interview-${o}-${a}`,...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??[],d],this.caseChanged=!0,d}addQuestionnaire(e,t,i,s){const n=this.addInterview(e,t,i.title,void 0,"questionnaire");n.url=`${n.id}.json`;const r=[n.interviewOf].flat().filter(a=>typeof a=="string"),o=J.interview(i,{witnesses:r.map(a=>({id:a,label:a}))},s);return delete o.speakers.witness.title,this.keepTranscript(n,`${JSON.stringify({...o,id:n.id,time:t},null,2)}
25
+ `;messages;language="en";host;result;state="idle";progress={done:0,total:0};error;note;opened=!1;ticked=new Set;wind;static register(){customElements.get(tt.TAG)||customElements.define(tt.TAG,tt)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}show(e){this.host=e,this.draw()}async loadLocale(){const e=Ft(Oe.preferencesFor(this),mt);this.messages=await Li.load(e),this.language=e,this.draw()}words(e,t=this.language){const i=new Map((this.host?.caseJson().conditions?.places?.candidates??[]).map(s=>[s.id,s.place.name??s.id]));return new ds(e,s=>s==="own"?e.ownPlace:i.get(s)??s,t)}async run(){const e=this.host;if(!(!e||this.state==="running")){this.state="running",this.progress={done:0,total:0},this.draw();try{const[{ScenarioSweep:t},{OpenMeteoWindProfiles:i},{TleArchive:s},{visibleMagnitudeLimit:n},{InterpretationKinds:r},{INTERPRETATION_SOURCES:o}]=await Promise.all([T(()=>import("./ScenarioSweep-BbtX26Fi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(p=>p.Z),[],import.meta.url),T(()=>import("./ShareDialogElement-EzLob2Tz.js").then(p=>p.bA),__vite__mapDeps([2,1,3,4,5,6,7,8,9,10,11]),import.meta.url),T(()=>import("./ShareDialogElement-EzLob2Tz.js").then(p=>p.bz),__vite__mapDeps([2,1,3,4,5,6,7,8,9,10,11]),import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(p=>p.Y),[],import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(p=>p.$),[],import.meta.url)]),a=new Map,d=new i({cache:{get:async p=>a.get(p),set:async(p,m)=>{a.set(p,m)}}});this.wind=d;const l=new s,h=this.messages,c=new t({wind:d,load:p=>e.load(p),limitAt:p=>n(p),kinds:o.map(p=>r.of(p)),satellites:async p=>(await l.at(p))?.objects,names:p=>h.bodies[p]});let u=0;this.result=await c.sweep(e.caseJson(),{progress:(p,m)=>{this.progress={done:p,total:m},(p===m||performance.now()-u>250)&&(u=performance.now(),this.draw())}}),this.ticked.clear();for(const p of this.result.accounts)for(const m of p.readings)for(const f of m.kept)this.ticked.add(this.key(m,f));this.state="done",this.note=void 0}catch(t){this.state="failed",this.error=t.message}this.draw()}}key(e,t){return`${e.url}|${t.id}`}async keepTicked(){const e=this.host,t=this.result;if(!e||!t)return;const[{ScenarioReadings:i},{InterpretationKinds:s},{INTERPRETATION_SOURCES:n}]=await Promise.all([T(()=>import("./ScenarioReadings-Is3HX0n0.js"),__vite__mapDeps([21,1,0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(h=>h.Y),[],import.meta.url),T(()=>import("./rr0-ufoathome.mjs").then(h=>h.$),[],import.meta.url)]),r=n.map(h=>s.of(h)),o=await Promise.all(mt.map(async h=>({language:h,m:await Li.load(h)}))),a=e.caseJson(),d=[];for(const h of t.accounts)for(const c of h.readings){const u=a.events?.find(m=>m.url===c.url),p=await e.load(c.url);for(const m of c.outcomes){if(!this.ticked.has(this.key(c,m.scenario)))continue;const f=m.scenario,g=c.depends.includes("wind")&&this.wind?await this.wind.profile(f.lat,f.lng,f.date):void 0,b=u?.title??p.interpretation?.title,v=Object.fromEntries(o.map(({language:k,m:I})=>{const C=typeof b=="string"?b:b?.[k]??b?.en??c.url;return[k,this.words(I,k).title(C,f)]})),y=a.conditions?.places?.candidates?.find(k=>k.id===f.placeId),S=i.recording(p,c.url,f,g,r,{title:v,verdict:c.verdict.robustness,...y?.rationale?{placeRationale:y.rationale}:{},...a.conditions?.time?.rationale?{timeRationale:a.conditions.time.rationale}:{}});d.push({recording:S,title:v,readingUrl:c.url})}}const l=e.keep(d);this.note=this.messages.kept.replace("{n}",String(l)),this.draw()}draw(){const e=this.messages,t=this.host?.caseJson().conditions;if(this.hidden=!t,!e||!t){this.shadowRoot.replaceChildren();return}const i=document.createElement("style");i.textContent=tt.CSS;const s=document.createElement("details");s.open=this.opened,s.addEventListener("toggle",()=>{this.opened=s.open});const n=document.createElement("summary");n.append(e.heading,ye.of(e.hint));const r=this.words(e),o=t.places?.candidates?.length??0,a=t.time?`${r.instant(t.time.from)} – ${r.instant(t.time.to)}`:"–",d=Object.assign(document.createElement("p"),{textContent:e.open.replace("{places}",String(o)).replace("{dates}",a)}),l=document.createElement("div");l.className="actions";const h=Object.assign(document.createElement("button"),{type:"button",className:"pill",textContent:e.run,disabled:this.state==="running"});h.addEventListener("click",()=>void this.run()),l.append(h),this.state==="running"&&l.append(Object.assign(document.createElement("span"),{textContent:e.running.replace("{done}",String(this.progress.done)).replace("{total}",String(this.progress.total||"…"))})),this.state==="failed"&&l.append(Object.assign(document.createElement("span"),{className:"note",textContent:e.failed.replace("{error}",this.error??"")})),s.append(n,d,l),this.result&&this.state!=="running"&&s.append(...this.results(this.result,e,r)),this.shadowRoot.replaceChildren(i,s)}results(e,t,i){const s=[],n=this.host.caseJson(),r=u=>typeof u=="string"?u:typeof u=="object"&&u!==null?String(u[this.language]??Object.values(u)[0]??""):"",o=u=>r(n.events?.find(p=>p.url===u)?.title)||u,a=u=>u.compared===0?"–":t.summary.replace("{agreed}",String(u.agreedDirection)).replace("{compared}",String(u.compared)).replace("{median}",u.medianDeg===void 0?"–":`${u.medianDeg.toFixed(1)}°`);for(const u of e.accounts)if(u.readings.length!==0){s.push(Object.assign(document.createElement("h4"),{textContent:`${t.account}${t.colon}${r(u.title)||u.eventId||u.url}`}));for(const p of u.readings){const m=document.createElement("div");m.className="reading",m.dataset.robustness=p.verdict.robustness,m.append(Object.assign(document.createElement("div"),{textContent:o(p.url)}),Object.assign(document.createElement("div"),{className:"verdict",textContent:i.sentence(p.verdict)})),p.depends.includes("wind")&&m.append(Object.assign(document.createElement("div"),{className:"note",textContent:t.dependsWind})),p.verdict.independent||m.append(this.scenarioTable(p,t,i,a)),s.push(m)}}const d=document.createElement("ul");d.className="alerts";const l=ds.grouped(e.alerts);for(const u of l)d.append(Object.assign(document.createElement("li"),{textContent:`${i.alert(u)}${t.colon}${u.accounts.join(", ")}`}));s.push(Object.assign(document.createElement("h4"),{textContent:t.alertsHeading}),l.length>0?d:Object.assign(document.createElement("p"),{textContent:t.noAlert}));const h=document.createElement("div");h.className="actions";const c=Object.assign(document.createElement("button"),{type:"button",className:"pill",textContent:t.keep,disabled:this.ticked.size===0});return c.addEventListener("click",()=>void this.keepTicked()),h.append(c),this.note&&h.append(Object.assign(document.createElement("span"),{className:"note",textContent:this.note})),s.push(h),s}scenarioTable(e,t,i,s){const n=document.createElement("table"),r=n.createTHead().insertRow();for(const l of["",t.scenario,t.said,t.drawn,t.wind])r.append(Object.assign(document.createElement("th"),{scope:"col",textContent:l}));const o=n.createTBody();o.insertRow().append(document.createElement("td"),Object.assign(document.createElement("td"),{textContent:t.asWritten}),Object.assign(document.createElement("td"),{className:"number",textContent:s(e.asWritten.said)}),Object.assign(document.createElement("td"),{className:"number",textContent:s(e.asWritten.drawn)}),document.createElement("td"));for(const l of e.outcomes){const h=o.insertRow();h.dataset.plausible=String(l.plausible);const c=Object.assign(document.createElement("input"),{type:"checkbox",checked:this.ticked.has(this.key(e,l.scenario)),disabled:!!l.error});c.setAttribute("aria-label",i.scenario(l.scenario)),c.addEventListener("change",()=>{const m=this.key(e,l.scenario);c.checked?this.ticked.add(m):this.ticked.delete(m),this.draw()});const u=document.createElement("td");u.append(c);const p=l.groundWind?t.windValue.replace("{toward}",String(Math.round(l.groundWind.towardDeg))).replace("{speed}",l.groundWind.speedMS.toFixed(1)):"";h.append(u,Object.assign(document.createElement("td"),{textContent:`${l.plausible?"✓":"✗"} ${i.scenario(l.scenario)}`}),Object.assign(document.createElement("td"),{className:"number",textContent:l.error??s(l.said)}),Object.assign(document.createElement("td"),{className:"number",textContent:l.error?"":s(l.drawn)}),Object.assign(document.createElement("td"),{className:"number",textContent:p}))}const d=document.createElement("div");return d.className="scroll",d.append(n),d}}class J{static DEFAULT="geipan-qt-2025";static IMAGES={"geipan-qt-2025":{"azimuth.png":new URL(""+new URL("azimuth-CvjiPmz0.png",import.meta.url).href,import.meta.url).href,"elevation.png":new URL(""+new URL("elevation-DPr5S6Jt.png",import.meta.url).href,import.meta.url).href,"angular-size.png":new URL(""+new URL("angular-size-CxoysZle.png",import.meta.url).href,import.meta.url).href,"protractor.png":new URL(""+new URL("protractor-DyE30B87.png",import.meta.url).href,import.meta.url).href}};static LOADERS={"geipan-qt-2025":()=>T(()=>import("./geipan-qt-2025-B_RUiH8B.js"),[],import.meta.url).then(e=>J.withImages(structuredClone(e.default),t=>J.IMAGES["geipan-qt-2025"][t]??t))};static withImages(e,t){const i=s=>s?.forEach(n=>{n.src=t(n.src)});for(const s of e.sections){i(s.images);for(const n of s.fields)i(n.images)}return e}static added=new Map;static ids(){return[...new Set([...Object.keys(J.LOADERS),...J.added.keys()])]}static add(e){J.added.set(e.id,e)}static fetched=new Map;static async load(e){const t=J.added.get(e)??await J.LOADERS[e]?.();if(t||!/[/:]|\.json$/i.test(e))return t;let i=J.fetched.get(e);return i||(i=fetch(e).then(s=>s.ok?s.json():void 0).then(s=>{if(!(!s||typeof s.id!="string"||!Array.isArray(s.sections)))return J.add(J.withImages(s,n=>new URL(n,e).href)),s}).catch(()=>{}),J.fetched.set(e,i)),i}static fields(e){return e.sections.flatMap(t=>t.fields)}static field(e,t){return J.fields(e).find(i=>i.id===t)}static text(e,t){if(e===void 0)return"";if(typeof e=="string")return e;const i=e;return(t&&i[t])??Object.values(i)[0]??""}static interview(e,t={},i){const s=t.witnesses?.length===1?t.witnesses[0]:void 0;return{version:1,...e.language?{language:e.language}:{},title:e.title,medium:"questionnaire",questionnaire:{id:e.id,...e.version?{version:e.version}:{},...i?{recipient:i}:{}},...s?{interviewOf:s.id}:{},speakers:{interviewer:{role:"interviewer",...t.by?.[0]!==void 0?{by:{people:t.by[0]}}:{}},witness:{role:"witness",...s?{title:s.label,of:s.id}:{}}},transcription:{method:"manual"},proofreading:{interviewer:{status:"pending"},witness:{status:"pending"}},segments:J.fields(e).map(n=>({speaker:"interviewer",field:n.id,text:J.text(n.question,e.language)}))}}static answerOf(e,t){return J.answerTurn(e,t)?.text}static filesOf(e,t){return J.answerTurn(e,t)?.files??[]}static answerTurn(e,t){return e.segments.find(i=>i.field===t&&e.speakers[i.speaker]?.role==="witness")}static fileName(e){return Ei.fileName(e)}static answerFiles(e,t,i,s){J.answer(e,t,i.map(n=>J.fileName(n)).join("; "),s,void 0,i)}static answer(e,t,i,s,n,r){const o=Object.entries(e.speakers).find(([,c])=>c.role==="witness")?.[0]??"witness";e.speakers[o]||(e.speakers[o]={role:"witness"});const a=e.segments.findIndex(c=>c.field===t&&e.speakers[c.speaker]?.role==="witness"),d=i.trim(),l=c=>{const{text:u,redacted:p,files:m,...f}=c;return n?{...f,redacted:n}:{...f,text:d,...r?.length?{files:r}:{}}};if(a>=0){d===""?e.segments.splice(a,1):e.segments[a]=l(e.segments[a]);return}if(d==="")return;let h=e.segments.findIndex(c=>c.field===t&&e.speakers[c.speaker]?.role!=="witness");if(h<0){const c=Object.entries(e.speakers).find(([,u])=>u.role==="interviewer")?.[0]??"interviewer";e.speakers[c]||(e.speakers[c]={role:"interviewer"}),e.segments.push({speaker:c,field:t,text:s??t}),h=e.segments.length-1}e.segments.splice(h+1,0,l({speaker:o,field:t}))}}const hs=Object.freeze(Object.defineProperty({__proto__:null,QuestionnaireTemplates:J},Symbol.toStringTag,{value:"Module"}));class ae{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===ne.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:ne.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},a=new ae(o,new URL("case.json",n).href),d=a.tracks[0];return d.recording=e,d.base={url:s},d.event.id=a.proposedId(d),a.caseChanged=!0,a}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===ne.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 a=1;for(;r.has(`interview-${o}-${a}`);)a++;const d={type:"event",eventType:ne.INTERVIEW_EVENT,id:`interview-${o}-${a}`,...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??[],d],this.caseChanged=!0,d}addQuestionnaire(e,t,i,s){const n=this.addInterview(e,t,i.title,void 0,"questionnaire");n.url=`${n.id}.json`;const r=[n.interviewOf].flat().filter(a=>typeof a=="string"),o=J.interview(i,{witnesses:r.map(a=>({id:a,label:a}))},s);return delete o.speakers.witness.title,this.keepTranscript(n,`${JSON.stringify({...o,id:n.id,time:t},null,2)}
26
26
  `),n}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}static sealed(e){return e.sealed===!0}seal(e,t){t?e.event.sealed=!0:delete e.event.sealed,this.caseChanged=!0}clone(e,t){if(!e.recording)return;const i=e.kind==="reading"?this.accountOf(e):void 0;if(e.kind==="reading"&&!i)return;const s=t??e.event.title;return this.addObservation(structuredClone(e.recording),e.event.time,s,i?{account:i,by:e.event.by}:void 0)}keep(e,t,i=!1){!i&&ae.sealed(e.event)||(t=Ge.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===ne.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",a=this.tracks.find(d=>d.url===r);return a?(a.event=n,a.kind=o,a):{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(a=>a.eventType===ne.INTERVIEW_EVENT&&(n.id!==void 0&&a.id===n.id||n.url!==void 0&&a.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=o=>typeof o=="string"?o:o&&typeof o=="object"?Object.values(o).find(a=>typeof a=="string"):void 0,s=t(e.recording?.observer?.id)||t(i(e.event.title))||t(i(e.recording?.observer?.title))||t(e.recording?.observer?.lastName),n=this.eventIds(e);if(s!==""){let o=s;for(let a=2;n.has(o);a++)o=`${s}-${a}`;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===ne.SIGHTING_EVENT&&o.interpretationOf!==void 0&&[o.interpretationOf].flat().some(a=>a!==void 0&&s(a))),r=this.interviews.filter(o=>[o.interviewOf].flat().some(a=>a!==void 0&&s(a)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!ae.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 a=[o.interpretationOf].flat().map(d=>s(d)?t:d);o.interpretationOf=Array.isArray(o.interpretationOf)?a:a[0]}for(const o of r){const a=[o.interviewOf].flat().map(d=>d!==void 0&&s(d)?t:d);o.interviewOf=Array.isArray(o.interviewOf)?a:a[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return ne.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(M=>M.event.url)),a=new Set(this.tracks.map(M=>M.recording?.id));let d=this.tracks.filter(M=>M.kind==="reading").length+1;for(;o.has(`interpretation-${r}-${d}.json`)||a.has(`${n.id??r}-interpretation-${d}`);)d++;const l=`interpretation-${r}-${d}.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:y,interpretation:S,...k}=structuredClone(n),I={version:4,id:`${n.id??r}-interpretation-${d}`,...k,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+l};this.json.events=[...this.json.events??[],C],this.caseChanged=!0;const R={event:C,url:new URL(C.url,this.url).href,kind:"reading",recording:I};return this.tracks.push(R),R}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",a=s?"interpretation":"observer";let d=`${a}-${o}.json`,l=e.id??o;for(let m=2;n.has(d)||r.has(l);m++)d=`${a}-${o}-${m}.json`,l=`${e.id??o}-${m}`;const h={...e,id:l},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+d};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(ae.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"||ae.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=a=>a.startsWith(i)?a.slice(i.length):a,n=this.tracks.filter(a=>e&&a.recording!==void 0&&(t||this.changed(a))).map(a=>({path:s(a.url),content:JSON.stringify(a.recording,null,2)+`
27
27
  `})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",o=[...this.transcripts].filter(([a,d])=>e&&a.url!==void 0&&(t||this.transcriptChanged(d))).map(([a,d])=>({path:s(new URL(a.url,this.url).href),content:d.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
28
28
  `},...n,...o]}attachments(){const e=this.url.replace(/[^/]*$/,""),t=new Map;for(const[i,s]of this.transcripts){if(i.url===void 0)continue;let n;try{n=JSON.parse(s.text)}catch{continue}const r=new URL(i.url,this.url).href;for(const o of(n.segments??[]).flatMap(a=>a.files??[])){const a=Ei.url(o,r),d=Ei.blob(a);d&&a.startsWith(e)&&t.set(decodeURIComponent(a.slice(e.length)),d)}}return[...t].map(([i,s])=>({path:i,blob:s}))}}const Ht="rr0-date-input",nr=`
@@ -2774,8 +2774,8 @@ ${z.rules([],[".model-picker .model-picker-address p"])}
2774
2774
  .model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
2775
2775
  .model-picker .model-name { font-weight: 600; }
2776
2776
  .model-picker .model-credit { font-size: .8em; color: #666; }
2777
- `;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await T(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-Cnt2GxTb.js");return{ModelThumbnails:i}},__vite__mapDeps([23,5,24,2,1,3,4,6,7,8,9,10,11]),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 d=++n,l=e.selectedOptions[0],h=e.value===""?i?.current():void 0,c=JSON.stringify([e.value,l?.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:l?.textContent??""} …`,s.title=this.messages().choose,s.append(u);const p=e.value;(h?Promise.resolve({url:h.url}):t(p)).then(m=>pt.pictureOf(m)).then(m=>{if(!m||d!==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 a=i&&{current:()=>i.current(),apply:d=>{i.apply(d),o()}};s.addEventListener("click",()=>void this.open(e,t,a)),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=pt.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 a=document.createElement("h2");a.textContent=n.title;const d=document.createElement("button");d.type="button",d.className="model-picker-close",d.setAttribute("aria-label",n.close),d.title=n.close,d.innerHTML=A.CLOSE;const l=document.createElement("header");l.append(a,d);const h=document.createElement("div");h.className="model-picker-body",o.append(l,h),r.append(o);const c=()=>{r.remove(),document.removeEventListener("keydown",u,!0),T(async()=>{const{ModelViewer:I}=await import("./ModelViewer-DOfAkPgK.js");return{ModelViewer:I}},__vite__mapDeps([25,5,24,2,1,3,4,6,7,8,9,10,11]),import.meta.url).then(({ModelViewer:I})=>I.end())},u=I=>{I.key==="Escape"&&(I.stopPropagation(),c())},p=i?.current(),m="\0address",f=I=>I===m&&p?Promise.resolve({url:p.url}):t(I),g=I=>{if(c(),s){I!==m&&s(I);return}I===m||I===e.value||(e.value=I,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const v=new Map,y=I=>{const C=document.createElement("button");C.type="button",C.className="model-card",C.dataset.value=I.value,C.setAttribute("aria-pressed",String(!s&&(I.value===m||I.value===e.value&&!p)));const R=document.createElement("div");R.className="model-thumb";const M=document.createElement("span");if(M.className="model-name",M.textContent=I.textContent,C.append(R,M),I.title){const x=document.createElement("span");x.className="model-credit",x.textContent=I.title,C.append(x)}f(I.value).then(x=>pt.pictureOf(x)).then(x=>{if(!x)return;const L=new Image;L.src=x,L.alt="",R.append(L)});let Z,Y=!1;const Re=()=>{Y&&!(Z&&!Z.active)||(Y=!0,Promise.all([f(I.value),T(()=>import("./ModelViewer-DOfAkPgK.js"),__vite__mapDeps([25,5,24,2,1,3,4,6,7,8,9,10,11]),import.meta.url)]).then(([x,{ModelViewer:L}])=>{!x||!Y||(Z=L.show(R,x))}).catch(()=>{}))},Ve=()=>{Y=!1,Z?.stop(),Z=void 0};return v.set(C,Re),C.addEventListener("pointerenter",Re),C.addEventListener("focus",Re),C.addEventListener("pointerleave",()=>{document.activeElement!==C&&Ve()}),C.addEventListener("blur",Ve),C.addEventListener("click",x=>{if(Z?.consumeDrag()){x.preventDefault();return}g(I.value)}),C},S=()=>(b=document.createElement("div"),b.className="model-picker-grid",h.append(b),b);if(p){const I=new Option(p.title||p.url,m);I.title=[p.author,p.license].filter(Boolean).join(" — "),S().append(y(I))}for(const I of Array.from(e.children))if(I instanceof HTMLOptGroupElement){const C=document.createElement("h3");C.textContent=I.label,h.append(C);const R=S();for(const M of Array.from(I.children))R.append(y(M));b=void 0}else I instanceof HTMLOptionElement&&(b??S()).append(y(I));i&&this.addAddressForm(l,d,o,h,i,n,c),d.addEventListener("click",c),r.addEventListener("click",I=>{I.target===r&&c()}),document.addEventListener("keydown",u,!0),this.root.append(r);const k=o.querySelector('.model-card[aria-pressed="true"]');(k??d).focus(),k&&v.get(k)?.()}addAddressForm(e,t,i,s,n,r,o){const a=document.createElement("button");a.type="button",a.className="model-picker-add",a.textContent="+",a.title=r.address,a.setAttribute("aria-label",r.address),a.setAttribute("aria-expanded","false"),e.insertBefore(a,t);const d=document.createElement("form");d.className="model-picker-address",d.hidden=!0;const l=(v,y,S="")=>{const k=document.createElement("label"),I=document.createElement("span");I.textContent=v;const C=document.createElement("input");return C.type=y,C.placeholder=S,k.append(I,C),d.append(k),C},h=l(r.addressUrl,"url","https://…/model.glb"),c=l(r.addressName,"text"),u=l(r.addressAuthor,"text"),p=l(r.addressLicense,"text","CC0 1.0"),m=l(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,d.append(f,g),i.insertBefore(d,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);a.addEventListener("click",()=>{const v=d.hidden;if(d.hidden=!v,a.setAttribute("aria-expanded",String(v)),!v)return;const y=n.current();h.value=y?.url??"",c.value=y?.title??"",u.value=y?.author??"",p.value=y?.license??"",m.value=y?.source??"",b(),h.focus()}),d.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 Mi{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=Mi.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 Jr{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 le{static STEP_MS=100;static plan(e){const t=le.routeOf(e),i=Le.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const o=new Set,a=(c,u,p,m)=>{if(Math.abs(c.radiusM-m)>=m*.1)return!1;const{x:f,z:g}=_s(u,p,c.lat,c.lng);return Math.hypot(f,g)<Le.rebuildDistanceFor(m)};for(let c=0;;c=Math.min(s,c+le.STEP_MS)){const u=ie(e,c);if(u?.lat!==void 0&&u.lng!==void 0){const p=Le.groundRadiusFor(u.elevationM??0),m=Le.patchRadiusFor(p,u.elevationM??0),f=Math.max(m,i);(!r||!a(r,u.lat,u.lng,f))&&(r=n.find(g=>a(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 d=e.weatherTrack.allKeyframes.map(c=>c.weather.visibilityKm).filter(c=>c!==void 0),l=Le.farRingRadiusFor(d.length>0?Math.max(...d):void 0);for(const c of o)n.push({lat:c.lat,lng:c.lng,radiusM:l,far:!0});if(l>Le.FAR_RING_RADIUS_M)for(const c of[...n])!c.far&&!o.has(c)&&c.radiusM<l&&n.push({lat:c.lat,lng:c.lng,radiusM:l,far:!0});const h=Os.map(c=>Bt.of(c)).filter(c=>c.reachM&&Bt.eventsOf(e.skyEvents,c).length>0);if(h.length>0){const c=u=>Math.max(...h.map(p=>p.reachM(Bt.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)||Le.needsFarRing(u.radiusM,0,c(u))&&n.push({lat:u.lat,lng:u.lng,radiusM:l,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=a=>n?.(a,i.length);switch(e){case"relief":{const a=le.routeOf(t),d=[];for(const[c,u]of i.entries()){try{const p=await s.elevation.getElevationGrid(ct.boundsOf(u),{width:Ui,height:Ui},{route:a});d.push({...u,grid:p})}catch(p){console.warn("Relief not snapshots for a patch:",p)}o(c+1)}if(d.length===0)return;const l=s.elevationCredit;return{bytes:await bn.encode({takenOn:r,attribution:l,patches:d}),attribution:l,takenOn:r,answered:d.length,patches:i.length}}case"imagery":{const a=new Fi,d=_(ht,s.imagery),l=d.create(a.fetch);let h=0;for(const[p,m]of i.entries()){try{await l.getImageryTexture(ct.boundsOf(m),{width:zi,height:zi}),h++}catch(f){console.warn("Imagery not snapshots for a patch:",f)}o(p+1)}if(a.tiles.size===0)return;const c=l.attribution;return{bytes:await _i.encode({takenOn:r,source:d.id,attribution:c,patches:[...i],tiles:a.tiles}),attribution:c,takenOn:r,answered:h,patches:i.length}}case"roads":return le.vector(s.roads,i,r,o,(a,d)=>a.getRoads(d),a=>a.contemporary);case"water":return le.vector(s.water,i,r,o,(a,d)=>a.getWater(d));case"railways":return le.vector(s.railways,i,r,o,(a,d)=>a.getRailways(d),a=>a.contemporary)}}static mapGround(e){const t=vn.of(e);return t&&$i.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=le.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Fi,r=_(ht,t),o=r.create(n.fetch),a=$i.IMAGERY_PX;try{await o.getImageryTexture(i,{width:a,height:a})}catch(h){console.warn("Map imagery not snapshots:",h);return}const d=o.attribution;return{bytes:await _i.encode({takenOn:s,source:r.id,attribution:d,patches:[],map:{bounds:i,pixels:a},tiles:n.tiles}),attribution:d,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const o=[];for(const[l,h]of t.entries()){if(h.radiusM<=Le.ROADS_MAX_RADIUS_M)try{o.push({...h,items:await n(e,ct.boundsOf(h))})}catch(c){console.warn("Not snapshots for a patch:",c)}s(l+1)}if(o.length===0)return;const a={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:o};return{bytes:new TextEncoder().encode(JSON.stringify(a)),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 te.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 te.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 T(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-DS1DRU2p.js");return{SightingFileEditor:r}},__vite__mapDeps([26,27,28]),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{z.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){z.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}he.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}z.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await T(async()=>{const{InputFileElement:s}=await import("./rr0-ufoathome.mjs").then(n=>n.a0);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{z.show(this.note,this.messages.annexUnreadable,"warning");return}const o=n!==void 0&&j.isInline(n.src),a=o?j.dataUrl(e,t):n?.src??te.annexName(this.host.base(),e);o||he.hold(this.address(a),t),s[e]={...s[e]?.live?{live:!0}:{},src:a,...r},z.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${a}`),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=te.annexName(this.host.base(),e),he.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)?te.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 T(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 he.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,le.plan(this.host.sighting()),this.host.sources(),s))?z.show(this.note,void 0):z.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 te.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||le.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=>te.isLive(i,h),r=h=>i[h]?.src!==void 0?i[h]:void 0;for(const h of te.NAMES)!i.live&&i[h]?.live&&(i[h]={live:!0});const o=le.plan(t);let a;for(const h of te.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,a??=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");le.mapGround(t)!==void 0&&(!h||h.refresh||!await this.fitsMap(h))&&await this.takeMap(i,a??=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 d=this.host.upperAirHeard(),l=r("upperAir");if(!n("upperAir")&&d&&(!l||l.refresh)){const h=new Date().toISOString().slice(0,10),c={version:1,takenOn:h,attribution:d.answer.source.name,answers:[d]},u=new TextEncoder().encode(JSON.stringify(c)),p=this.place("upperAir",l?.src,e,u);i.upperAir={src:p,takenOn:h,attribution:d.answer.source.name},j.isInline(p)||s.set(p,u)}else l&&!n("upperAir")&&(l.refresh&&(i.upperAir={...l,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 le.freeze(e,this.host.sighting(),i,s,(a,d)=>z.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(a)).replaceAll("{of}",String(d))));return z.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){z.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await le.freezeMap(this.host.sighting(),t.imagery);return z.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=le.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await he.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&ct.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 he.zip(s))["index.json"])).patches:(await he.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(o=>o.radiusM<=Le.ROADS_MAX_RADIUS_M);return ct.samePatches(n.map(({lat:o,lng:a,radiusM:d})=>({lat:o,lng:a,radiusM:d})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&j.isInline(t))return j.dataUrl(e,s);const n=t??te.annexName(i,e);return he.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{z.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return he.bytes(this.address(e.src))}address(e){return he.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of te.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=te.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 Yt{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,z.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 gt(Oe.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=vi(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:Ge.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(a=>{if(!a.ok)throw new Error(String(a.status))})}catch{const a={...this.host.sighting().snapshots??{}};a[e]={...a[e]??{},src:t.url},z.show(this.note,void 0),this.write(e,a);return}let i;try{const{InputFileElement:a}=await T(async()=>{const{InputFileElement:l}=await import("./rr0-ufoathome.mjs").then(h=>h.a0);return{InputFileElement:l}},[],import.meta.url),d=await a.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=Ge.recording(JSON.parse(new TextDecoder().decode(d))),typeof i!="object"||i===null||$.KEYS[e].every(l=>i[l]===void 0))throw new Error("Not this section")}catch{z.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...vi(s)};if(e==="decor")$.put(e,n,"timeline"in i?$.taken(e,i):i);else for(const a of $.KEYS[e])n[a]=i[a];const r=Rs(n);Yt.copy(e,r,s);const o={...s.snapshots??{}};t.url?o[e]={...o[e]??{},src:t.url}:o[e]=o[e]??{},z.show(this.note,void 0),this.write(e,o)}write(e,t){this.host.sighting().snapshots=te.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 Xr{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 Qr=ce.point("timeZone").provide(ce.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new Xr}]);class ui{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 V{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=V.select("observerOccupationKind");graduate=V.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=V.select("observersRelation");activity=V.select("observerActivity");factors=new Map(sr.map(e=>[e,V.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){ye.register(),e.append(this.label(this.occupationKind,l=>[l.occupationKind,l.occupationKindHint]),this.label(this.graduate,l=>[l.graduate]));const n=this.label(this.enquiryMinutes,l=>[l.enquiryMinutes,l.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,l=>[l.relation]),this.label(this.activity,l=>[l.activity]));const o=Object.assign(document.createElement("h3"),{className:"section-title"});o.append(this.strangenessTitle),i.append(o,this.strangenessIntro,...[...this.factors].map(([l,h])=>this.label(h,c=>[c.factors[l],c.factorHints[l]])));const a=[["yes","yes"],["no","no"]],d=l=>l.map(h=>[h,h]);V.choices(this.occupationKind,"",d(Object.keys(ui.OCCUPATIONS))),V.choices(this.graduate,"",a),V.choices(this.relation,"",d(ui.RELATIONS)),V.choices(this.activity,"",d(ui.ACTIVITIES));for(const l of this.factors.values())V.choices(l,"",a);for(const l of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])l.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,V.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),V.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),V.choices(this.relation,e.unknown,Object.entries(e.relations)),V.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)V.choices(i,V.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=V.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=V.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=V.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:V.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);ye.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 Dt=new Set;Ps();Bn();Bs.register();const Je={width:48,height:28},eo=2500,Ct=40,Ot=10,to=30,io=10,Ss=600,Is=900,Xe=2e-4,so=900,no=-1.46,ro=3,pi=.2,oo=.5,ao=3,lo=.01,ho=1.6,mi=2e3,co=250,Ts=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),uo=1,po=5,mo=10,Ne=4,ot="ufo-1",go={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function fo(E){return E.kind==="oval"?"oval":"polygon"}const bo=-6,vo=21;class w extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=Qr[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new Jr;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;exportKmlButton;exportGeoJsonButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;saidInterviews;candidatesView;sectionFolds;sectionIndexResize;snapshotsPanel;sectionFilePanel;eventsPanel;aroundPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;aircraftStatus=Object.assign(document.createElement("span"),{className:"source-status"});aircraftFlights;aircraftFlightsShownAt=0;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=Yr();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 rt(qr());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 w.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?wn.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 a=this.numberBounds.get(r),d=Number(r.value);if(!a||r.value===""||!Number.isFinite(d))return;const l=Math.min(Math.max(d,a[0]),a[1]);l!==d&&(r.value=String(l))};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 ei;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=Ke.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...go};currentSourceId=ot;selectedSourceIds=new Set([ot]);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(Ts.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;Ts.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>${vr}</style>${br}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const l of this.shadow.querySelectorAll(Ht))l.build();for(const l of this.shadow.querySelectorAll(qt))l.build();for(const l of this.shadow.querySelectorAll(Ai))l.build();for(const l of this.shadow.querySelectorAll(Di))l.build();this.sceneElement=document.createElement(yn),this.sceneElement.addEventListener("observermapchange",l=>{this.ufoElement.sighting.observerMap=l.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",l=>{const{lat:h,lng:c}=l.detail;this.latInput.value=String(Number(h.toFixed(6))),this.lngInput.value=String(Number(c.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 ut(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const l of[this.timeStartLabel,this.timeEndLabel])l.addEventListener("click",()=>this.switchTimeDisplay()),l.addEventListener("keydown",h=>{h.key!=="Enter"&&h.key!==" "||(h.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(qt),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 O(this.shadow);const t=this.shadow.getElementById("section-index");this.sectionFolds.indexIn(t,()=>this.groupPanels?.find(l=>!l.hidden)),this.sectionIndexResize=new je(this.shadow.getElementById("section-index-resize"),this.shadow.querySelector(".app"),()=>t,"rr0-section-index-width","--rr0-section-index-width",44);const i=this;this.witnessErrorView=new Hs({get sighting(){return i.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:l=>{const h=this.ufoElement.sighting,{conditions:c,...u}=h.account??{},p={...u,...l?{conditions:l}:{}};h.account=Object.values(p).some(m=>m!==void 0)?p:void 0},recordingJson:()=>this.sightingData,valueSources:()=>this.valueSources(),lawsChanged:()=>{this.sceneElement.confrontationTolerance=En.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new Si(this.shadow.getElementById("timeline-tracks"),l=>this.goToMark(l),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",l=>{l.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new Ws(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",l=>{const h=l.target.id;w.SCENE_LINKED.includes(h)&&this.setActiveSceneField(h)}),this.shadow.addEventListener("focusout",l=>{const h=l.relatedTarget;(!h||!w.SCENE_LINKED.includes(h.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.filmStockSelect=this.shadow.getElementById("filmStock"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),this.skySourcesInput=this.shadow.getElementById("sky-sources"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.evaluationFields=new V(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(`${Di}[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(w.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:(l,h)=>this.download(l,h)}),this.sectionFilePanel=new Yt(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(l,h)=>this.download(l,h),changed:l=>{if(this.touch(),this.ufoElement.refresh(),l==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),l==="place"&&this.syncPlaceNameField(),l==="lightPollution"){const h=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=h===void 0?"":String(h),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const s={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:l=>this.goToMark(l),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const l=this.ufoElement.sighting.timeline;return l.sourceIds.includes(this.currentSourceId)?l.topOf(this.currentSourceId):void 0},shapesLabel:l=>this.shapesLabel(l),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:l=>this.naming.point(l),lookedAt:()=>{const l=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return l?.headingDeg===void 0||l.pitchDeg===void 0?void 0:{azimuthDeg:l.headingDeg,altitudeDeg:l.pitchDeg}},bodyLabel:l=>{const h=this.ufoElement.sighting.interpretation?.bodies.find(c=>c.id===l);return this.said.read(h?.title)??l},valueSources:()=>this.valueSources()};this.eventsPanel=new Ie(this.shadow.getElementById("events-section"),s,void 0),this.phenomenonEventsPanel=new Ie(this.shadow.getElementById("phenomenon-events-section"),s,void 0,"phenomenon"),this.bodiesEventsPanel=new Ie(this.shadow.getElementById("bodies-events-section"),s,void 0,"bodies"),this.aroundPanel=new ur(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 l=Number(this.samplingRateInput.value);s.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(l)&&l>0?l:void 0,pe.refresh(this.ufoElement.sighting),s.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.snapshotsPanel.localize(this.messages),this.sectionFilePanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",l=>{l.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 wr(this.shadow.getElementById("aircraft-flights"),l=>this.aimAtFlight(l),l=>this.naming.point(l)),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 be({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:l=>`option-decor-${l}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:l=>this.selectDecor(l),onAdd:l=>this.addDecor(l),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 be({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:l=>this.selectObserver(l),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 se(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:l=>this.setPlantedDecor(l),kindName:l=>this.decorList.kindLabel(l),cite:l=>this.citeSource(l),busy:(l,h)=>this.sceneElement.setBusy(l,h),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(l=>({lat:l.pose.lat,lng:l.pose.lng})).filter(l=>typeof l.lat=="number"&&typeof l.lng=="number")},this.messages,async(l,h)=>this.surroundingsProvider?this.surroundingsProvider.covers(l,h)?this.surroundingsProvider:void 0:(await T(async()=>{const{SurroundingsSources:c}=await import("./surroundingsSources--qffL_nJ.js");return{SurroundingsSources:c}},__vite__mapDeps([29,1,2,3,4,5,6,7,8,9,10,11]),import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,l,h),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const l=this.scenerySource.value===w.FILE_SOURCE;if(this.setDecorFromFile(l),l){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===w.NO_SCENERY){this.surroundings.withdraw();return}const h=this.plantingCentre();h&&this.surroundings.survey(h.lat,h.lng)}),this.sceneryRadius.addEventListener("input",()=>{const l=Number(this.sceneryRadius.value);if(!Number.isFinite(l)||l<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const h=this.plantingCentre();this.surroundings.radiusChanged(l,h?.lat,h?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSourceInput=this.shadow.getElementById("reference-source"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceVideoFromInput=this.shadow.getElementById("referenceVideoFrom"),this.referenceVideoToInput=this.shadow.getElementById("referenceVideoTo"),this.referenceVideoRateInput=this.shadow.getElementById("referenceVideoRate"),this.referenceRemoveKeyButton=this.shadow.getElementById("reference-remove-key"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new fi(this.addReferenceButton,"reference-add-kind",l=>this.addReferenceOfKind(l),l=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[l]??`reference-add-${l}`),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 pt(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 lt(this.decorParametersHost,"en","decorParam.");const n={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new lt(this.decorBaseHost,"en","decorBase.",n,(l,h)=>this.enhanceDecorModelChoice(l,h)),this.decorStateForm=new lt(this.decorStateHost,"en","decorState.",n),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",l=>{this.focus({preventScroll:!0}),this.onPointerDown(l)}),this.ufoElement.canvasElement.addEventListener("pointermove",l=>this.onPointerMove(l));let r;this.ufoElement.canvasElement.addEventListener("pointerdown",l=>{r={x:l.clientX,y:l.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",l=>{const h=r;r=void 0,!(!h?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(l.clientX-h.x,l.clientY-h.y)>w.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",l=>this.onContextMenu(l)),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 o=this.shadow.getElementById("editor-mute"),a=this.shadow.getElementById("editor-volume");o.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.toggleMuted()}),a.addEventListener("input",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.volume=Number(a.value)}),this.ufoElement.addEventListener("mutedchange",()=>this.syncSoundControls()),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.exportKmlButton.addEventListener("click",()=>void this.exportFigures("kml")),this.exportGeoJsonButton.addEventListener("click",()=>void this.exportFigures("geojson")),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",l=>{const h=l.detail;h.file?this.importFromFile(h.file):this.importFromUrl(h.url)}),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()});for(const l of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])l.addEventListener(l instanceof HTMLSelectElement||l.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 l=this.ufoElement.sighting;l.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),l.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),l.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",l=>{const{seconds:h,text:c}=l.detail;this.ufoElement.sighting.event.durationText=c,this.ufoElement.durationSeconds=h,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((h??0)*1e3),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const l of this.referenceFields)l.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",l=>void this.setReferenceSource(l.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 l=this.shadow.getElementById("trace-import-row");l.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",l=>void this.addTraces(l.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",l=>this.onReferenceWheel(l),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",l=>this.onBodyWheel(l),{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 l of[this.milestoneLabelInput,this.milestoneNoteInput])l.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(kn,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(xn,()=>{const l=this.currentReference();l&&this.syncReferenceStatus(l)}),this.sceneElement.addEventListener(Sn,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(In,()=>{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 fi(this.addShapeButton,"add-shape-kind",l=>{const h=Ae.byId(l);if(h){this.addModel(h);return}this.currentAppearance={...this.currentAppearance,presetId:l},this.addShape()},l=>`add-shape-${l}`),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 l of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])l.addEventListener("input",()=>this.updateObserver());for(const l of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])l.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",l=>{if(this.observerSaid=l.detail.said,!this.observerPosition.relative)return;const h=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(h,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",l=>this.writeObserverBasis(l.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",l=>{l.key==="Enter"&&(l.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 l=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const h=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(c=>[c.t,Pe.fovOf(this.ufoElement.sighting,c.t)]));this.retuneFieldOfView(l),this.retuneExposure(l),Pe.reproject(this.ufoElement.sighting,l,h),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.accountCompareInput.addEventListener("change",()=>this.syncBodiesShown()),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const d=l=>this.shadow.querySelector(`${Ht}[name="${l}"]`);this.startDate=d("obs-time"),this.endDate=d("obs-end-time"),this.birthDate=d("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=wt.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const l of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(l,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",l=>{const{time:h}=l.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=h}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",l=>{this.birth=l.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",l=>{const{time:h}=l.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=h})});for(const l of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])l.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(w.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const l of this.weatherFields){if(l===this.iceCrystalAlignmentInput||l===this.rareIceCrystalsInput){l.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}l.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const l of this.soundFields)l.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(l=>this.shadow.getElementById(l.getAttribute("aria-controls")));for(const l of this.groupTabs)l.addEventListener("click",()=>this.toggleGroup(l,!this.isGroupOpen(l)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const l of this.subgroupTabs)l.addEventListener("click",()=>this.openSubgroup(l)),w.pictureTab(l);this.buildSkyParts(),Ut.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",l=>this.onParamSummaryClick(l)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(l=>l.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=dr(this.shadow.getElementById("cloud-editor"),this.sceneElement,(l=!0)=>{l&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(l,h)=>{this.headingInput.value=String(this.rounded(l)),this.pitchInput.value=String(this.rounded(h)),this.updateObserver()},Ft(Oe.preferencesFor(this),mt),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),Oe.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),ce.changes.addEventListener("change",this.onModulesChanged),T(async()=>{const{ModuleSession:t}=await import("./ModuleSession-BKDWGSEo.js");return{ModuleSession:t}},__vite__mapDeps([30,1,10,7]),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=wt.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),ce.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=Ge.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]??ot,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:()=>`${wi.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(z.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 T(async()=>{const{zipSync:l,strToU8:h}=await import("./browser-CltifEM0.js");return{zipSync:l,strToU8:h}},[],import.meta.url),a={[s]:o(n)};for(const[l,h]of t)a[l]=h;const d=r(a,{level:0});this.download(new Blob([d],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.snapshotExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",j.size(d.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)),...te.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,w.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=te.NAMES.includes(e),i=$.NAMES.includes(e)?e:void 0,s=e===w.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||be.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)?Yt.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 ei)||ce.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),a=o===void 0?void 0:ce.installed().find(d=>d.id===o)?.url;!a||xs.names(n,a,s)||(n=[...n??[],xs.of(a,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??=T(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-DH1oroWm.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([31,1,30,10,7,6,13,14,2,3,4,5,8,9,11,15,16,17,18,19,20]),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=_(yt,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:_(ht,this.chosenSourceId.get("imagery")).id,roads:Ln(),water:Mn(),railways:Tn()}}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)}));he.release();const i=await this.recordingText(t),s=JSON.parse(i);if(ne.isCase(s)){if(ne.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 T(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)&&he.hold(he.address(h.slice(o.length),void 0),c);const a=i(s[r]),d=JSON.parse(a);let l=!1;for(const h of $.NAMES){const c=d.snapshots?.[h]?.src,u=c!==void 0?s[o+c]:void 0;if(!u)continue;const p=Ge.recording(JSON.parse(i(u)));$.put(h,d,p),l=!0}return l?JSON.stringify(d):a}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 et.recording(e);if(ne.isCase(t)){ne.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;he.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(){z.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof zt)return e.said(this.messages.formatVersionError);if(!(e instanceof Zs))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=St[0].create();get narrativeSourceId(){return _(St,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:w.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof ue&&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=Se.stated(r);if(o.length>0){const a=this.ufoElement.sighting.provenance,d=Hi(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=Se.apply(d,Kt.loadable(r),o)}finally{this.patchingDraft=!1}this.ufoElement.sighting.provenance=a,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:w.valueAt(Hi(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[wo[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=_(St,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 a of i.choices??[]){const d=document.createElement("option");d.value=a.value,d.textContent=this.said.read(a.label)??a.value,r.appendChild(d)}}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 ue))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(){w.pageCredentials.clear(),ti.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!==""?w.pageCredentials.set(t,i):w.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(w.NARRATIVE_KEY_STORAGE),localStorage.removeItem(w.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 w.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} `),w.creditLink(_(ci,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",ir,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(_(Tt,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",St,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",ci,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",Tt,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",yt,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",ht,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[w.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[w.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[w.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",Wi,()=>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,w.FILE_SOURCE))};o();const a=()=>{const f=this.chosenSourceId.get(e);return f!==void 0&&t.some(g=>g.id===f)?f:t[0].id};r.value=s?.fromFile()?w.FILE_SOURCE:a();const d=document.createElement("a");d.className="source-credit",d.target="_blank",d.rel="noopener noreferrer";const l=document.createElement("button");l.type="button",l.className="link source-file-link",l.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=_(t,r.value);ti.set(f.id,c.value),i(f,!0)});const p=()=>{const f=r.value===w.FILE_SOURCE,g=_(t,f?a():r.value);h.hidden=f||!g.keyUrl,u.href=g.keyUrl??"",c.value=ti.of(g.id)??"",r.title=f?s.where():g.credit,d.hidden=f,d.href=g.creditUrl,d.textContent=g.credit,l.hidden=!f,f&&(l.textContent=s.label(),l.title=s.where())};p(),r.addEventListener("change",()=>{const f=r.value===w.FILE_SOURCE;f||this.chosenSourceId.set(e,r.value),s?.setFromFile(f),p(),f||i(_(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?w.FILE_SOURCE:a(),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===w.FILE_SOURCE&&s?f:a(),p(),g&&r.value!==w.FILE_SOURCE&&i(_(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),d,l,h),n}aircraftPicker(){const e=this.sourcePicker("aircraft",ji,(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?z.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):z.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=te.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=w.LIVE_ROADS;static LIVE_RAILWAYS=w.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 a=s.map(([l,h,c])=>{o.append(new Option(h,l));const u=document.createElement("span");return u.className="source-picker",u.dataset.kind=l,u.append(c),u});o.value=this.sourceKindShown.get(i)??s[0][0];const d=()=>{this.sourceKindShown.set(i,o.value);for(const l of a)l.hidden=l.dataset.kind!==o.value};o.addEventListener("change",d),d(),n.append(r,document.createTextNode(" "),o),e.replaceChildren(n,...a)}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} `),w.creditLink(_(ci,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(_(Tt,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:_(yt,this.chosenSourceId.get("elevation")).create(),imagery:_(ht,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(_(ji,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new ei(_(Wi,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)<Xe&&Math.abs(i-this.namedCoordinates.lng)<Xe||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),Is))}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)<Xe&&Math.abs(i-s.lng)<Xe||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),Is))}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,a=this.ufoElement.sighting.observerTrack,d=this.ufoElement.currentTime,l=a.getInterpolatedPoseAt(d),h=l?.altitudeM!==void 0?r:void 0,c=h!==void 0?l.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?ke.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),f=this.numberOrUndefined(this.fNumberInput.value),g=this.filterSelect.value,b=de.byId(a.getLatestPoseAt(d-1)?.filter),v=g===de.NONE.id||g===""?b===de.NONE?void 0:de.NONE.id:g,y=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=y===u.exposureSeconds?void 0:y;const S=this.numberOrUndefined(this.focusDistanceInput.value),k=Math.abs(m-ke.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&&!k?a.removeKeyframeAt(d):a.addKeyframe(d,{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()),R=a.getInterpolatedPoseAt(0);o.place=e!==void 0&&t!==void 0?[{lat:R?.lat??e,lng:R?.lng??t,name:C}]:void 0;const M=this.plantingCentre();this.surroundings.placeChanged(M?.lat,M?.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&&!It.isFirm(t))return;const s=It.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&&It.at(i,e)===t)return;const s=It.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&&$t({...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:wt.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},a=Object.keys(o).length>0?[o,...s]:s;e.sources=a.length>0?a: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={...oe(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={...oe(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;be.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"||Be.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=Be.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=Be.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(z.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>Rr?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)||Mt))},a=this.registrationShown(n),d=o.headingDeg!==a.headingDeg||o.pitchDeg!==a.pitchDeg||o.rollDeg!==a.rollDeg||o.fovDeg!==a.fovDeg,l=this.referenceKindSelect.value;return l==="video"?{...d?Be.withKey(n,this.ufoElement.currentTime,o):n,kind:l,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:l,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:d?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=ie(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(Be.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=ie(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=ie(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:Or,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:Mt},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,a)=>{const d=new FileReader;d.onload=()=>o(d.result),d.onerror=()=>a(d.error),d.readAsDataURL(r)})}else i=e.url;const s=this.ufoElement.sighting,n=Be.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??=T(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-BJeiCK8A.js");return{PictureRegistration:e}},__vite__mapDeps([32,5]),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:Be.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 a=this.pictureRegistration.picturePointOf(r,s.registration,n);return a?{...o,picture:a}: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)||Mt,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 a=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,n)+a,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);be.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,a)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(o.scene)),label:this.landmarkLabel(o,a),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)),a=[];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||a.push({ghost:c,light:u,ghostRadius:p?Math.hypot(p.x-c.x,p.y-c.y):0})}const d=n.centre?o(n.centre):void 0,l=n.cropped?o({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(a,d,l)}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(Be.rollOfPicture(s)??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(d=>d.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)),a=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[d,l]of a)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${d}`,{basis:"derived",rationale:o,of:this.rounded(l)})}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=ie(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 T(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 a=document.createElement("option");a.value=String(r),a.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(a)}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:Mt}})}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;be.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:l}=await T(async()=>{const{TraceImport:h}=await import("./TraceImport-CntRHXoJ.js");return{TraceImport:h}},__vite__mapDeps([33,1]),import.meta.url);i=await l.fromBytes(await Ys.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(l=>l.id));let r=1;const o=this.said.write(void 0,i.documentName??t,this.writingLanguage),a=i.traces.map(l=>{for(;n.has(`trace-${r}`);)r++;const h=`trace-${r}`;return n.add(h),{...l,id:h,title:l.title===void 0?void 0:this.said.write(void 0,l.title,this.writingLanguage),source:o}});s.traces=[...s.traces,...a],this.currentTraceId=a[0].id,this.refreshTraceList();const d=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(a.length)).replace("{name}",t)+d,this.ufoElement.refresh()}async exportFigures(e){const t=this.fileBase(),{GEO_EXPORT_TEXTS:i}=await T(async()=>{const{GEO_EXPORT_TEXTS:o}=await import("./GeoExportTexts-3a51cuxQ.js");return{GEO_EXPORT_TEXTS:o}},__vite__mapDeps([34,1]),import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:o}=await T(async()=>{const{KmlExport:d}=await import("./KmlExport-DEPgRRWe.js");return{KmlExport:d}},__vite__mapDeps([35,36,3,4,1,6,7,2,5,8,9,10,11]),import.meta.url),a=o.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([a],{type:"application/vnd.google-earth.kml+xml"}),`${t}.kml`);return}const{GeoJsonExport:n}=await T(async()=>{const{GeoJsonExport:o}=await import("./GeoJsonExport-iyhoKOUU.js");return{GeoJsonExport:o}},__vite__mapDeps([37,36,3,4,1,6,7,2,5,8,9,10,11]),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 Wn){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(),eo)}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=jn(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 rt(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===w.FILE_SOURCE;if(!e){const t=_(xe,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new rt(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=te.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=xe.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==_(xe,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new rt(e.create())}else!e&&t!==void 0&&!xe.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new rt(_(xe,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...xe.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,w.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!At(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?w.FILE_SOURCE:i?i.id:_(xe,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=_(xe,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&&!At(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),Ss))}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||!At(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&&At(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&&ve(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=Tt[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(),Ss)}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=$t(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=Gn(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?ii.MUTED:ii.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(),A.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(dt.opensPrecise(e.time)),this.endDate.setPrecise(dt.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)>ro;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),so))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Xe&&Math.abs(e.lng-i)<Xe}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=_(yt,this.chosenSourceId.get("elevation")),n=await new Mi(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=ie(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(w.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(dt.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=oe(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??yi)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??Kn)),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=rs(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!==w.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 T(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-DS1DRU2p.js");return{SightingFileEditor:t}},__vite__mapDeps([26,27,28]),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"){z.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 cs.of(e,t,t==="thin"?Pe.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(w.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(w.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Rs(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=cs.of(this.ownJson(vi(e)),t,t==="thin"?Pe.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(w.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 a=this.ufoElement.sighting.weatherSource;a===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):xe.some(d=>d.id===a.id)&&this.askAboutWeather(o,a.name??a.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(a){this.showFileNote(a instanceof zt?a.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,a=[];for(let d=0;d<360;d+=w.COMPASS_STEP_DEG){const l=this.sceneElement.horizonPointAt(d);l&&s(l)&&a.push({...l,label:this.naming.point(d)})}n={label:this.messages.overlayHeading.replaceAll("{deg}",i(o)).replaceAll("{point}",this.naming.point(o)),compass:a}}let r;if(t!==void 0){const o=[[]];for(let a=0;a<=360;a+=w.HORIZON_STEP_DEG){const d=this.sceneElement.horizonPointAt(a);d&&Math.abs(d.x-.5)<1.5&&Math.abs(d.y-.5)<1.5?o[o.length-1].push(d):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=d=>this.numberOrUndefined(d.value),a=(d,l=1)=>d===void 0?"?":d.toLocaleString(this.language,{maximumFractionDigits:l});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 d=Pe.fovOf(i,s),h=2*si.of(i.instrument,n.height,d).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",a(d)).replaceAll("{h}",a(h)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const d=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!d){e.hide();return}const l=d.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])=>`${a(u,m)}${p}`).join(" · ");e.measure((l.x+l.width/2)/n.width,(l.y+l.height/2)/n.height,Math.max(l.width,l.height)*1.3/n.width,c)}else if(t==="windDirection"||t==="windSpeed"){const d=o(this.windDirectionInput)??0,l=d-(o(this.headingInput)??0);e.wind(l,r.overlayWind.replaceAll("{point}",this.naming.point(d)).replaceAll("{speed}",a(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=d=>{let l=-1;return d.forEach((h,c)=>{h<=i()&&(l=c)}),l===-1&&d.length>0?0:l};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const d=n(t().observerTrack.allKeyframes.map(l=>l.t));return d===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${d}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const d=t().timeline.allKeyframes,l=n(d.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId)).map(p=>p.t));if(l===-1||this.apparentWidthInput.value==="")return;const h=d.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId))[l],c=d.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",o.dataset.icon="candidates",this.shadow.getElementById("group-observation").append(o);const a=d=>d?.closest("label")??void 0;this.candidatesView=new re({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const d=this.ufoElement.sighting.event,l=d.place?.[0];if(!l||d.time?.year===void 0||d.time.hour===void 0)return;const h=ve(d.time,l.lng,d.utcOffsetHours);return h?{date:h,observer:{lat:l.lat,lng:l.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:d=>Ze(d,this.instrumentGain()),fieldLabels:()=>({time:a(s),heading:a(this.headingInput),size:a(this.apparentWidthInput),duration:a(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:d=>{const l=`${d}/${this.language}`;return this.poherMatrix?.key!==l&&(this.poherMatrix={key:l,loaded:Ue.load(d,this.language,h=>et.json(h))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const d=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,l=this.sceneElement.satellitePassesDuring(d);return l.length>0?{passes:l,positionsAt:h=>this.sceneElement.satellitePositionsAt(h)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const d=this.ufoElement.sighting.interpretation;return[...d&&(d.bodies.length>0||Rt.computes(d,Pt.kinds()))?[{id:"own",label:this.said.read(d.title)??this.principalObserverLabel(),interpretation:d}]:[],...this.readings]},computed:d=>this.sceneElement.computedInterpretation(d),starName:d=>this.naming.star({name:d}),projectionAt:(d,l)=>this.sceneElement.bodyProjectionAt(d,l),variants:()=>this.ufoElement.sighting.variants,keep:d=>this.editVariants(l=>[...l,d]),remove:d=>this.editVariants(l=>l.filter((h,c)=>c!==d))},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 l=ve(i.time,s.lng,i.utcOffsetHours);l&&(t.sunAltitudeDeg=G("Sun",l,{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 l=oe(e,0);t.cloudCover=l.cloudCover,t.lightning=l.storm,t.lowVisibility=l.precipitationType!=="none"&&l.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const l=n.allKeyframes.filter(u=>u.shapes.some(p=>p.sourceId===r)),h=l.map(u=>({t:u.t,shape:n.getShapeAt(u.t,r)})).filter(u=>u.shape?.aim),c=n.getInterpolatedShapeAt(l[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,y=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,y)))/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(l=>n.groupMembers(l)?.[0]??l));o.size>0&&(t.count=o.size);const a=[...o].map(l=>n.getInterpolatedShapeAt(0,l)?.aim).filter(l=>l!==void 0);if(a.length>=3){const l=Math.PI/180,h=a.map(m=>({x:(((m.azimuthDeg-a[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*l),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 d=new Set([...o].map(l=>n.getInterpolatedShapeAt(0,l)?.color).filter(l=>l!==void 0));return d.size>0&&(t.colors=[...d]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(l=>l.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=()=>getComputedStyle(t).display==="grid",n=()=>s()?"--rr0-scene-wide-height":"--rr0-scene-max-height",r=()=>s()?`${w.SCENE_HEIGHT_KEY}-wide`:w.SCENE_HEIGHT_KEY,o=a=>{const[d,l]=[n(),r()];a===void 0?t.style.removeProperty(d):t.style.setProperty(d,`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,a)))}px`);try{a===void 0?localStorage.removeItem(l):localStorage.setItem(l,t.style.getPropertyValue(d))}catch{}};try{for(const[a,d]of[["--rr0-scene-max-height",w.SCENE_HEIGHT_KEY],["--rr0-scene-wide-height",`${w.SCENE_HEIGHT_KEY}-wide`]]){const l=localStorage.getItem(d);l&&/^\d+px$/.test(l)&&t.style.setProperty(a,l)}}catch{}e.addEventListener("pointerdown",a=>{a.preventDefault();const d=a.clientY,l=i.getBoundingClientRect().height;e.setPointerCapture?.(a.pointerId),e.classList.add("dragging");const h=u=>o(l+u.clientY-d),c=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",h),e.removeEventListener("pointerup",c),e.removeEventListener("pointercancel",c)};e.addEventListener("pointermove",h),e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}),e.addEventListener("keydown",a=>{a.key!=="ArrowUp"&&a.key!=="ArrowDown"||(a.preventDefault(),o(i.getBoundingClientRect().height+(a.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>o(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 a=this.groupTabs.find(d=>d.getAttribute("aria-controls")===o);a&&this.toggleGroup(a,!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"?pe.observerTrackIsExpanded(t):pe.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(l=>l.t)};const n=this.ufoElement.seekableDuration,r=l=>e==="observer"?q.isObserver(t,l):q.isPhenomenon(t,l),o=(t.events??[]).map((l,h)=>({event:l,index:h})).filter(({event:l})=>r(l)),a=new Set(o.map(({event:l})=>l.who)).size>1,d=o.map(({event:l,index:h})=>{const c=this.messages.events.kinds[l.eventType]??l.eventType;return{id:String(h),t:l.t,until:l.until??n,label:e==="phenomenon"&&a?`${this.shapesLabel(l.who??"")} · ${c}`:c}});return{times:[],spans:d}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(a=>a.id)),s=a=>q.partOf(a)?.element??a??"",n=(e.events??[]).map((a,d)=>({event:a,index:d})).filter(({event:a})=>i.has(s(a.who)));if(n.length===0||!pe.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(a=>a.track.map(d=>d.t)))].sort((a,d)=>a-d)};const r=this.ufoElement.seekableDuration,o=n.map(({event:a,index:d})=>{const l=t.find(p=>p.id===s(a.who)),h=q.partOf(a.who)?.part,c=this.messages.events.kinds[a.eventType]??a.eventType,u=[...t.length>1?[this.said.read(l?.title)??s(a.who)]:[],...h?[h]:[]];return{id:String(d),t:a.t,until:a.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=(a,d)=>[...d].map(l=>({t:l,kind:"keyframe",label:`${this.messages.keyframeMark} (${a})`})),i=a=>{if(this.showsBodies){const l=this.eventMarks("bodies");return l.spans?l.spans.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.bodiesTrack,l.times)}const{spans:d}=this.eventMarks("phenomenon");return d?d.map(l=>({t:l.t,kind:"event",label:l.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(l=>!a||l.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(l=>l.t))},s=()=>{const{times:a,spans:d}=this.eventMarks("observer");return d?d.map(l=>({t:l.t,kind:"event",label:l.label})):t(this.messages.observerTrack,a)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(a=>a.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(a=>a.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 a of e.milestones)o.push({t:a.t,kind:"milestone",label:this.said.read(a.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=ii.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=Pt.kinds();if(Rt.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Rt.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(d=>d.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:o,opensMostLacking:a}=this;this.openSubgroup(r),this.sectionChosen=o,this.opensMostLacking=a}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=w.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:w.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),Cs.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 An(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(`
2778
- `)}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=w.QUESTION_FIELDS[n];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const a=this.shadow.getElementById(o);a&&!a.hidden&&a.value===""&&t.add(o)}}for(const[n,r]of Object.entries(w.QUESTION_FIELDS))for(const o of w.QUESTION_FIELDS[n].fields){const a=this.shadow.getElementById(o);if(!a)continue;const d=t.has(o)&&!a.classList.contains("missing-required");a.classList.toggle("wanted",d),(d||a.title===this.messages.questionUnanswered)&&(a.title=d?this.messages.questionUnanswered:this.fieldHints.get(o)??"")}const i=new Map;let s;for(const[n,r]of Object.entries(w.QUESTION_FIELDS))for(const o of r.fields){const a=this.shadow.getElementById(o);if(!a)continue;const d=a.classList.contains("missing-required");!d&&!a.classList.contains("wanted")||(d&&(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,a=r===s,d=w.badgeOn(n);d.hidden=o===0,d.textContent=String(o),d.classList.toggle("optional",!a);const l=o===0?void 0:a?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o));l?n.dataset.unanswered=l:delete n.dataset.unanswered,w.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(a=>a.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(a=>a.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&&be.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:fo(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(w.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,fe.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,fe.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(fe.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(fe.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),a={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-o)/2,width:r,height:o},d=n.ofBounds(a),l=s.kind==="oval"?{...s,bounds:a,angular:d}:{...s,bounds:a,angular:d,points:this.scalePoints(s,a)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:l}]),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={[de.NONE.id]:this.messages.filterNone,[de.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[de.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==de.ALL.length||de.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||de.NONE.id;this.filterSelect.replaceChildren();for(const r of de.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||de.usableWith(de.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),a=ke.unavailability(r,t);if(!a)return{id:r.id,label:o};const d=(a.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(a.from)).replace("{to}",String(a.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",o),hint:d}:{id:r.id,label:o,disabledReason:d}};this.instrumentSelect.choices=ke.CATEGORIES.map(r=>({label:s[r],children:Vn.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=w.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=ie(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??ke.fieldOfViewDeg(t),r=s?ke.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),Ut.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 a=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=a===void 0?"":w.exposureText(a)),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,Dn.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const d=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const l=Et.byId(e.film);this.isoInput.placeholder=d?d.autoExposure?"auto":String(l?.iso??d.iso):"",this.setRowVisible(this.isoInput,d!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,d?.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=de.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=ke.fieldOfViewDeg(e),s=ke.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>lo||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 ie(e,this.ufoElement.currentTime)?.fovDeg??ke.fieldOfViewDeg(e.instrument)}currentProjection(){return si.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=fe.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=ie(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?ke.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,o=s?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const a=this.ufoElement.canvasElement.height;if(a<=0)return;const d=2*Cn*e/a*i.heightMm,l=r*r/(o*d)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(l))}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)??io,o=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),a=o!==void 0&&o<r,d=s(r,1),l=i?.angular?.widthDeg,h=i?.angular?.heightDeg,c=l!==void 0&&h!==void 0&&l>0&&h>0?{widthM:s(fe.sizeMAt(d,l),2),lengthM:s(fe.sizeMAt(d,l),2),heightM:s(fe.sizeMAt(d,h),2)}:void 0,u={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},p={t,...u,distanceM:d,...a?{onGround:!0}:{},...c?{sizeM:c}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:p}:{keyframe:p}}loadBodyEditor(){return this.bodyEditorLoading??=T(async()=>{const{BodyEditor:e}=await import("./BodyEditor-BG--NjnZ.js");return{BodyEditor:e}},__vite__mapDeps([38,2,1,3,4,5,6,7,8,9,10,11,13,16]),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=Pt.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=Os.map(i=>Bt.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]}static pictureTab(e){const t=A.part(e.getAttribute("aria-controls")??"");t&&!e.querySelector("svg")&&e.insertAdjacentHTML("afterbegin",t)}buildSkyParts(){const e=this.shadow.getElementById("weather-tabs"),t=this.shadow.getElementById("sky-event-parts");if(!e||!t)return;const i=this.wantedSkyParts();for(const[s,n]of this.skyParts)if(!i.some(r=>r.key===s&&r.kind===n.kind)){if(n.tab.getAttribute("aria-expanded")==="true"){const r=this.subgroupTabs.find(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),w.pictureTab(n),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 a=document.createElement("div");a.className="toolbar";const d=document.createElement("div");d.id=`${s.id}-editor`,a.append(d),o.append(a),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(wt.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:fe.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=si.of(i.instrument,fe.CANVAS_HEIGHT_PX,Pe.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const o=Pe.aimOf(i,e,r.shape.bounds),a=s.ofBounds(r.shape.bounds),{aim:d,...l}=r.shape;return{...r,shape:o?{...l,aim:o,angular:a}:{...l,angular:a}}}))}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},...Ae.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(l=>l.value===e.id).label,o=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",a={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},d=s.map((l,h)=>{const c=e.partNames[h],u=c?`${r} ${o}, ${a[c]}`:`${r} ${o}`;return{sourceId:n[h],shape:{...l,title:this.said.write(void 0,u,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,d),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(a=>t.includes(a.sourceId)).map(a=>{const{bounds:d}=a.shape;return{sourceId:i[t.indexOf(a.sourceId)],shape:{...a.shape,bounds:{...d,x:d.x+s,y:d.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]??ot,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:Gi.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Fs}:{},windows:zs(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(w.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(w.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(w.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(w.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await T(()=>import("./surroundingsSources--qffL_nJ.js"),__vite__mapDeps([29,1,2,3,4,5,6,7,8,9,10,11]),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=w.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(o=>{const a=document.createElement("option");return a.value=o.id,a.textContent=o.name,a.title=o.credit,a}),r=new Option(this.messages.sourceFile,w.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!==w.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?w.FILE_SOURCE:this.sceneryChoice===w.NO_SCENERY?w.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===w.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=te.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?Wt.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*mi,t=Math.round(e/co*1e3);return{lights:Gi.byId("airliner")?.create(),track:[{t:0,eastM:-mi,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:mi,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=Qn(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?os[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(a=>a.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(([,a])=>a!==void 0).map(([a,d])=>[a,this.roundedMeters(d)]))};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=Ki([...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=Ki(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;be.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=w.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!==w.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!==w.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 T(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([39,40]),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=Et.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=(a,d,l=!1)=>{const h=document.createElement("option");h.value=a,h.textContent=d,h.disabled=l,this.filmStockSelect.appendChild(h)};r("",this.messages.filmStockAny);const o=i.map(a=>({stock:a,gap:Et.gap(a,t,s)}));for(const{stock:a}of o.filter(d=>!d.gap))r(a.id,a.name);for(const{stock:a,gap:d}of o.filter(l=>l.gap)){const l=d.kind==="before"?this.messages.filmStockNotYet.replace("{from}",String(d.from)):this.messages.filmStockNoLonger.replace("{to}",String(d.to));r(a.id,`${a.name} (${l})`,a.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(Et.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 _t(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?nt.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(at.resolve(ge.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(at.resolve(ge.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}=as(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=Vi.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:qi.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Vi.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:ge.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:os[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(d=>d.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=nt.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const o=this.ufoElement.sighting;o.decor=o.decor.map(d=>d.id===s.id?nt.apply(d,r,t,n):d),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const a=o.decor.find(d=>d.id===s.id);t==="title"&&this.decorList.rename(a.id,this.decorLabel(a)),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?Ds.of(e,this.publishedParametersOf(e)):void 0,i=t&&at.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 _t(()=>this.ufoElement.sighting.decor.find(o=>o.id===n),o=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(d=>{if(d.id!==n)return d;const l=structuredClone(d);return o(l),l})});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?ve(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=G("Sun",i,t).altitudeDeg;return Ze(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new er;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Zi;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new gt(["en"]);tagNames=new Yi({});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?ve(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,oe(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,a=[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(d=>d!==void 0);o||(this.showMeteorButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0),this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",a.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 On.gainFor(e.instrument,{fNumber:ie(e,0)?.fNumber,fieldOfViewDeg:Pe.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=G("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Ze(i,s,n),o=l=>l.toLocaleString(void 0,{maximumFractionDigits:1});if(r<no)return this.messages.skyStarsNone;const a=this.ufoElement.sighting.instrument,d=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(a)).replace("{gain}",o(Math.abs(s))).replace("{eye}",o(Ze(i,0,n)));return r<=Ji?d:d+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Ji))}showerClause(e,t){const i=Xi.observedRatePerHour(Xi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=ni.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=ni.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:ni.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=ri.brightestAt(e,t);if(!i||i.magnitude>Qi){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=es.brightestAt(e,t);if(!i||i.magnitude>Qi){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=Rn.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=G("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=G("Moon",e,t);if(i.altitudeDeg<=0||Qe(e).illuminatedFraction<.97)return;const s=[],n=Ye.distanceKm(e,t),r=Ye.relativeToMean(Ye.radiusAtKm(n)),o=n<=Ye.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Ye.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(Ye.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Zt.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=we.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=Ze(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 a=Math.round(i.shadowHeightKm).toLocaleString(),d=(i.trackedObjects??0).toLocaleString(),l=h=>h.replace("{height}",a).replace("{count}",d);return i.lowOrbitLit?r.length===0?l(this.messages.skySatellitesLit):l(this.messages.skySatellitesLitWith).replace("{eras}",o):l(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 d={key:n,status:"loading"};this.reentries=d,w.reentryArchive.candidates(i,s,t).then(l=>{d.status=l?"ready":"unavailable",d.candidates=l,this.reentries===d&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=we.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(d=>d.record.precision==="minute"||r);if(o.length===0)return;const a=o.slice(0,3).map(d=>this.reentryText(d));return o.length>3&&a.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",a.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(d=>d.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(d=>d.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)),a=this.starlinkTrain(i);return a?`${o}, ${a}`: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=G("Sun",i.peak.date,t);return s<=Ze(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:a}=r.peak.object;o!=="starlink"||!a||(r.peak.date.getTime()-Date.parse(`${a}T00:00:00Z`))/864e5>60||t.set(a,(t.get(a)??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=ie(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=ve(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=>ts.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=ts.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=ve(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=oe(this.ufoElement.sighting,0),s=G("Sun",e,t),n=G("Moon",e,t),r=kt.deckLitUntilDeg(kt.DECK_HEIGHT_M),o=s.altitudeDeg>-r,a=o?s:n;if(a.altitudeDeg<=-r)return;const d=i.highCloudCover;if(d===void 0||d<=0)return this.messages.skyOpticsNoIce;if(kt.strength(d,i.lowerCloudCover??i.cloudCover,a.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const l=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,h=this.listed(kt.formsAt(a.altitudeDeg,r).map(u=>this.opticsFormName(u))),c=i.iceCrystalAlignment??yi;return this.messages.skyOpticsPossible.replace("{forms}",h).replace("{source}",l)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(c*100)))}rainbowClause(e,t){const i=oe(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=G("Sun",e,t),n=G("Moon",e,t),r=s.altitudeDeg>0,o=r?s:n;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const a=i.lowerCloudCover??i.cloudCover;if(oi.strength(i.precipitationIntensity,a,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const d=oi.formsAt(o.altitudeDeg);if(d.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(oi.primary().radiusDeg)));const l=this.listed(d.map(c=>this.bowFormName(c)));if(r)return this.messages.skyBowPossible.replace("{forms}",l);const h=Math.round(Qe(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",l).replace("{lit}",String(h))}glowClause(e,t){const i=G("Sun",e,t);if(i.altitudeDeg>bo)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<=P.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=G("Moon",e,t),a=s.darkestSkyMagPerArcsec2<vo,d=this.ufoElement.sighting.lightPollution,l=me.scatteringAt(90-o.altitudeDeg)*me.moonOutput(me.phaseAngleOf(Qe(e).illuminatedFraction),o.altitudeDeg)*me.scatteredFraction(90),h=me.artificialZenithNanolamberts(d)>l;if(a&&o.altitudeDeg>0&&!h){const u=Math.round(Qe(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(u)).replace("{sky}",r)}const c=me.artificialZenithNanolamberts(d)>me.twilightExcessNanolamberts(i.altitudeDeg);return a&&h&&c?this.messages.skyGlowTowns.replace("{sky}",r):a?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=G("Sun",e,t),s=G("Moon",e,t);return me.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:me.phaseAngleOf(Qe(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new P;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<ri.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=ve(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=ri.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=ve(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=es.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(d=>d.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}=as(e,this.ufoElement.currentTime),r=Math.hypot(i,s);if(r===0&&n===0)return;const o=Math.atan2(i,s)*180/Math.PI,a=Math.atan2(n-ho-(ie(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(a*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??w.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return rs(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Je.width/2,y:e.height/2-Je.height/2,width:Je.width,height:Je.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 Ti(this.ufoElement.sighting.timeline,new yr(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"})),A.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=Oe.preferencesFor(this);this.preferences=t;const i=Ft(t,mt),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,a,d]=await Promise.all([Ls.load(i),i==="en"?{}:Js(i),Xs(i),pr.load(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.decorParameterTexts=d,this.naming=new Zi(a),this.said=new gt(t),this.tagNames=new Yi(o),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new is(r,this.naming,this.said,this.tagNames,{messages:r,locale:this.language},this.decorParameterTexts),this.refreshParamSummary()),l?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===ot&&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(w.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(w.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(Ai))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,ye.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 is(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,ye.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.sectionIndexResize.label(e.resizeSectionIndex),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])_e.popover(this.shadow.getElementById(s),e.close);_e.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),_e.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),_e.button(this.contextMenu,e.close,()=>this.hideContextMenu()),_e.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,w.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",a=i==="shape";if(a)if(this.selectedSourceIds.size>1){const h=new ai(this.selectedMembers()),c=ee.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"?ee.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&&ee.hitTestHandle(h,t);if(h&&u){if(o)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const d=this.ufoElement.shapeAt(t.x,t.y,Dt);if(!d){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(d.sourceId):this.selectedSourceIds.has(d.sourceId)||this.selectUnit(d.sourceId),o||!a)return;const l=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===d.sourceId?d.shape:n.getInterpolatedShapeAt(r,h)??d.shape}));this.dragState={kind:"move",sources:l,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"&&ee.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId,shape:n}:this.ufoElement.shapeAt(t.x,t.y,Dt);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 a=this.pickDecorAt(e),d=a?this.ufoElement.sighting.decor.find(l=>l.id===a):void 0;d&&this.showDecorContextMenu(e.clientX,e.clientY,d)}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 a=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!a,this.contextUngroupButton.title=a?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const d=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),l=this.selectedSourceIds.size===1&&d?.kind==="polygon";this.contextAddVertexButton.disabled=!l,this.contextAddVertexButton.title=l?"":this.messages.notAPolygon;const h=l&&this.contextMenuPoint?ee.hitTestVertex(d,this.contextMenuPoint):void 0,c=l&&d.points.length<=Pn;this.contextDeleteVertexButton.disabled=!l||h===void 0||c,this.contextDeleteVertexButton.title=l?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,a=this.messages;r.textContent=`${o} — ${n>=.995?a.masksBodyFully:n>.005?a.masksBodyPartly.replace("{share}",String(Math.round(n*100))):a.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=ee.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=ee.hitTestVertex(i,e);if(s===void 0)return;const n=ee.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(Ct,(e.maxX-e.minX)/2*t.width),s=Math.max(Ct,(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=Ot,a=Ot+to,d=t.width-Ot,l=t.height-r-Ot,h=Math.max(e.x,o),c=Math.max(e.y,a),u=Math.min(e.x+e.width,d),p=Math.min(e.y+e.height,l);return u-h<Ct||p-c<Ct?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=ee.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,a=(c,u)=>Math.max(.05,Math.abs(c)/Math.max(1,Math.abs(u))),d=o==="e"||o==="w",l=o==="n"||o==="s",h=d?a(i.x-s.x,n.x-s.x):l?a(i.y-s.y,n.y-s.y):a(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:l?r.widthM:r.widthM*h,lengthM:l?r.lengthM:r.lengthM*h,heightM:d?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:pi};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:oo};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=qi.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:nt.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,Dt)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=nt.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),o=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,a=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,o);return!n||!a?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:a,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&&ls(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&ls(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,a=s.map(({sourceId:d,original:l})=>({sourceId:d,shape:{...l,bounds:{...l.bounds,x:l.bounds.x+r,y:l.bounds.y+o}}}));this.commitShapes(i,a)}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=ee.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:o}])}else{const{kind:s,sourceId:n,original:r,handle:o}=this.dragState,a=s==="resize"?ee.resizeShape(r,o,t):ee.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:a}])}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)<ao)return;this.cameraDragState.moved=!0}const o=s+(t.x-i.x)*pi,a=Math.max(-90,Math.min(90,n-(t.y-i.y)*pi));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=a,this.sceneElement.setIndoorLook(o,a),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(a)),this.updateObserver(),this.rounded(o)!==this.rounded(s)&&(this.cameraDragState.headingTurned=!0),this.rounded(a)!==this.rounded(n)&&(this.cameraDragState.pitchTurned=!0),this.showOrientation(this.cameraDragState.headingTurned?o:void 0,this.cameraDragState.pitchTurned?a:void 0),this.showViewDragHint(e.altKey);const d=this.ufoElement.sighting.observerTrack,l=this.ufoElement.currentTime,h=d.allKeyframes.find(c=>c.t===l);h&&h.viewOnly===!0!==e.altKey&&(d.setViewOnly(l,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?mo: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)*po*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)*uo*t,o=i*Math.PI/180,a=tr(Math.sin(o)*r,-Math.cos(o)*r,s,n);this.latInput.value=a.lat.toFixed(7),this.lngInput.value=a.lng.toFixed(7);const d=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(d,this.plantingCentre()),this.surroundings.walked(a.lat,a.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=_s(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(a,d)=>Math.round((a-d)*1e3)/1e3,o=this.ufoElement.sighting;o.decor=o.decor.map(a=>({...a,eastM:r(a.eastM,s),northM:r(a.northM,n),...a.track?{track:a.track.map(d=>({...d,eastM:r(d.eastM,s),northM:r(d.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ss,i.width-Ne);break;case"ArrowRight":i.width+=Ne;break;case"ArrowUp":i.height=Math.max(ss,i.height-Ne);break;case"ArrowDown":i.height+=Ne;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Ne;break;case"ArrowRight":i.x+=Ne;break;case"ArrowUp":i.y-=Ne;break;case"ArrowDown":i.y+=Ne;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 ai(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 a=r?this.bodyCanvasBounds():void 0,d=a&&ee.hitTestHandle({bounds:a,angle:0},t);if(d)return this.cursorForHandle(d,0);const l=this.ndcOf(e),h=l&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(l.x,l.y):void 0;return r&&h?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const a=this.decorCanvasBounds(),d=a&&ee.hitTestHandle({bounds:a,angle:0},t);if(d)return this.cursorForHandle(d,0);const l=this.editableDecor();if(l&&!this.ufoElement.shapeAt(t.x,t.y,Dt)&&this.grabsDecor(e,t,l))return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const a=ee.hitTestHandle({bounds:new ai(this.selectedMembers()).bounds(),angle:0},t);if(a)return this.cursorForHandle(a,0)}else{const a=s.getInterpolatedShapeAt(n,this.currentSourceId);if(a?.kind==="polygon"&&ee.hitTestVertex(a,t)!==void 0)return"vertex";const d=a&&ee.hitTestHandle(a,t);if(a&&d)return this.cursorForHandle(d,a.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-${ee.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(Ns(this.buildPrototype({x:0,y:0,width:Je.width,height:Je.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 wo={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},Ms="rr0-sighting-editor";function Ks(){Us(),As(),qs(),Ir(),xr(),Lr(),Ps(),customElements.get(Ms)||customElements.define(Ms,w)}const ki="rr0-case-editor",yo=`
2777
+ `;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await T(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-DWvRMmj_.js");return{ModelThumbnails:i}},__vite__mapDeps([23,5,24,2,1,3,4,6,7,8,9,10,11]),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 d=++n,l=e.selectedOptions[0],h=e.value===""?i?.current():void 0,c=JSON.stringify([e.value,l?.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:l?.textContent??""} …`,s.title=this.messages().choose,s.append(u);const p=e.value;(h?Promise.resolve({url:h.url}):t(p)).then(m=>pt.pictureOf(m)).then(m=>{if(!m||d!==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 a=i&&{current:()=>i.current(),apply:d=>{i.apply(d),o()}};s.addEventListener("click",()=>void this.open(e,t,a)),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=pt.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 a=document.createElement("h2");a.textContent=n.title;const d=document.createElement("button");d.type="button",d.className="model-picker-close",d.setAttribute("aria-label",n.close),d.title=n.close,d.innerHTML=A.CLOSE;const l=document.createElement("header");l.append(a,d);const h=document.createElement("div");h.className="model-picker-body",o.append(l,h),r.append(o);const c=()=>{r.remove(),document.removeEventListener("keydown",u,!0),T(async()=>{const{ModelViewer:I}=await import("./ModelViewer-CM7qTW8F.js");return{ModelViewer:I}},__vite__mapDeps([25,5,24,2,1,3,4,6,7,8,9,10,11]),import.meta.url).then(({ModelViewer:I})=>I.end())},u=I=>{I.key==="Escape"&&(I.stopPropagation(),c())},p=i?.current(),m="\0address",f=I=>I===m&&p?Promise.resolve({url:p.url}):t(I),g=I=>{if(c(),s){I!==m&&s(I);return}I===m||I===e.value||(e.value=I,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const v=new Map,y=I=>{const C=document.createElement("button");C.type="button",C.className="model-card",C.dataset.value=I.value,C.setAttribute("aria-pressed",String(!s&&(I.value===m||I.value===e.value&&!p)));const R=document.createElement("div");R.className="model-thumb";const M=document.createElement("span");if(M.className="model-name",M.textContent=I.textContent,C.append(R,M),I.title){const x=document.createElement("span");x.className="model-credit",x.textContent=I.title,C.append(x)}f(I.value).then(x=>pt.pictureOf(x)).then(x=>{if(!x)return;const L=new Image;L.src=x,L.alt="",R.append(L)});let Z,Y=!1;const Re=()=>{Y&&!(Z&&!Z.active)||(Y=!0,Promise.all([f(I.value),T(()=>import("./ModelViewer-CM7qTW8F.js"),__vite__mapDeps([25,5,24,2,1,3,4,6,7,8,9,10,11]),import.meta.url)]).then(([x,{ModelViewer:L}])=>{!x||!Y||(Z=L.show(R,x))}).catch(()=>{}))},Ve=()=>{Y=!1,Z?.stop(),Z=void 0};return v.set(C,Re),C.addEventListener("pointerenter",Re),C.addEventListener("focus",Re),C.addEventListener("pointerleave",()=>{document.activeElement!==C&&Ve()}),C.addEventListener("blur",Ve),C.addEventListener("click",x=>{if(Z?.consumeDrag()){x.preventDefault();return}g(I.value)}),C},S=()=>(b=document.createElement("div"),b.className="model-picker-grid",h.append(b),b);if(p){const I=new Option(p.title||p.url,m);I.title=[p.author,p.license].filter(Boolean).join(" — "),S().append(y(I))}for(const I of Array.from(e.children))if(I instanceof HTMLOptGroupElement){const C=document.createElement("h3");C.textContent=I.label,h.append(C);const R=S();for(const M of Array.from(I.children))R.append(y(M));b=void 0}else I instanceof HTMLOptionElement&&(b??S()).append(y(I));i&&this.addAddressForm(l,d,o,h,i,n,c),d.addEventListener("click",c),r.addEventListener("click",I=>{I.target===r&&c()}),document.addEventListener("keydown",u,!0),this.root.append(r);const k=o.querySelector('.model-card[aria-pressed="true"]');(k??d).focus(),k&&v.get(k)?.()}addAddressForm(e,t,i,s,n,r,o){const a=document.createElement("button");a.type="button",a.className="model-picker-add",a.textContent="+",a.title=r.address,a.setAttribute("aria-label",r.address),a.setAttribute("aria-expanded","false"),e.insertBefore(a,t);const d=document.createElement("form");d.className="model-picker-address",d.hidden=!0;const l=(v,y,S="")=>{const k=document.createElement("label"),I=document.createElement("span");I.textContent=v;const C=document.createElement("input");return C.type=y,C.placeholder=S,k.append(I,C),d.append(k),C},h=l(r.addressUrl,"url","https://…/model.glb"),c=l(r.addressName,"text"),u=l(r.addressAuthor,"text"),p=l(r.addressLicense,"text","CC0 1.0"),m=l(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,d.append(f,g),i.insertBefore(d,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);a.addEventListener("click",()=>{const v=d.hidden;if(d.hidden=!v,a.setAttribute("aria-expanded",String(v)),!v)return;const y=n.current();h.value=y?.url??"",c.value=y?.title??"",u.value=y?.author??"",p.value=y?.license??"",m.value=y?.source??"",b(),h.focus()}),d.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 Mi{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=Mi.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 Jr{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 le{static STEP_MS=100;static plan(e){const t=le.routeOf(e),i=Le.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const o=new Set,a=(c,u,p,m)=>{if(Math.abs(c.radiusM-m)>=m*.1)return!1;const{x:f,z:g}=_s(u,p,c.lat,c.lng);return Math.hypot(f,g)<Le.rebuildDistanceFor(m)};for(let c=0;;c=Math.min(s,c+le.STEP_MS)){const u=ie(e,c);if(u?.lat!==void 0&&u.lng!==void 0){const p=Le.groundRadiusFor(u.elevationM??0),m=Le.patchRadiusFor(p,u.elevationM??0),f=Math.max(m,i);(!r||!a(r,u.lat,u.lng,f))&&(r=n.find(g=>a(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 d=e.weatherTrack.allKeyframes.map(c=>c.weather.visibilityKm).filter(c=>c!==void 0),l=Le.farRingRadiusFor(d.length>0?Math.max(...d):void 0);for(const c of o)n.push({lat:c.lat,lng:c.lng,radiusM:l,far:!0});if(l>Le.FAR_RING_RADIUS_M)for(const c of[...n])!c.far&&!o.has(c)&&c.radiusM<l&&n.push({lat:c.lat,lng:c.lng,radiusM:l,far:!0});const h=Os.map(c=>Bt.of(c)).filter(c=>c.reachM&&Bt.eventsOf(e.skyEvents,c).length>0);if(h.length>0){const c=u=>Math.max(...h.map(p=>p.reachM(Bt.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)||Le.needsFarRing(u.radiusM,0,c(u))&&n.push({lat:u.lat,lng:u.lng,radiusM:l,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=a=>n?.(a,i.length);switch(e){case"relief":{const a=le.routeOf(t),d=[];for(const[c,u]of i.entries()){try{const p=await s.elevation.getElevationGrid(ct.boundsOf(u),{width:Ui,height:Ui},{route:a});d.push({...u,grid:p})}catch(p){console.warn("Relief not snapshots for a patch:",p)}o(c+1)}if(d.length===0)return;const l=s.elevationCredit;return{bytes:await bn.encode({takenOn:r,attribution:l,patches:d}),attribution:l,takenOn:r,answered:d.length,patches:i.length}}case"imagery":{const a=new Fi,d=_(ht,s.imagery),l=d.create(a.fetch);let h=0;for(const[p,m]of i.entries()){try{await l.getImageryTexture(ct.boundsOf(m),{width:zi,height:zi}),h++}catch(f){console.warn("Imagery not snapshots for a patch:",f)}o(p+1)}if(a.tiles.size===0)return;const c=l.attribution;return{bytes:await _i.encode({takenOn:r,source:d.id,attribution:c,patches:[...i],tiles:a.tiles}),attribution:c,takenOn:r,answered:h,patches:i.length}}case"roads":return le.vector(s.roads,i,r,o,(a,d)=>a.getRoads(d),a=>a.contemporary);case"water":return le.vector(s.water,i,r,o,(a,d)=>a.getWater(d));case"railways":return le.vector(s.railways,i,r,o,(a,d)=>a.getRailways(d),a=>a.contemporary)}}static mapGround(e){const t=vn.of(e);return t&&$i.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=le.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Fi,r=_(ht,t),o=r.create(n.fetch),a=$i.IMAGERY_PX;try{await o.getImageryTexture(i,{width:a,height:a})}catch(h){console.warn("Map imagery not snapshots:",h);return}const d=o.attribution;return{bytes:await _i.encode({takenOn:s,source:r.id,attribution:d,patches:[],map:{bounds:i,pixels:a},tiles:n.tiles}),attribution:d,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const o=[];for(const[l,h]of t.entries()){if(h.radiusM<=Le.ROADS_MAX_RADIUS_M)try{o.push({...h,items:await n(e,ct.boundsOf(h))})}catch(c){console.warn("Not snapshots for a patch:",c)}s(l+1)}if(o.length===0)return;const a={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:o};return{bytes:new TextEncoder().encode(JSON.stringify(a)),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 te.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 te.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 T(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-DS1DRU2p.js");return{SightingFileEditor:r}},__vite__mapDeps([26,27,28]),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{z.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){z.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}he.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}z.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await T(async()=>{const{InputFileElement:s}=await import("./rr0-ufoathome.mjs").then(n=>n.a0);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{z.show(this.note,this.messages.annexUnreadable,"warning");return}const o=n!==void 0&&j.isInline(n.src),a=o?j.dataUrl(e,t):n?.src??te.annexName(this.host.base(),e);o||he.hold(this.address(a),t),s[e]={...s[e]?.live?{live:!0}:{},src:a,...r},z.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${a}`),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=te.annexName(this.host.base(),e),he.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)?te.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 T(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 he.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,le.plan(this.host.sighting()),this.host.sources(),s))?z.show(this.note,void 0):z.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 te.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||le.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=>te.isLive(i,h),r=h=>i[h]?.src!==void 0?i[h]:void 0;for(const h of te.NAMES)!i.live&&i[h]?.live&&(i[h]={live:!0});const o=le.plan(t);let a;for(const h of te.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,a??=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");le.mapGround(t)!==void 0&&(!h||h.refresh||!await this.fitsMap(h))&&await this.takeMap(i,a??=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 d=this.host.upperAirHeard(),l=r("upperAir");if(!n("upperAir")&&d&&(!l||l.refresh)){const h=new Date().toISOString().slice(0,10),c={version:1,takenOn:h,attribution:d.answer.source.name,answers:[d]},u=new TextEncoder().encode(JSON.stringify(c)),p=this.place("upperAir",l?.src,e,u);i.upperAir={src:p,takenOn:h,attribution:d.answer.source.name},j.isInline(p)||s.set(p,u)}else l&&!n("upperAir")&&(l.refresh&&(i.upperAir={...l,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 le.freeze(e,this.host.sighting(),i,s,(a,d)=>z.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(a)).replaceAll("{of}",String(d))));return z.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){z.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await le.freezeMap(this.host.sighting(),t.imagery);return z.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=le.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await he.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&ct.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 he.zip(s))["index.json"])).patches:(await he.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(o=>o.radiusM<=Le.ROADS_MAX_RADIUS_M);return ct.samePatches(n.map(({lat:o,lng:a,radiusM:d})=>({lat:o,lng:a,radiusM:d})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&j.isInline(t))return j.dataUrl(e,s);const n=t??te.annexName(i,e);return he.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{z.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return he.bytes(this.address(e.src))}address(e){return he.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of te.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=te.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 Yt{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,z.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 gt(Oe.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=vi(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:Ge.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(a=>{if(!a.ok)throw new Error(String(a.status))})}catch{const a={...this.host.sighting().snapshots??{}};a[e]={...a[e]??{},src:t.url},z.show(this.note,void 0),this.write(e,a);return}let i;try{const{InputFileElement:a}=await T(async()=>{const{InputFileElement:l}=await import("./rr0-ufoathome.mjs").then(h=>h.a0);return{InputFileElement:l}},[],import.meta.url),d=await a.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=Ge.recording(JSON.parse(new TextDecoder().decode(d))),typeof i!="object"||i===null||$.KEYS[e].every(l=>i[l]===void 0))throw new Error("Not this section")}catch{z.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...vi(s)};if(e==="decor")$.put(e,n,"timeline"in i?$.taken(e,i):i);else for(const a of $.KEYS[e])n[a]=i[a];const r=Rs(n);Yt.copy(e,r,s);const o={...s.snapshots??{}};t.url?o[e]={...o[e]??{},src:t.url}:o[e]=o[e]??{},z.show(this.note,void 0),this.write(e,o)}write(e,t){this.host.sighting().snapshots=te.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 Xr{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 Qr=ce.point("timeZone").provide(ce.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new Xr}]);class ui{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 V{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=V.select("observerOccupationKind");graduate=V.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=V.select("observersRelation");activity=V.select("observerActivity");factors=new Map(sr.map(e=>[e,V.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){ye.register(),e.append(this.label(this.occupationKind,l=>[l.occupationKind,l.occupationKindHint]),this.label(this.graduate,l=>[l.graduate]));const n=this.label(this.enquiryMinutes,l=>[l.enquiryMinutes,l.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,l=>[l.relation]),this.label(this.activity,l=>[l.activity]));const o=Object.assign(document.createElement("h3"),{className:"section-title"});o.append(this.strangenessTitle),i.append(o,this.strangenessIntro,...[...this.factors].map(([l,h])=>this.label(h,c=>[c.factors[l],c.factorHints[l]])));const a=[["yes","yes"],["no","no"]],d=l=>l.map(h=>[h,h]);V.choices(this.occupationKind,"",d(Object.keys(ui.OCCUPATIONS))),V.choices(this.graduate,"",a),V.choices(this.relation,"",d(ui.RELATIONS)),V.choices(this.activity,"",d(ui.ACTIVITIES));for(const l of this.factors.values())V.choices(l,"",a);for(const l of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])l.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,V.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),V.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),V.choices(this.relation,e.unknown,Object.entries(e.relations)),V.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)V.choices(i,V.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=V.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=V.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=V.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:V.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);ye.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 Dt=new Set;Ps();Bn();Bs.register();const Je={width:48,height:28},eo=2500,Ct=40,Ot=10,to=30,io=10,Ss=600,Is=900,Xe=2e-4,so=900,no=-1.46,ro=3,pi=.2,oo=.5,ao=3,lo=.01,ho=1.6,mi=2e3,co=250,Ts=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),uo=1,po=5,mo=10,Ne=4,ot="ufo-1",go={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function fo(E){return E.kind==="oval"?"oval":"polygon"}const bo=-6,vo=21;class w extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=Qr[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new Jr;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;exportKmlButton;exportGeoJsonButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;saidInterviews;candidatesView;sectionFolds;sectionIndexResize;snapshotsPanel;sectionFilePanel;eventsPanel;aroundPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;aircraftStatus=Object.assign(document.createElement("span"),{className:"source-status"});aircraftFlights;aircraftFlightsShownAt=0;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=Yr();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 rt(qr());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 w.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?wn.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 a=this.numberBounds.get(r),d=Number(r.value);if(!a||r.value===""||!Number.isFinite(d))return;const l=Math.min(Math.max(d,a[0]),a[1]);l!==d&&(r.value=String(l))};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 ei;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=Ke.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...go};currentSourceId=ot;selectedSourceIds=new Set([ot]);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(Ts.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;Ts.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>${vr}</style>${br}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const l of this.shadow.querySelectorAll(Ht))l.build();for(const l of this.shadow.querySelectorAll(qt))l.build();for(const l of this.shadow.querySelectorAll(Ai))l.build();for(const l of this.shadow.querySelectorAll(Di))l.build();this.sceneElement=document.createElement(yn),this.sceneElement.addEventListener("observermapchange",l=>{this.ufoElement.sighting.observerMap=l.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",l=>{const{lat:h,lng:c}=l.detail;this.latInput.value=String(Number(h.toFixed(6))),this.lngInput.value=String(Number(c.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 ut(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const l of[this.timeStartLabel,this.timeEndLabel])l.addEventListener("click",()=>this.switchTimeDisplay()),l.addEventListener("keydown",h=>{h.key!=="Enter"&&h.key!==" "||(h.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(qt),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 O(this.shadow);const t=this.shadow.getElementById("section-index");this.sectionFolds.indexIn(t,()=>this.groupPanels?.find(l=>!l.hidden)),this.sectionIndexResize=new je(this.shadow.getElementById("section-index-resize"),this.shadow.querySelector(".app"),()=>t,"rr0-section-index-width","--rr0-section-index-width",44);const i=this;this.witnessErrorView=new Hs({get sighting(){return i.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:l=>{const h=this.ufoElement.sighting,{conditions:c,...u}=h.account??{},p={...u,...l?{conditions:l}:{}};h.account=Object.values(p).some(m=>m!==void 0)?p:void 0},recordingJson:()=>this.sightingData,valueSources:()=>this.valueSources(),lawsChanged:()=>{this.sceneElement.confrontationTolerance=En.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new Si(this.shadow.getElementById("timeline-tracks"),l=>this.goToMark(l),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",l=>{l.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new Ws(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",l=>{const h=l.target.id;w.SCENE_LINKED.includes(h)&&this.setActiveSceneField(h)}),this.shadow.addEventListener("focusout",l=>{const h=l.relatedTarget;(!h||!w.SCENE_LINKED.includes(h.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.filmStockSelect=this.shadow.getElementById("filmStock"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),this.skySourcesInput=this.shadow.getElementById("sky-sources"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.evaluationFields=new V(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(`${Di}[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(w.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:(l,h)=>this.download(l,h)}),this.sectionFilePanel=new Yt(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(l,h)=>this.download(l,h),changed:l=>{if(this.touch(),this.ufoElement.refresh(),l==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),l==="place"&&this.syncPlaceNameField(),l==="lightPollution"){const h=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=h===void 0?"":String(h),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const s={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:l=>this.goToMark(l),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const l=this.ufoElement.sighting.timeline;return l.sourceIds.includes(this.currentSourceId)?l.topOf(this.currentSourceId):void 0},shapesLabel:l=>this.shapesLabel(l),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:l=>this.naming.point(l),lookedAt:()=>{const l=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return l?.headingDeg===void 0||l.pitchDeg===void 0?void 0:{azimuthDeg:l.headingDeg,altitudeDeg:l.pitchDeg}},bodyLabel:l=>{const h=this.ufoElement.sighting.interpretation?.bodies.find(c=>c.id===l);return this.said.read(h?.title)??l},valueSources:()=>this.valueSources()};this.eventsPanel=new Ie(this.shadow.getElementById("events-section"),s,void 0),this.phenomenonEventsPanel=new Ie(this.shadow.getElementById("phenomenon-events-section"),s,void 0,"phenomenon"),this.bodiesEventsPanel=new Ie(this.shadow.getElementById("bodies-events-section"),s,void 0,"bodies"),this.aroundPanel=new ur(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 l=Number(this.samplingRateInput.value);s.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(l)&&l>0?l:void 0,pe.refresh(this.ufoElement.sighting),s.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.snapshotsPanel.localize(this.messages),this.sectionFilePanel.localize(this.messages),this.refreshFileItems(),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",l=>{l.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 wr(this.shadow.getElementById("aircraft-flights"),l=>this.aimAtFlight(l),l=>this.naming.point(l)),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 be({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:l=>`option-decor-${l}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:l=>this.selectDecor(l),onAdd:l=>this.addDecor(l),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 be({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:l=>this.selectObserver(l),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 se(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:l=>this.setPlantedDecor(l),kindName:l=>this.decorList.kindLabel(l),cite:l=>this.citeSource(l),busy:(l,h)=>this.sceneElement.setBusy(l,h),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(l=>({lat:l.pose.lat,lng:l.pose.lng})).filter(l=>typeof l.lat=="number"&&typeof l.lng=="number")},this.messages,async(l,h)=>this.surroundingsProvider?this.surroundingsProvider.covers(l,h)?this.surroundingsProvider:void 0:(await T(async()=>{const{SurroundingsSources:c}=await import("./surroundingsSources-UHKGesPa.js");return{SurroundingsSources:c}},__vite__mapDeps([29,1,2,3,4,5,6,7,8,9,10,11]),import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,l,h),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const l=this.scenerySource.value===w.FILE_SOURCE;if(this.setDecorFromFile(l),l){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===w.NO_SCENERY){this.surroundings.withdraw();return}const h=this.plantingCentre();h&&this.surroundings.survey(h.lat,h.lng)}),this.sceneryRadius.addEventListener("input",()=>{const l=Number(this.sceneryRadius.value);if(!Number.isFinite(l)||l<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const h=this.plantingCentre();this.surroundings.radiusChanged(l,h?.lat,h?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSourceInput=this.shadow.getElementById("reference-source"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceVideoFromInput=this.shadow.getElementById("referenceVideoFrom"),this.referenceVideoToInput=this.shadow.getElementById("referenceVideoTo"),this.referenceVideoRateInput=this.shadow.getElementById("referenceVideoRate"),this.referenceRemoveKeyButton=this.shadow.getElementById("reference-remove-key"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new fi(this.addReferenceButton,"reference-add-kind",l=>this.addReferenceOfKind(l),l=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[l]??`reference-add-${l}`),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 pt(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 lt(this.decorParametersHost,"en","decorParam.");const n={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new lt(this.decorBaseHost,"en","decorBase.",n,(l,h)=>this.enhanceDecorModelChoice(l,h)),this.decorStateForm=new lt(this.decorStateHost,"en","decorState.",n),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",l=>{this.focus({preventScroll:!0}),this.onPointerDown(l)}),this.ufoElement.canvasElement.addEventListener("pointermove",l=>this.onPointerMove(l));let r;this.ufoElement.canvasElement.addEventListener("pointerdown",l=>{r={x:l.clientX,y:l.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",l=>{const h=r;r=void 0,!(!h?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(l.clientX-h.x,l.clientY-h.y)>w.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",l=>this.onContextMenu(l)),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 o=this.shadow.getElementById("editor-mute"),a=this.shadow.getElementById("editor-volume");o.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.toggleMuted()}),a.addEventListener("input",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.volume=Number(a.value)}),this.ufoElement.addEventListener("mutedchange",()=>this.syncSoundControls()),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.exportKmlButton.addEventListener("click",()=>void this.exportFigures("kml")),this.exportGeoJsonButton.addEventListener("click",()=>void this.exportFigures("geojson")),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",l=>{const h=l.detail;h.file?this.importFromFile(h.file):this.importFromUrl(h.url)}),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()});for(const l of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])l.addEventListener(l instanceof HTMLSelectElement||l.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 l=this.ufoElement.sighting;l.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),l.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),l.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",l=>{const{seconds:h,text:c}=l.detail;this.ufoElement.sighting.event.durationText=c,this.ufoElement.durationSeconds=h,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((h??0)*1e3),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const l of this.referenceFields)l.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",l=>void this.setReferenceSource(l.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 l=this.shadow.getElementById("trace-import-row");l.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",l=>void this.addTraces(l.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",l=>this.onReferenceWheel(l),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",l=>this.onBodyWheel(l),{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 l of[this.milestoneLabelInput,this.milestoneNoteInput])l.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(kn,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(xn,()=>{const l=this.currentReference();l&&this.syncReferenceStatus(l)}),this.sceneElement.addEventListener(Sn,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(In,()=>{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 fi(this.addShapeButton,"add-shape-kind",l=>{const h=Ae.byId(l);if(h){this.addModel(h);return}this.currentAppearance={...this.currentAppearance,presetId:l},this.addShape()},l=>`add-shape-${l}`),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 l of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])l.addEventListener("input",()=>this.updateObserver());for(const l of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])l.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",l=>{if(this.observerSaid=l.detail.said,!this.observerPosition.relative)return;const h=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(h,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",l=>this.writeObserverBasis(l.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",l=>{l.key==="Enter"&&(l.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 l=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const h=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(c=>[c.t,Pe.fovOf(this.ufoElement.sighting,c.t)]));this.retuneFieldOfView(l),this.retuneExposure(l),Pe.reproject(this.ufoElement.sighting,l,h),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.accountCompareInput.addEventListener("change",()=>this.syncBodiesShown()),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const d=l=>this.shadow.querySelector(`${Ht}[name="${l}"]`);this.startDate=d("obs-time"),this.endDate=d("obs-end-time"),this.birthDate=d("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=wt.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const l of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(l,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",l=>{const{time:h}=l.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=h}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",l=>{this.birth=l.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",l=>{const{time:h}=l.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=h})});for(const l of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])l.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(w.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const l of this.weatherFields){if(l===this.iceCrystalAlignmentInput||l===this.rareIceCrystalsInput){l.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}l.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const l of this.soundFields)l.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(l=>this.shadow.getElementById(l.getAttribute("aria-controls")));for(const l of this.groupTabs)l.addEventListener("click",()=>this.toggleGroup(l,!this.isGroupOpen(l)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const l of this.subgroupTabs)l.addEventListener("click",()=>this.openSubgroup(l)),w.pictureTab(l);this.buildSkyParts(),Ut.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",l=>this.onParamSummaryClick(l)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(l=>l.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=dr(this.shadow.getElementById("cloud-editor"),this.sceneElement,(l=!0)=>{l&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(l,h)=>{this.headingInput.value=String(this.rounded(l)),this.pitchInput.value=String(this.rounded(h)),this.updateObserver()},Ft(Oe.preferencesFor(this),mt),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),Oe.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),ce.changes.addEventListener("change",this.onModulesChanged),T(async()=>{const{ModuleSession:t}=await import("./ModuleSession-BKDWGSEo.js");return{ModuleSession:t}},__vite__mapDeps([30,1,10,7]),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=wt.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),ce.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=Ge.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]??ot,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:()=>`${wi.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(z.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 T(async()=>{const{zipSync:l,strToU8:h}=await import("./browser-CltifEM0.js");return{zipSync:l,strToU8:h}},[],import.meta.url),a={[s]:o(n)};for(const[l,h]of t)a[l]=h;const d=r(a,{level:0});this.download(new Blob([d],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.snapshotExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",j.size(d.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)),...te.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,w.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=te.NAMES.includes(e),i=$.NAMES.includes(e)?e:void 0,s=e===w.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||be.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)?Yt.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 ei)||ce.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),a=o===void 0?void 0:ce.installed().find(d=>d.id===o)?.url;!a||xs.names(n,a,s)||(n=[...n??[],xs.of(a,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??=T(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-DsOa2zH0.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([31,1,30,10,7,6,13,14,2,3,4,5,8,9,11,15,16,17,18,19,20]),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=_(yt,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:_(ht,this.chosenSourceId.get("imagery")).id,roads:Ln(),water:Mn(),railways:Tn()}}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)}));he.release();const i=await this.recordingText(t),s=JSON.parse(i);if(ne.isCase(s)){if(ne.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 T(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)&&he.hold(he.address(h.slice(o.length),void 0),c);const a=i(s[r]),d=JSON.parse(a);let l=!1;for(const h of $.NAMES){const c=d.snapshots?.[h]?.src,u=c!==void 0?s[o+c]:void 0;if(!u)continue;const p=Ge.recording(JSON.parse(i(u)));$.put(h,d,p),l=!0}return l?JSON.stringify(d):a}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 et.recording(e);if(ne.isCase(t)){ne.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;he.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(){z.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof zt)return e.said(this.messages.formatVersionError);if(!(e instanceof Zs))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=St[0].create();get narrativeSourceId(){return _(St,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:w.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof ue&&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=Se.stated(r);if(o.length>0){const a=this.ufoElement.sighting.provenance,d=Hi(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=Se.apply(d,Kt.loadable(r),o)}finally{this.patchingDraft=!1}this.ufoElement.sighting.provenance=a,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:w.valueAt(Hi(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[wo[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=_(St,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 a of i.choices??[]){const d=document.createElement("option");d.value=a.value,d.textContent=this.said.read(a.label)??a.value,r.appendChild(d)}}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 ue))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(){w.pageCredentials.clear(),ti.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!==""?w.pageCredentials.set(t,i):w.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(w.NARRATIVE_KEY_STORAGE),localStorage.removeItem(w.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 w.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} `),w.creditLink(_(ci,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",ir,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(_(Tt,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",St,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",ci,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",Tt,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",yt,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",ht,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[w.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[w.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[w.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",Wi,()=>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,w.FILE_SOURCE))};o();const a=()=>{const f=this.chosenSourceId.get(e);return f!==void 0&&t.some(g=>g.id===f)?f:t[0].id};r.value=s?.fromFile()?w.FILE_SOURCE:a();const d=document.createElement("a");d.className="source-credit",d.target="_blank",d.rel="noopener noreferrer";const l=document.createElement("button");l.type="button",l.className="link source-file-link",l.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=_(t,r.value);ti.set(f.id,c.value),i(f,!0)});const p=()=>{const f=r.value===w.FILE_SOURCE,g=_(t,f?a():r.value);h.hidden=f||!g.keyUrl,u.href=g.keyUrl??"",c.value=ti.of(g.id)??"",r.title=f?s.where():g.credit,d.hidden=f,d.href=g.creditUrl,d.textContent=g.credit,l.hidden=!f,f&&(l.textContent=s.label(),l.title=s.where())};p(),r.addEventListener("change",()=>{const f=r.value===w.FILE_SOURCE;f||this.chosenSourceId.set(e,r.value),s?.setFromFile(f),p(),f||i(_(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?w.FILE_SOURCE:a(),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===w.FILE_SOURCE&&s?f:a(),p(),g&&r.value!==w.FILE_SOURCE&&i(_(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),d,l,h),n}aircraftPicker(){const e=this.sourcePicker("aircraft",ji,(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?z.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):z.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=te.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=w.LIVE_ROADS;static LIVE_RAILWAYS=w.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 a=s.map(([l,h,c])=>{o.append(new Option(h,l));const u=document.createElement("span");return u.className="source-picker",u.dataset.kind=l,u.append(c),u});o.value=this.sourceKindShown.get(i)??s[0][0];const d=()=>{this.sourceKindShown.set(i,o.value);for(const l of a)l.hidden=l.dataset.kind!==o.value};o.addEventListener("change",d),d(),n.append(r,document.createTextNode(" "),o),e.replaceChildren(n,...a)}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} `),w.creditLink(_(ci,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(_(Tt,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:_(yt,this.chosenSourceId.get("elevation")).create(),imagery:_(ht,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(_(ji,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new ei(_(Wi,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)<Xe&&Math.abs(i-this.namedCoordinates.lng)<Xe||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),Is))}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)<Xe&&Math.abs(i-s.lng)<Xe||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),Is))}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,a=this.ufoElement.sighting.observerTrack,d=this.ufoElement.currentTime,l=a.getInterpolatedPoseAt(d),h=l?.altitudeM!==void 0?r:void 0,c=h!==void 0?l.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?ke.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),f=this.numberOrUndefined(this.fNumberInput.value),g=this.filterSelect.value,b=de.byId(a.getLatestPoseAt(d-1)?.filter),v=g===de.NONE.id||g===""?b===de.NONE?void 0:de.NONE.id:g,y=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=y===u.exposureSeconds?void 0:y;const S=this.numberOrUndefined(this.focusDistanceInput.value),k=Math.abs(m-ke.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&&!k?a.removeKeyframeAt(d):a.addKeyframe(d,{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()),R=a.getInterpolatedPoseAt(0);o.place=e!==void 0&&t!==void 0?[{lat:R?.lat??e,lng:R?.lng??t,name:C}]:void 0;const M=this.plantingCentre();this.surroundings.placeChanged(M?.lat,M?.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&&!It.isFirm(t))return;const s=It.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&&It.at(i,e)===t)return;const s=It.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&&$t({...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:wt.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},a=Object.keys(o).length>0?[o,...s]:s;e.sources=a.length>0?a: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={...oe(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={...oe(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;be.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"||Be.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=Be.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=Be.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(z.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>Rr?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)||Mt))},a=this.registrationShown(n),d=o.headingDeg!==a.headingDeg||o.pitchDeg!==a.pitchDeg||o.rollDeg!==a.rollDeg||o.fovDeg!==a.fovDeg,l=this.referenceKindSelect.value;return l==="video"?{...d?Be.withKey(n,this.ufoElement.currentTime,o):n,kind:l,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:l,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:d?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=ie(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(Be.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=ie(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=ie(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:Or,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:Mt},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,a)=>{const d=new FileReader;d.onload=()=>o(d.result),d.onerror=()=>a(d.error),d.readAsDataURL(r)})}else i=e.url;const s=this.ufoElement.sighting,n=Be.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??=T(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-BJeiCK8A.js");return{PictureRegistration:e}},__vite__mapDeps([32,5]),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:Be.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 a=this.pictureRegistration.picturePointOf(r,s.registration,n);return a?{...o,picture:a}: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)||Mt,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 a=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,n)+a,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);be.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,a)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(o.scene)),label:this.landmarkLabel(o,a),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)),a=[];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||a.push({ghost:c,light:u,ghostRadius:p?Math.hypot(p.x-c.x,p.y-c.y):0})}const d=n.centre?o(n.centre):void 0,l=n.cropped?o({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(a,d,l)}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(Be.rollOfPicture(s)??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(d=>d.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)),a=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[d,l]of a)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${d}`,{basis:"derived",rationale:o,of:this.rounded(l)})}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=ie(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 T(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 a=document.createElement("option");a.value=String(r),a.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(a)}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:Mt}})}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;be.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:l}=await T(async()=>{const{TraceImport:h}=await import("./TraceImport-CntRHXoJ.js");return{TraceImport:h}},__vite__mapDeps([33,1]),import.meta.url);i=await l.fromBytes(await Ys.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(l=>l.id));let r=1;const o=this.said.write(void 0,i.documentName??t,this.writingLanguage),a=i.traces.map(l=>{for(;n.has(`trace-${r}`);)r++;const h=`trace-${r}`;return n.add(h),{...l,id:h,title:l.title===void 0?void 0:this.said.write(void 0,l.title,this.writingLanguage),source:o}});s.traces=[...s.traces,...a],this.currentTraceId=a[0].id,this.refreshTraceList();const d=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(a.length)).replace("{name}",t)+d,this.ufoElement.refresh()}async exportFigures(e){const t=this.fileBase(),{GEO_EXPORT_TEXTS:i}=await T(async()=>{const{GEO_EXPORT_TEXTS:o}=await import("./GeoExportTexts-3a51cuxQ.js");return{GEO_EXPORT_TEXTS:o}},__vite__mapDeps([34,1]),import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:o}=await T(async()=>{const{KmlExport:d}=await import("./KmlExport-BMNwwys8.js");return{KmlExport:d}},__vite__mapDeps([35,36,3,4,1,6,7,2,5,8,9,10,11]),import.meta.url),a=o.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([a],{type:"application/vnd.google-earth.kml+xml"}),`${t}.kml`);return}const{GeoJsonExport:n}=await T(async()=>{const{GeoJsonExport:o}=await import("./GeoJsonExport-Pq_pPvjK.js");return{GeoJsonExport:o}},__vite__mapDeps([37,36,3,4,1,6,7,2,5,8,9,10,11]),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 Wn){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(),eo)}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=jn(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 rt(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===w.FILE_SOURCE;if(!e){const t=_(xe,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new rt(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=te.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=xe.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==_(xe,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new rt(e.create())}else!e&&t!==void 0&&!xe.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new rt(_(xe,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...xe.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,w.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!At(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?w.FILE_SOURCE:i?i.id:_(xe,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=_(xe,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&&!At(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),Ss))}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||!At(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&&At(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&&ve(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=Tt[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(),Ss)}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=$t(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=Gn(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?ii.MUTED:ii.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(),A.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(dt.opensPrecise(e.time)),this.endDate.setPrecise(dt.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)>ro;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),so))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Xe&&Math.abs(e.lng-i)<Xe}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=_(yt,this.chosenSourceId.get("elevation")),n=await new Mi(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=ie(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(w.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(dt.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=oe(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??yi)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??Kn)),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=rs(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!==w.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 T(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-DS1DRU2p.js");return{SightingFileEditor:t}},__vite__mapDeps([26,27,28]),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"){z.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 cs.of(e,t,t==="thin"?Pe.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(w.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(w.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Rs(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=cs.of(this.ownJson(vi(e)),t,t==="thin"?Pe.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(w.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 a=this.ufoElement.sighting.weatherSource;a===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):xe.some(d=>d.id===a.id)&&this.askAboutWeather(o,a.name??a.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(a){this.showFileNote(a instanceof zt?a.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,a=[];for(let d=0;d<360;d+=w.COMPASS_STEP_DEG){const l=this.sceneElement.horizonPointAt(d);l&&s(l)&&a.push({...l,label:this.naming.point(d)})}n={label:this.messages.overlayHeading.replaceAll("{deg}",i(o)).replaceAll("{point}",this.naming.point(o)),compass:a}}let r;if(t!==void 0){const o=[[]];for(let a=0;a<=360;a+=w.HORIZON_STEP_DEG){const d=this.sceneElement.horizonPointAt(a);d&&Math.abs(d.x-.5)<1.5&&Math.abs(d.y-.5)<1.5?o[o.length-1].push(d):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=d=>this.numberOrUndefined(d.value),a=(d,l=1)=>d===void 0?"?":d.toLocaleString(this.language,{maximumFractionDigits:l});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 d=Pe.fovOf(i,s),h=2*si.of(i.instrument,n.height,d).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",a(d)).replaceAll("{h}",a(h)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const d=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!d){e.hide();return}const l=d.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])=>`${a(u,m)}${p}`).join(" · ");e.measure((l.x+l.width/2)/n.width,(l.y+l.height/2)/n.height,Math.max(l.width,l.height)*1.3/n.width,c)}else if(t==="windDirection"||t==="windSpeed"){const d=o(this.windDirectionInput)??0,l=d-(o(this.headingInput)??0);e.wind(l,r.overlayWind.replaceAll("{point}",this.naming.point(d)).replaceAll("{speed}",a(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=d=>{let l=-1;return d.forEach((h,c)=>{h<=i()&&(l=c)}),l===-1&&d.length>0?0:l};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const d=n(t().observerTrack.allKeyframes.map(l=>l.t));return d===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${d}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const d=t().timeline.allKeyframes,l=n(d.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId)).map(p=>p.t));if(l===-1||this.apparentWidthInput.value==="")return;const h=d.filter(p=>p.shapes.some(m=>m.sourceId===this.currentSourceId))[l],c=d.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",o.dataset.icon="candidates",this.shadow.getElementById("group-observation").append(o);const a=d=>d?.closest("label")??void 0;this.candidatesView=new re({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const d=this.ufoElement.sighting.event,l=d.place?.[0];if(!l||d.time?.year===void 0||d.time.hour===void 0)return;const h=ve(d.time,l.lng,d.utcOffsetHours);return h?{date:h,observer:{lat:l.lat,lng:l.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:d=>Ze(d,this.instrumentGain()),fieldLabels:()=>({time:a(s),heading:a(this.headingInput),size:a(this.apparentWidthInput),duration:a(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:d=>{const l=`${d}/${this.language}`;return this.poherMatrix?.key!==l&&(this.poherMatrix={key:l,loaded:Ue.load(d,this.language,h=>et.json(h))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const d=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,l=this.sceneElement.satellitePassesDuring(d);return l.length>0?{passes:l,positionsAt:h=>this.sceneElement.satellitePositionsAt(h)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const d=this.ufoElement.sighting.interpretation;return[...d&&(d.bodies.length>0||Rt.computes(d,Pt.kinds()))?[{id:"own",label:this.said.read(d.title)??this.principalObserverLabel(),interpretation:d}]:[],...this.readings]},computed:d=>this.sceneElement.computedInterpretation(d),starName:d=>this.naming.star({name:d}),projectionAt:(d,l)=>this.sceneElement.bodyProjectionAt(d,l),variants:()=>this.ufoElement.sighting.variants,keep:d=>this.editVariants(l=>[...l,d]),remove:d=>this.editVariants(l=>l.filter((h,c)=>c!==d))},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 l=ve(i.time,s.lng,i.utcOffsetHours);l&&(t.sunAltitudeDeg=G("Sun",l,{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 l=oe(e,0);t.cloudCover=l.cloudCover,t.lightning=l.storm,t.lowVisibility=l.precipitationType!=="none"&&l.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const l=n.allKeyframes.filter(u=>u.shapes.some(p=>p.sourceId===r)),h=l.map(u=>({t:u.t,shape:n.getShapeAt(u.t,r)})).filter(u=>u.shape?.aim),c=n.getInterpolatedShapeAt(l[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,y=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,y)))/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(l=>n.groupMembers(l)?.[0]??l));o.size>0&&(t.count=o.size);const a=[...o].map(l=>n.getInterpolatedShapeAt(0,l)?.aim).filter(l=>l!==void 0);if(a.length>=3){const l=Math.PI/180,h=a.map(m=>({x:(((m.azimuthDeg-a[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*l),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 d=new Set([...o].map(l=>n.getInterpolatedShapeAt(0,l)?.color).filter(l=>l!==void 0));return d.size>0&&(t.colors=[...d]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(l=>l.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=()=>getComputedStyle(t).display==="grid",n=()=>s()?"--rr0-scene-wide-height":"--rr0-scene-max-height",r=()=>s()?`${w.SCENE_HEIGHT_KEY}-wide`:w.SCENE_HEIGHT_KEY,o=a=>{const[d,l]=[n(),r()];a===void 0?t.style.removeProperty(d):t.style.setProperty(d,`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,a)))}px`);try{a===void 0?localStorage.removeItem(l):localStorage.setItem(l,t.style.getPropertyValue(d))}catch{}};try{for(const[a,d]of[["--rr0-scene-max-height",w.SCENE_HEIGHT_KEY],["--rr0-scene-wide-height",`${w.SCENE_HEIGHT_KEY}-wide`]]){const l=localStorage.getItem(d);l&&/^\d+px$/.test(l)&&t.style.setProperty(a,l)}}catch{}e.addEventListener("pointerdown",a=>{a.preventDefault();const d=a.clientY,l=i.getBoundingClientRect().height;e.setPointerCapture?.(a.pointerId),e.classList.add("dragging");const h=u=>o(l+u.clientY-d),c=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",h),e.removeEventListener("pointerup",c),e.removeEventListener("pointercancel",c)};e.addEventListener("pointermove",h),e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}),e.addEventListener("keydown",a=>{a.key!=="ArrowUp"&&a.key!=="ArrowDown"||(a.preventDefault(),o(i.getBoundingClientRect().height+(a.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>o(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 a=this.groupTabs.find(d=>d.getAttribute("aria-controls")===o);a&&this.toggleGroup(a,!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"?pe.observerTrackIsExpanded(t):pe.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(l=>l.t)};const n=this.ufoElement.seekableDuration,r=l=>e==="observer"?q.isObserver(t,l):q.isPhenomenon(t,l),o=(t.events??[]).map((l,h)=>({event:l,index:h})).filter(({event:l})=>r(l)),a=new Set(o.map(({event:l})=>l.who)).size>1,d=o.map(({event:l,index:h})=>{const c=this.messages.events.kinds[l.eventType]??l.eventType;return{id:String(h),t:l.t,until:l.until??n,label:e==="phenomenon"&&a?`${this.shapesLabel(l.who??"")} · ${c}`:c}});return{times:[],spans:d}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(a=>a.id)),s=a=>q.partOf(a)?.element??a??"",n=(e.events??[]).map((a,d)=>({event:a,index:d})).filter(({event:a})=>i.has(s(a.who)));if(n.length===0||!pe.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(a=>a.track.map(d=>d.t)))].sort((a,d)=>a-d)};const r=this.ufoElement.seekableDuration,o=n.map(({event:a,index:d})=>{const l=t.find(p=>p.id===s(a.who)),h=q.partOf(a.who)?.part,c=this.messages.events.kinds[a.eventType]??a.eventType,u=[...t.length>1?[this.said.read(l?.title)??s(a.who)]:[],...h?[h]:[]];return{id:String(d),t:a.t,until:a.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=(a,d)=>[...d].map(l=>({t:l,kind:"keyframe",label:`${this.messages.keyframeMark} (${a})`})),i=a=>{if(this.showsBodies){const l=this.eventMarks("bodies");return l.spans?l.spans.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.bodiesTrack,l.times)}const{spans:d}=this.eventMarks("phenomenon");return d?d.map(l=>({t:l.t,kind:"event",label:l.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(l=>!a||l.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(l=>l.t))},s=()=>{const{times:a,spans:d}=this.eventMarks("observer");return d?d.map(l=>({t:l.t,kind:"event",label:l.label})):t(this.messages.observerTrack,a)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(a=>a.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(a=>a.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 a of e.milestones)o.push({t:a.t,kind:"milestone",label:this.said.read(a.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=ii.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=Pt.kinds();if(Rt.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Rt.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(d=>d.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:o,opensMostLacking:a}=this;this.openSubgroup(r),this.sectionChosen=o,this.opensMostLacking=a}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=w.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:w.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),Cs.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 An(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(`
2778
+ `)}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=w.QUESTION_FIELDS[n];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const a=this.shadow.getElementById(o);a&&!a.hidden&&a.value===""&&t.add(o)}}for(const[n,r]of Object.entries(w.QUESTION_FIELDS))for(const o of w.QUESTION_FIELDS[n].fields){const a=this.shadow.getElementById(o);if(!a)continue;const d=t.has(o)&&!a.classList.contains("missing-required");a.classList.toggle("wanted",d),(d||a.title===this.messages.questionUnanswered)&&(a.title=d?this.messages.questionUnanswered:this.fieldHints.get(o)??"")}const i=new Map;let s;for(const[n,r]of Object.entries(w.QUESTION_FIELDS))for(const o of r.fields){const a=this.shadow.getElementById(o);if(!a)continue;const d=a.classList.contains("missing-required");!d&&!a.classList.contains("wanted")||(d&&(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,a=r===s,d=w.badgeOn(n);d.hidden=o===0,d.textContent=String(o),d.classList.toggle("optional",!a);const l=o===0?void 0:a?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o));l?n.dataset.unanswered=l:delete n.dataset.unanswered,w.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(a=>a.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(a=>a.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&&be.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:fo(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(w.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,fe.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,fe.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(fe.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(fe.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),a={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-o)/2,width:r,height:o},d=n.ofBounds(a),l=s.kind==="oval"?{...s,bounds:a,angular:d}:{...s,bounds:a,angular:d,points:this.scalePoints(s,a)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:l}]),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={[de.NONE.id]:this.messages.filterNone,[de.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[de.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==de.ALL.length||de.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||de.NONE.id;this.filterSelect.replaceChildren();for(const r of de.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||de.usableWith(de.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),a=ke.unavailability(r,t);if(!a)return{id:r.id,label:o};const d=(a.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(a.from)).replace("{to}",String(a.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",o),hint:d}:{id:r.id,label:o,disabledReason:d}};this.instrumentSelect.choices=ke.CATEGORIES.map(r=>({label:s[r],children:Vn.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=w.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=ie(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??ke.fieldOfViewDeg(t),r=s?ke.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),Ut.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 a=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=a===void 0?"":w.exposureText(a)),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,Dn.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const d=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const l=Et.byId(e.film);this.isoInput.placeholder=d?d.autoExposure?"auto":String(l?.iso??d.iso):"",this.setRowVisible(this.isoInput,d!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,d?.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=de.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=ke.fieldOfViewDeg(e),s=ke.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>lo||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 ie(e,this.ufoElement.currentTime)?.fovDeg??ke.fieldOfViewDeg(e.instrument)}currentProjection(){return si.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=fe.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=ie(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?ke.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,o=s?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const a=this.ufoElement.canvasElement.height;if(a<=0)return;const d=2*Cn*e/a*i.heightMm,l=r*r/(o*d)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(l))}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)??io,o=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),a=o!==void 0&&o<r,d=s(r,1),l=i?.angular?.widthDeg,h=i?.angular?.heightDeg,c=l!==void 0&&h!==void 0&&l>0&&h>0?{widthM:s(fe.sizeMAt(d,l),2),lengthM:s(fe.sizeMAt(d,l),2),heightM:s(fe.sizeMAt(d,h),2)}:void 0,u={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},p={t,...u,distanceM:d,...a?{onGround:!0}:{},...c?{sizeM:c}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:p}:{keyframe:p}}loadBodyEditor(){return this.bodyEditorLoading??=T(async()=>{const{BodyEditor:e}=await import("./BodyEditor-BV8WwzAj.js");return{BodyEditor:e}},__vite__mapDeps([38,2,1,3,4,5,6,7,8,9,10,11,13,16]),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=Pt.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=Os.map(i=>Bt.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]}static pictureTab(e){const t=A.part(e.getAttribute("aria-controls")??"");t&&!e.querySelector("svg")&&e.insertAdjacentHTML("afterbegin",t)}buildSkyParts(){const e=this.shadow.getElementById("weather-tabs"),t=this.shadow.getElementById("sky-event-parts");if(!e||!t)return;const i=this.wantedSkyParts();for(const[s,n]of this.skyParts)if(!i.some(r=>r.key===s&&r.kind===n.kind)){if(n.tab.getAttribute("aria-expanded")==="true"){const r=this.subgroupTabs.find(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),w.pictureTab(n),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 a=document.createElement("div");a.className="toolbar";const d=document.createElement("div");d.id=`${s.id}-editor`,a.append(d),o.append(a),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(wt.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:fe.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=si.of(i.instrument,fe.CANVAS_HEIGHT_PX,Pe.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const o=Pe.aimOf(i,e,r.shape.bounds),a=s.ofBounds(r.shape.bounds),{aim:d,...l}=r.shape;return{...r,shape:o?{...l,aim:o,angular:a}:{...l,angular:a}}}))}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},...Ae.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(l=>l.value===e.id).label,o=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",a={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},d=s.map((l,h)=>{const c=e.partNames[h],u=c?`${r} ${o}, ${a[c]}`:`${r} ${o}`;return{sourceId:n[h],shape:{...l,title:this.said.write(void 0,u,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,d),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(a=>t.includes(a.sourceId)).map(a=>{const{bounds:d}=a.shape;return{sourceId:i[t.indexOf(a.sourceId)],shape:{...a.shape,bounds:{...d,x:d.x+s,y:d.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]??ot,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:Gi.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Fs}:{},windows:zs(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(w.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(w.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(w.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(w.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await T(()=>import("./surroundingsSources-UHKGesPa.js"),__vite__mapDeps([29,1,2,3,4,5,6,7,8,9,10,11]),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=w.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(o=>{const a=document.createElement("option");return a.value=o.id,a.textContent=o.name,a.title=o.credit,a}),r=new Option(this.messages.sourceFile,w.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!==w.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?w.FILE_SOURCE:this.sceneryChoice===w.NO_SCENERY?w.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===w.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=te.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?Wt.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*mi,t=Math.round(e/co*1e3);return{lights:Gi.byId("airliner")?.create(),track:[{t:0,eastM:-mi,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:mi,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=Qn(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?os[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(a=>a.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(([,a])=>a!==void 0).map(([a,d])=>[a,this.roundedMeters(d)]))};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=Ki([...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=Ki(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;be.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=w.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!==w.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!==w.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 T(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([39,40]),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=Et.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=(a,d,l=!1)=>{const h=document.createElement("option");h.value=a,h.textContent=d,h.disabled=l,this.filmStockSelect.appendChild(h)};r("",this.messages.filmStockAny);const o=i.map(a=>({stock:a,gap:Et.gap(a,t,s)}));for(const{stock:a}of o.filter(d=>!d.gap))r(a.id,a.name);for(const{stock:a,gap:d}of o.filter(l=>l.gap)){const l=d.kind==="before"?this.messages.filmStockNotYet.replace("{from}",String(d.from)):this.messages.filmStockNoLonger.replace("{to}",String(d.to));r(a.id,`${a.name} (${l})`,a.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(Et.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 _t(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?nt.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(at.resolve(ge.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(at.resolve(ge.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}=as(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=Vi.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:qi.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Vi.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:ge.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:os[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(d=>d.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=nt.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const o=this.ufoElement.sighting;o.decor=o.decor.map(d=>d.id===s.id?nt.apply(d,r,t,n):d),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const a=o.decor.find(d=>d.id===s.id);t==="title"&&this.decorList.rename(a.id,this.decorLabel(a)),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?Ds.of(e,this.publishedParametersOf(e)):void 0,i=t&&at.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 _t(()=>this.ufoElement.sighting.decor.find(o=>o.id===n),o=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(d=>{if(d.id!==n)return d;const l=structuredClone(d);return o(l),l})});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?ve(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=G("Sun",i,t).altitudeDeg;return Ze(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new er;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Zi;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new gt(["en"]);tagNames=new Yi({});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?ve(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,oe(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,a=[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(d=>d!==void 0);o||(this.showMeteorButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0),this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",a.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 On.gainFor(e.instrument,{fNumber:ie(e,0)?.fNumber,fieldOfViewDeg:Pe.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=G("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Ze(i,s,n),o=l=>l.toLocaleString(void 0,{maximumFractionDigits:1});if(r<no)return this.messages.skyStarsNone;const a=this.ufoElement.sighting.instrument,d=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(a)).replace("{gain}",o(Math.abs(s))).replace("{eye}",o(Ze(i,0,n)));return r<=Ji?d:d+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Ji))}showerClause(e,t){const i=Xi.observedRatePerHour(Xi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=ni.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=ni.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:ni.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=ri.brightestAt(e,t);if(!i||i.magnitude>Qi){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=es.brightestAt(e,t);if(!i||i.magnitude>Qi){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=Rn.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=G("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=G("Moon",e,t);if(i.altitudeDeg<=0||Qe(e).illuminatedFraction<.97)return;const s=[],n=Ye.distanceKm(e,t),r=Ye.relativeToMean(Ye.radiusAtKm(n)),o=n<=Ye.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Ye.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(Ye.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),Zt.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=we.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=Ze(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 a=Math.round(i.shadowHeightKm).toLocaleString(),d=(i.trackedObjects??0).toLocaleString(),l=h=>h.replace("{height}",a).replace("{count}",d);return i.lowOrbitLit?r.length===0?l(this.messages.skySatellitesLit):l(this.messages.skySatellitesLitWith).replace("{eras}",o):l(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 d={key:n,status:"loading"};this.reentries=d,w.reentryArchive.candidates(i,s,t).then(l=>{d.status=l?"ready":"unavailable",d.candidates=l,this.reentries===d&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=we.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(d=>d.record.precision==="minute"||r);if(o.length===0)return;const a=o.slice(0,3).map(d=>this.reentryText(d));return o.length>3&&a.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",a.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(d=>d.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(d=>d.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)),a=this.starlinkTrain(i);return a?`${o}, ${a}`: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=G("Sun",i.peak.date,t);return s<=Ze(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:a}=r.peak.object;o!=="starlink"||!a||(r.peak.date.getTime()-Date.parse(`${a}T00:00:00Z`))/864e5>60||t.set(a,(t.get(a)??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=ie(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=ve(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=>ts.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=ts.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=ve(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=oe(this.ufoElement.sighting,0),s=G("Sun",e,t),n=G("Moon",e,t),r=kt.deckLitUntilDeg(kt.DECK_HEIGHT_M),o=s.altitudeDeg>-r,a=o?s:n;if(a.altitudeDeg<=-r)return;const d=i.highCloudCover;if(d===void 0||d<=0)return this.messages.skyOpticsNoIce;if(kt.strength(d,i.lowerCloudCover??i.cloudCover,a.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const l=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,h=this.listed(kt.formsAt(a.altitudeDeg,r).map(u=>this.opticsFormName(u))),c=i.iceCrystalAlignment??yi;return this.messages.skyOpticsPossible.replace("{forms}",h).replace("{source}",l)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(c*100)))}rainbowClause(e,t){const i=oe(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=G("Sun",e,t),n=G("Moon",e,t),r=s.altitudeDeg>0,o=r?s:n;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const a=i.lowerCloudCover??i.cloudCover;if(oi.strength(i.precipitationIntensity,a,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const d=oi.formsAt(o.altitudeDeg);if(d.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(oi.primary().radiusDeg)));const l=this.listed(d.map(c=>this.bowFormName(c)));if(r)return this.messages.skyBowPossible.replace("{forms}",l);const h=Math.round(Qe(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",l).replace("{lit}",String(h))}glowClause(e,t){const i=G("Sun",e,t);if(i.altitudeDeg>bo)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<=P.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=G("Moon",e,t),a=s.darkestSkyMagPerArcsec2<vo,d=this.ufoElement.sighting.lightPollution,l=me.scatteringAt(90-o.altitudeDeg)*me.moonOutput(me.phaseAngleOf(Qe(e).illuminatedFraction),o.altitudeDeg)*me.scatteredFraction(90),h=me.artificialZenithNanolamberts(d)>l;if(a&&o.altitudeDeg>0&&!h){const u=Math.round(Qe(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(u)).replace("{sky}",r)}const c=me.artificialZenithNanolamberts(d)>me.twilightExcessNanolamberts(i.altitudeDeg);return a&&h&&c?this.messages.skyGlowTowns.replace("{sky}",r):a?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=G("Sun",e,t),s=G("Moon",e,t);return me.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:me.phaseAngleOf(Qe(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new P;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<ri.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=ve(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=ri.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=ve(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=es.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(d=>d.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}=as(e,this.ufoElement.currentTime),r=Math.hypot(i,s);if(r===0&&n===0)return;const o=Math.atan2(i,s)*180/Math.PI,a=Math.atan2(n-ho-(ie(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(a*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??w.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return rs(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Je.width/2,y:e.height/2-Je.height/2,width:Je.width,height:Je.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 Ti(this.ufoElement.sighting.timeline,new yr(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"})),A.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=Oe.preferencesFor(this);this.preferences=t;const i=Ft(t,mt),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,a,d]=await Promise.all([Ls.load(i),i==="en"?{}:Js(i),Xs(i),pr.load(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.decorParameterTexts=d,this.naming=new Zi(a),this.said=new gt(t),this.tagNames=new Yi(o),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new is(r,this.naming,this.said,this.tagNames,{messages:r,locale:this.language},this.decorParameterTexts),this.refreshParamSummary()),l?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===ot&&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(w.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(w.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(Ai))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,ye.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 is(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,ye.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.sectionIndexResize.label(e.resizeSectionIndex),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])_e.popover(this.shadow.getElementById(s),e.close);_e.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),_e.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),_e.button(this.contextMenu,e.close,()=>this.hideContextMenu()),_e.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,w.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",a=i==="shape";if(a)if(this.selectedSourceIds.size>1){const h=new ai(this.selectedMembers()),c=ee.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"?ee.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&&ee.hitTestHandle(h,t);if(h&&u){if(o)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const d=this.ufoElement.shapeAt(t.x,t.y,Dt);if(!d){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(d.sourceId):this.selectedSourceIds.has(d.sourceId)||this.selectUnit(d.sourceId),o||!a)return;const l=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===d.sourceId?d.shape:n.getInterpolatedShapeAt(r,h)??d.shape}));this.dragState={kind:"move",sources:l,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"&&ee.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId,shape:n}:this.ufoElement.shapeAt(t.x,t.y,Dt);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 a=this.pickDecorAt(e),d=a?this.ufoElement.sighting.decor.find(l=>l.id===a):void 0;d&&this.showDecorContextMenu(e.clientX,e.clientY,d)}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 a=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!a,this.contextUngroupButton.title=a?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const d=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),l=this.selectedSourceIds.size===1&&d?.kind==="polygon";this.contextAddVertexButton.disabled=!l,this.contextAddVertexButton.title=l?"":this.messages.notAPolygon;const h=l&&this.contextMenuPoint?ee.hitTestVertex(d,this.contextMenuPoint):void 0,c=l&&d.points.length<=Pn;this.contextDeleteVertexButton.disabled=!l||h===void 0||c,this.contextDeleteVertexButton.title=l?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,a=this.messages;r.textContent=`${o} — ${n>=.995?a.masksBodyFully:n>.005?a.masksBodyPartly.replace("{share}",String(Math.round(n*100))):a.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=ee.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=ee.hitTestVertex(i,e);if(s===void 0)return;const n=ee.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(Ct,(e.maxX-e.minX)/2*t.width),s=Math.max(Ct,(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=Ot,a=Ot+to,d=t.width-Ot,l=t.height-r-Ot,h=Math.max(e.x,o),c=Math.max(e.y,a),u=Math.min(e.x+e.width,d),p=Math.min(e.y+e.height,l);return u-h<Ct||p-c<Ct?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=ee.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,a=(c,u)=>Math.max(.05,Math.abs(c)/Math.max(1,Math.abs(u))),d=o==="e"||o==="w",l=o==="n"||o==="s",h=d?a(i.x-s.x,n.x-s.x):l?a(i.y-s.y,n.y-s.y):a(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.y));t.target.resize({widthM:l?r.widthM:r.widthM*h,lengthM:l?r.lengthM:r.lengthM*h,heightM:d?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:pi};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:oo};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=qi.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:nt.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,Dt)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=nt.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),o=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,a=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,o);return!n||!a?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:a,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&&ls(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&ls(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,a=s.map(({sourceId:d,original:l})=>({sourceId:d,shape:{...l,bounds:{...l.bounds,x:l.bounds.x+r,y:l.bounds.y+o}}}));this.commitShapes(i,a)}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=ee.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:o}])}else{const{kind:s,sourceId:n,original:r,handle:o}=this.dragState,a=s==="resize"?ee.resizeShape(r,o,t):ee.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:a}])}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)<ao)return;this.cameraDragState.moved=!0}const o=s+(t.x-i.x)*pi,a=Math.max(-90,Math.min(90,n-(t.y-i.y)*pi));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=a,this.sceneElement.setIndoorLook(o,a),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(a)),this.updateObserver(),this.rounded(o)!==this.rounded(s)&&(this.cameraDragState.headingTurned=!0),this.rounded(a)!==this.rounded(n)&&(this.cameraDragState.pitchTurned=!0),this.showOrientation(this.cameraDragState.headingTurned?o:void 0,this.cameraDragState.pitchTurned?a:void 0),this.showViewDragHint(e.altKey);const d=this.ufoElement.sighting.observerTrack,l=this.ufoElement.currentTime,h=d.allKeyframes.find(c=>c.t===l);h&&h.viewOnly===!0!==e.altKey&&(d.setViewOnly(l,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?mo: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)*po*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)*uo*t,o=i*Math.PI/180,a=tr(Math.sin(o)*r,-Math.cos(o)*r,s,n);this.latInput.value=a.lat.toFixed(7),this.lngInput.value=a.lng.toFixed(7);const d=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(d,this.plantingCentre()),this.surroundings.walked(a.lat,a.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=_s(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(a,d)=>Math.round((a-d)*1e3)/1e3,o=this.ufoElement.sighting;o.decor=o.decor.map(a=>({...a,eastM:r(a.eastM,s),northM:r(a.northM,n),...a.track?{track:a.track.map(d=>({...d,eastM:r(d.eastM,s),northM:r(d.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ss,i.width-Ne);break;case"ArrowRight":i.width+=Ne;break;case"ArrowUp":i.height=Math.max(ss,i.height-Ne);break;case"ArrowDown":i.height+=Ne;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Ne;break;case"ArrowRight":i.x+=Ne;break;case"ArrowUp":i.y-=Ne;break;case"ArrowDown":i.y+=Ne;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 ai(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 a=r?this.bodyCanvasBounds():void 0,d=a&&ee.hitTestHandle({bounds:a,angle:0},t);if(d)return this.cursorForHandle(d,0);const l=this.ndcOf(e),h=l&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(l.x,l.y):void 0;return r&&h?"move":r?"pan":void 0}if(i==="decor"&&r&&this.decorMoveAxis(e)){const a=this.decorCanvasBounds(),d=a&&ee.hitTestHandle({bounds:a,angle:0},t);if(d)return this.cursorForHandle(d,0);const l=this.editableDecor();if(l&&!this.ufoElement.shapeAt(t.x,t.y,Dt)&&this.grabsDecor(e,t,l))return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const a=ee.hitTestHandle({bounds:new ai(this.selectedMembers()).bounds(),angle:0},t);if(a)return this.cursorForHandle(a,0)}else{const a=s.getInterpolatedShapeAt(n,this.currentSourceId);if(a?.kind==="polygon"&&ee.hitTestVertex(a,t)!==void 0)return"vertex";const d=a&&ee.hitTestHandle(a,t);if(a&&d)return this.cursorForHandle(d,a.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-${ee.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(Ns(this.buildPrototype({x:0,y:0,width:Je.width,height:Je.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 wo={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},Ms="rr0-sighting-editor";function Ks(){Us(),As(),qs(),Ir(),xr(),Lr(),Ps(),customElements.get(Ms)||customElements.define(Ms,w)}const ki="rr0-case-editor",yo=`
2779
2779
  <style>
2780
2780
  /* What the layout adapts to: the width this editor is given, never the window's. */
2781
2781
  :host { display: block; container-type: inline-size; }
@@ -3170,6 +3170,6 @@ ${z.rules([],[".model-picker .model-picker-address p"])}
3170
3170
  </form>
3171
3171
  </dialog>
3172
3172
  `;class De extends HTMLElement{shadow=this.attachShadow({mode:"open"});editor;session;current;listShown=!0;currentInterview;interviewElement;interviewReady;group="events";fileEditor;fileEditorLoading;fileApplied="";editorMessages;messages=Ke.none();ready=Promise.resolve();said=new gt(["en"]);localeToken=0;language="en";dialogMode="add";pendingLoad;dirtyTimer;caseDate;dateModeFor;constructor(){super(),Ks(),Us(),Bs.register(),this.shadow.innerHTML=yo,customElements.upgrade(this.shadow),this.shadow.getElementById("case-date").build();for(const e of this.shadow.querySelectorAll("rr0-input-file"))e.build();this.editor=this.shadow.getElementById("editor"),this.columns=new je(this.byId("column-resize"),this.byId("group-events"),()=>this.byId("case-overview"),je.CASE_HISTORY_KEY,je.PROPERTY,44),this.interviewElement=this.shadow.getElementById("interview"),this.interviewElement.addEventListener(on,e=>this.interviewChanged(e.detail)),this.interviewElement.addEventListener(an,e=>void this.sendCase(e.detail)),this.interviewElement.addEventListener(ln,e=>void this.feedObservation(e.detail)),this.interviewElement.addEventListener(dn,e=>void this.followToObservation(e.detail)),this.editor.addEventListener("caseloaded",e=>{e.preventDefault();const{json:t,url:i}=e.detail;this.openCase(t,i??location.href,i!==void 0&&!$e.local(i))}),this.editor.addEventListener("recordingloaded",()=>this.closeCase()),this.editor.addEventListener("sightingchange",()=>{clearTimeout(this.checkReadingTimer),this.checkReadingTimer=setTimeout(()=>this.checkReading(),De.CHECK_READING_AFTER_MS)}),this.editor.guardsLeaving=!1,this.editor.addEventListener("beforeload",e=>{this.dirty&&(e.preventDefault(),this.pendingLoad=e.detail.proceed,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion))});for(const e of["input","change","datechange","click","pointerup","keyup"])this.shadow.addEventListener(e,()=>this.scheduleDirtyCheck(),!0);for(const[e,t]of[["case-id","id"],["case-title","title"]])this.input(e).addEventListener("input",()=>this.writeCaseField(t,this.input(e).value));this.caseDate=this.byId("case-date"),this.caseDate.addEventListener("datechange",e=>{const{time:t}=e.detail;this.writeCaseField("time",t?De.rr0TimeOf(qn(t)):"")}),this.byId("track").addEventListener("change",()=>{this.byId("cited").hidden=!0,this.listShown=!1,this.refreshOverview();const e=this.session?this.items(this.session)[Number(this.byId("track").value)]:void 0;e&&(e.interview?this.showInterview(e.interview):this.showTrack(e.track))});for(const e of this.shadow.querySelectorAll("#case-tabs .group-tab"))e.addEventListener("click",()=>this.openGroup(e.getAttribute("aria-controls")==="group-case-file"?"file":"events"));this.inputFile("import").addEventListener("filepick",e=>{const t=e.detail;t.file?this.importFromFile(t.file):this.importFromUrl(t.url)}),this.byId("add").addEventListener("click",()=>this.askAdd()),this.byId("group-readings").addEventListener("click",()=>{this.grouping=!this.grouping,Fe.rememberGrouping(this.grouping),this.refreshOverview()}),this.byId("events-search").addEventListener("input",e=>{this.query=e.target.value,this.refreshOverview()}),this.byId("cited-back").addEventListener("click",()=>{const e=this.citedFrom;if(!e||!this.session)return;const t=this.items(this.session).findIndex(i=>i.interview===e);t>=0&&this.openEvent(t)}),this.byId("back-to-case").addEventListener("click",()=>{this.listShown=!0,this.refreshRow()}),this.shareDialog=this.byId("share-dialog"),hn.register(),this.byId("report-export").source=async()=>{const e=this.session;if(!e)throw new Error("No case");this.commit(),await Promise.all(e.tracks.filter(i=>!i.recording).map(i=>this.loadTrack(i).catch(()=>{})));const t=new Map;for(const i of e.tracks)i.recording&&t.set(i.url,i.recording);return{caseJson:e.json,caseUrl:e.url,recordings:t}},this.shareDialog.subject=this.shareSubject,this.byId("share-case").addEventListener("click",()=>this.openShare()),this.byId("read-case").addEventListener("click",()=>this.read()),this.byId("save-menu").addEventListener("beforetoggle",e=>{if(e.newState!=="open")return;const t=this.byId("save-options").getBoundingClientRect(),i=this.byId("save-menu");i.style.top=`${Math.round(t.bottom+6)}px`,i.style.right=`${Math.max(8,Math.round(window.innerWidth-t.right))}px`}),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 e=this.current;!this.session||!e||(this.session.seal(e,!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",e=>{e.preventDefault(),this.submitDialog()})}static get observedAttributes(){return["src",vt]}attributeChangedCallback(e,t,i){e===vt&&(i!==null&&!this.switcher&&new Qs(s=>this.after(s),this,s=>this.dispatchEvent(new CustomEvent(en,{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();const t=this.caseStart;!e&&t&&!this.session&&(this.ready=this.ready.then(()=>this.startCase(t)))}caseStart;async startCase(e){if(this.caseStart=e,!e.questionnaires?.length)return;this.makeCase(!1);const t=await this.addStartQuestionnaires();t[0]&&tn.step(e)==="questionnaire"&&await this.showInterview(t[0])}get sightingData(){return this.editor.sightingData}set sightingData(e){const t=Ge.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=Oe.preferencesFor(this),i=Ft(t,mt),[s,n,r]=await Promise.all([sn.load(i),Ls.load(i),Nn.load(i)]);if(e!==this.localeToken)return;this.said=new gt(t),this.language=i,this.messages=s,this.readingCheck=new ns(r),this.bestCases=new Fn(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(){_e.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),this.byId("save-options").title=e.saveOptions,this.byId("save-options").setAttribute("aria-label",e.saveOptions),t("label-read-case",e.readButton),this.byId("read-case").title=e.readTitle,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("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.columns.label(e.resizeColumns),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"){z.show(this.byId("case-file-note"),e,t)}fileText(){return this.session?JSON.stringify(this.session.json,null,2)+`
3173
- `:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{await this.ready,this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([T(()=>import("./SightingFileEditor-DS1DRU2p.js"),__vite__mapDeps([26,27,28]),import.meta.url),T(()=>import("./caseSchema-BEJTs2Ld.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(!ne.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{ne.check(i)}catch(s){this.showFileNote(s instanceof zt?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 et.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!ne.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof zt?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){ne.check(e);const s=new ae(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(a=>a.url===r)??s.tracks.find(a=>a.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=Ge.recording(await et.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?De.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||Rt.computes(r.recording?.interpretation,Pt.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 T(async()=>{const{InterviewFile:o}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:o}},__vite__mapDeps([41,1]),import.meta.url),s=this.items(e),n=e.interviews.length===1,r=[];for(const o of e.interviews){const a=await this.transcriptOf(o);if(!a||!Array.isArray(a.segments))continue;const d=o.id;r.push({...n||d===void 0?{}:{id:d},label:this.optionLabel({interview:o},s.findIndex(l=>l.interview===o)),segments:a.segments.map((l,h)=>{const c=i.said(l)??"",u=c.length>80?`${c.slice(0,77)}…`:c;return{index:h,label:c===""?"":`${i.speakerName(a,l.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=gi.strip(t.recording).provenance,r=c=>n.at(c)?.range,o=r("time"),a=r("place.locations.0.lat"),d=r("place.locations.0.lng"),l=gi.strip(t.recording).recording.lighting;this.editor.setReadingBounds({...typeof o=="string"?{time:o}:{},...l?{hour:c=>ns.nearestLit(l,c,this.editor.sightingData)}:{},...Array.isArray(a)?{lat:a}:{},...Array.isArray(d)?{lng:d}:{}});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 T(async()=>{const{InterviewFile:n}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:n}},__vite__mapDeps([41,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 et.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 T(async()=>{const{InterviewFile:a}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:a}},__vite__mapDeps([41,1]),import.meta.url);if(i!==this.passagesToken)return;const n=e.event.id??t.proposedId(e),r=[];for(const a of t.interviews){const d=await this.transcriptOf(a);if(!d||!Array.isArray(d.segments))continue;const l={...d,interviewOf:d.interviewOf??a.interviewOf};for(const h of s.passagesAbout(l,n))r.push({interview:a,json:d,passage:h})}if(i!==this.passagesToken||this.current!==e||r.length===0)return;const o=this.items(t);this.editor.passages=r.sort((a,d)=>a.passage.at-d.passage.at).map(({interview:a,json:d,passage:l})=>{const h=`${this.messages.passagesHeading} ${this.optionLabel({interview:a},o.findIndex(u=>u.interview===a))}`,c=l.text===void 0?"":l.range?l.text.slice(l.range[0],l.range[1]):l.text;return{at:l.at,clock:s.clock(l.at,!0),said:c===""?h:`${s.speakerName(d,l.speaker)}${this.messages.colon}${this.messages.quoted.replace("{text}",c.length>120?`${c.slice(0,117)}…`:c)}`,where:h,open:()=>void this.showInterview(a).then(()=>this.interviewElement.revealSegment(l.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(l=>this.labelOf(l,i.tracks.indexOf(l))).join(", "):this.said.read(e.interview.title);if(!o)return this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1));const a=e.interview.title?this.said.read(e.interview.title):"";return r.length>0&&i.interviews.some(l=>l!==e.interview&&i.intervieweesOf(l).some(h=>r.includes(h)))&&a?`${this.messages.interviewOf} ${o} (${a})`:`${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??=T(async()=>{const{register:e}=await import("./InterviewEditorElement-BA060rqJ.js");return{register:e}},__vite__mapDeps([42,1,2,3,4,5,6,7,8,9,10,11,43,14,44,41,15,13,16,17,18,19,20]),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 Fe.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 Fe.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),this.sweepScenarios(e);const n=s.findIndex(({item:o})=>o.interview?o.interview===this.currentInterview:o.track===this.current),r=s[n];if(this.revealOpenEvent(t,r?.item.interview??r?.item.track),r){const o=this.kindOf(r.item),a=this.byId("crumb-kind");a.textContent=this.kindLabel(o),a.dataset.kind=o,this.byId("crumb-title").textContent=this.optionLabel(r.item,r.index)}}revealed;revealOpenEvent(e,t){this.listShown||t===void 0||t===this.revealed||(this.revealed=t,requestAnimationFrame(()=>{const i=e.querySelector("[data-open]");if(!i)return;const s=e.getBoundingClientRect(),n=i.getBoundingClientRect();n.top>=s.top&&n.bottom<=s.bottom||e.scrollTo({top:e.scrollTop+n.top-s.top-Math.max(0,(s.height-n.height)/2),behavior:"smooth"})}))}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=Fe.groupingRemembered();columns;folded=new Set;kindsShown=new Set(["observation","interview","reading"]);query="";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),a=document.createElement("button");a.type="button",a.className="filter-chip",a.dataset.kind=n,a.setAttribute("aria-pressed",String(o));const d=document.createElement("span");d.textContent={observation:t.kindObservations,reading:t.kindReadings,interview:t.kindInterviews}[n];const l=document.createElement("span");return l.className="filter-count",l.textContent=String(r),a.append(d,l),a.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())}),a}))}renderEvents(e,t){const i=this.messages,s=this.byId("event-list"),n=t.filter(({item:b})=>this.kindsShown.has(this.kindOf(b)));this.renderFilter(t),this.byId("events-count").textContent=String(n.length);const r=b=>{const v=[b.track?.event.interpretationOf].flat().filter(y=>y!==void 0);return n.map(({item:y})=>y).filter(y=>y.track?.kind==="observer"&&v.some(S=>y.track.event.id===S||y.track.recording?.id===S))},o=n.some(({item:b})=>this.kindOf(b)==="reading"),a=this.byId("group-readings");a.hidden=!o,a.setAttribute("aria-pressed",String(this.grouping));const d=this.grouping?Fe.grouped(n,{kind:b=>this.kindOf(b),read:r}):n,l=new Map(n.map(({item:b,index:v})=>[b,v])),h=b=>!this.listShown&&(b.interview?b.interview===this.currentInterview:b.track===this.current),u=d.filter(({item:b,under:v})=>v===void 0||this.query.trim()!==""||!this.folded.has(l.get(v))||h(b)).map(({item:b,index:v,under:y})=>{const S=this.kindOf(b),k=b.track?.event??b.interview,I={at:v,kind:S,title:this.optionLabel(b,v),meta:[k.time?String(k.time).replace("T"," "):"",k.id??""].filter(Boolean).join(" · "),by:S==="observation"?"":this.authorsSaid(k.by),open:h(b),...y?{nested:!0}:{}},C=this.grouping&&S==="observation"?d.filter(R=>R.under===b).length:0;if(C>0&&(I.readings={count:C,folded:this.folded.has(v)}),b.track?.kind==="observer"){const R=e.interviews.filter(M=>e.intervieweesOf(M).includes(b.track)).map(M=>({at:e.tracks.length+e.interviews.indexOf(M),title:this.optionLabel({interview:M},0)}));R.length>0&&(I.links={heading:i.passagesHeading,to:R})}else if(b.track){const R=[b.track.event.interpretationOf].flat().filter(M=>M!==void 0).map(M=>e.tracks.find(Z=>Z.kind==="observer"&&(Z.event.id===M||Z.recording?.id===M))).filter(M=>M!==void 0).filter(M=>M!==y?.track).map(M=>({at:e.tracks.indexOf(M),title:this.labelOf(M,e.tracks.indexOf(M))}));R.length>0&&(I.links={heading:y?i.alsoAbout:i.interpretationOf,to:R})}return I}),p=new Fe(s,b=>this.openEvent(b),b=>this.openEvent(b),void 0,b=>{this.folded.delete(b)||this.folded.add(b),this.refreshOverview()});p.render(u,i,(b,{card:v,body:y,links:S})=>this.dress(e,t.find(({index:k})=>k===b.at).item,b.at,v,y,S));const m=this.byId("events-search");m.placeholder=i.searchEvents,m.setAttribute("aria-label",i.searchEvents),m.hidden=t.length<5;const f=p.search(this.query),g=this.byId("events-none");g.textContent=i.noEventFound,g.hidden=this.query.trim()===""||f>0}dress(e,t,i,s,n,r){const o=this.messages,a=r.textContent!=="",d=t.track?.kind==="reading"?this.findingsOf(t.track):void 0,l=zn.of(d);if(l){s.dataset.verdict=l;const p=document.createElement("span");p.className="verdict",p.textContent=o.readingVerdict[l],r.prepend(p,...a?[document.createTextNode(" · ")]:[])}const h=t.track!==void 0&&ae.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=A.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?A.LOCK:A.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=A.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),d&&d.length>0&&n.append(this.findingsList(d)),t.track?.kind==="reading"&&t.track.recording){const p=_n.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 a=document.createElement("span");a.className="finding-against",a.textContent=` (${t.findingAgainst[s.against??"established"]})`,n.append(a)}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||(!ae.sealed(s.event)&&this.current===s&&this.commit(),t.seal(s,!ae.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&&ae.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&&ae.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())}refreshCaseState(){const e=!(this.session?.dirty??!1);this.byId("save-case").disabled=e,this.byId("save-options").disabled=e;const t=this.byId("save-menu");if(e)try{t.hidePopover?.()}catch{}const i=this.byId("share-case");i.disabled=this.sourceUrl===void 0,i.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"";const s=this.byId("read-case");s.hidden=!this.hasAttribute(vt)&&this.readAddress()===void 0,this.session&&s.parentElement!==i.parentElement?i.before(s):!this.session&&s.parentElement!==this.editor&&(s.slot="head-actions",this.editor.append(s))}switcher;readAddress(){return this.session?this.sourceUrl:this.editor.address}read(){const e=this.readAddress();if(this.hasAttribute(vt)){const i=this.holdForReading();if(nn.ask(this,rn,i))return;$e.releaseCopies()}if(e===void 0)return;const t=this.session?this.sharedTrack:void 0;window.open(`${wi.home()}/play/?file=${encodeURIComponent(e)}${t?`&events=${encodeURIComponent(De.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`${wi.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){cn.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()})}sweepScenarios(e){tt.register(),this.byId("scenario-sweep").show({caseJson:()=>e.json,load:async i=>{const s=e.tracks.find(n=>n.event.url===i);if(!s)throw new Error(`No event of the case lists ${i}`);return await this.loadTrack(s),s.recording},keep:i=>{let s=0;for(const{recording:n,title:r,readingUrl:o}of i){const a=e.tracks.find(l=>l.event.url===o),d=a?e.accountOf(a):void 0;!a||!d||(e.addObservation(n,this.today(),r,{account:d,...a.event.by?{by:a.event.by}:{}}),s++)}return s>0&&this.refreshOverview(),s}})}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(e=!0){if(this.session)return;const t=this.editor.sightingData,i=t.time,s=typeof i=="object"?i.value:i,n=s?De.rr0TimeOf(s):void 0,r=this.said.read(t.observer?.title),o=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=ae.around(t,n,r,o,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,t),this.dateModeFor=void 0,this.refreshRow(),e&&this.addStartQuestionnaires()}async addStartQuestionnaires(){const e=this.session,t=e?.tracks.find(r=>r.kind==="observer"),i=this.caseStart?.questionnaires??[];if(!e||!t||i.length===0)return[];const{QuestionnaireTemplates:s}=await T(async()=>{const{QuestionnaireTemplates:r}=await Promise.resolve().then(()=>hs);return{QuestionnaireTemplates:r}},void 0,import.meta.url),n=[];for(const r of i){const o=await s.load(r).catch(()=>{});!o||this.session!==e||n.push(e.addQuestionnaire(t,this.today(),o,this.caseStart?.recipient))}return n.length>0&&(this.refreshRow(),this.scheduleDirtyCheck()),n}async feedObservation(e){const t=this.session,i=t?.intervieweeOf(e.event);if(!t||!i||ae.sealed(i.event)){e.report(0);return}this.commit(),await this.loadTrack(i);const[{QuestionnaireFeed:s},{QuestionnaireTemplates:n}]=await Promise.all([T(()=>import("./QuestionnaireFeed-W69udpmT.js"),__vite__mapDeps([45,46,41,1,6,7,13,14,2,3,4,5,8,9,10,11,15,16,17,18,19,20]),import.meta.url),T(()=>Promise.resolve().then(()=>hs),void 0,import.meta.url)]),r=await n.load(e.json.questionnaire?.id??n.DEFAULT);if(!r||!i.recording){e.report(0);return}const o=structuredClone(i.recording),a=s.apply(o,e.json,r,e.event.id);a.length>0&&(t.keep(i,o),t.touch(),this.current===i&&this.showTrack(i),this.refreshRow(),this.scheduleDirtyCheck()),e.report(a.length)}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:Zn(De.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)&&dt.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,a]of[["case-id","id"],["case-title","title"]]){const d=this.input(o);d!==t&&(d.value=String(e.json[a]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),s=this.items(e);i.replaceChildren(...s.map((o,a)=>new Option(this.optionLabel(o,a),String(a))));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&&ae.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{duplicateIds:t,unresolved:i}=e.problems(),s=[...t.map(r=>this.messages.idDuplicated.replace("{id}",r)),...i.map(({reference:r})=>this.messages.readingUnresolved.replace("{id}",r))],n=this.byId("case-problems");n.hidden=s.length===0,n.textContent=s.join(" ")}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??=a=>{const d=a.composedPath();(a instanceof KeyboardEvent?a.key==="Escape":!d.includes(this.dialog)&&!d.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 T(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CGVsMdje.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(ne.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 a=(i?this.input("title").value:n).trim(),d=a!==""?a:this.said.read(o.observer?.title),l=this.input("author").value.trim(),h=e.addObservation(o,r!==""?r:void 0,d,i?{account:i,by:l!==""?[{title:l}]: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 et.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 s of t.tracks)await this.loadTrack(s)}catch{return!1}const i=await this.archive(e);return t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),this.download(i.blob,i.name),!0}async archive(e){const t=this.session,i=t.files(e,!0),s=e?t.attachments():[];if(i.length===1&&s.length===0)return{blob:new Blob([i[0].content],{type:"application/json"}),name:i[0].path};const{zipSync:n,strToU8:r}=await T(async()=>{const{zipSync:a,strToU8:d}=await import("./browser-CltifEM0.js");return{zipSync:a,strToU8:d}},[],import.meta.url),o={};for(const a of i)o[a.path]=r(a.content);for(const a of s)o[a.path]=new Uint8Array(await a.blob.arrayBuffer());return{blob:new Blob([n(o)],{type:"application/zip"}),name:`${t.json.id??"case"}.zip`}}async sendCase(e){const t=this.session;if(!t)return;this.commit();let i;try{for(const a of t.tracks)await this.loadTrack(a);i=await this.archive(!0)}catch(a){e.report("failed",a instanceof Error?a.message:String(a));return}const s=new File([i.blob],i.name,{type:i.blob.type}),n=e.body.replaceAll("{file}",i.name),r=navigator;if(typeof r.share=="function"&&r.canShare?.({files:[s]}))try{await r.share({files:[s],title:e.subject,text:n}),e.report("shared",i.name);return}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return}this.download(i.blob,i.name);const o=document.createElement("a");o.href=`mailto:${e.email?encodeURIComponent(e.email).replace("%40","@"):""}?subject=${encodeURIComponent(e.subject)}&body=${encodeURIComponent(`${n}
3173
+ `:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{await this.ready,this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([T(()=>import("./SightingFileEditor-DS1DRU2p.js"),__vite__mapDeps([26,27,28]),import.meta.url),T(()=>import("./caseSchema-BEJTs2Ld.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(!ne.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{ne.check(i)}catch(s){this.showFileNote(s instanceof zt?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 et.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!ne.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof zt?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){ne.check(e);const s=new ae(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(a=>a.url===r)??s.tracks.find(a=>a.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=Ge.recording(await et.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?De.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||Rt.computes(r.recording?.interpretation,Pt.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 T(async()=>{const{InterviewFile:o}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:o}},__vite__mapDeps([41,1]),import.meta.url),s=this.items(e),n=e.interviews.length===1,r=[];for(const o of e.interviews){const a=await this.transcriptOf(o);if(!a||!Array.isArray(a.segments))continue;const d=o.id;r.push({...n||d===void 0?{}:{id:d},label:this.optionLabel({interview:o},s.findIndex(l=>l.interview===o)),segments:a.segments.map((l,h)=>{const c=i.said(l)??"",u=c.length>80?`${c.slice(0,77)}…`:c;return{index:h,label:c===""?"":`${i.speakerName(a,l.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=gi.strip(t.recording).provenance,r=c=>n.at(c)?.range,o=r("time"),a=r("place.locations.0.lat"),d=r("place.locations.0.lng"),l=gi.strip(t.recording).recording.lighting;this.editor.setReadingBounds({...typeof o=="string"?{time:o}:{},...l?{hour:c=>ns.nearestLit(l,c,this.editor.sightingData)}:{},...Array.isArray(a)?{lat:a}:{},...Array.isArray(d)?{lng:d}:{}});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 T(async()=>{const{InterviewFile:n}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:n}},__vite__mapDeps([41,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 et.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 T(async()=>{const{InterviewFile:a}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:a}},__vite__mapDeps([41,1]),import.meta.url);if(i!==this.passagesToken)return;const n=e.event.id??t.proposedId(e),r=[];for(const a of t.interviews){const d=await this.transcriptOf(a);if(!d||!Array.isArray(d.segments))continue;const l={...d,interviewOf:d.interviewOf??a.interviewOf};for(const h of s.passagesAbout(l,n))r.push({interview:a,json:d,passage:h})}if(i!==this.passagesToken||this.current!==e||r.length===0)return;const o=this.items(t);this.editor.passages=r.sort((a,d)=>a.passage.at-d.passage.at).map(({interview:a,json:d,passage:l})=>{const h=`${this.messages.passagesHeading} ${this.optionLabel({interview:a},o.findIndex(u=>u.interview===a))}`,c=l.text===void 0?"":l.range?l.text.slice(l.range[0],l.range[1]):l.text;return{at:l.at,clock:s.clock(l.at,!0),said:c===""?h:`${s.speakerName(d,l.speaker)}${this.messages.colon}${this.messages.quoted.replace("{text}",c.length>120?`${c.slice(0,117)}…`:c)}`,where:h,open:()=>void this.showInterview(a).then(()=>this.interviewElement.revealSegment(l.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(l=>this.labelOf(l,i.tracks.indexOf(l))).join(", "):this.said.read(e.interview.title);if(!o)return this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1));const a=e.interview.title?this.said.read(e.interview.title):"";return r.length>0&&i.interviews.some(l=>l!==e.interview&&i.intervieweesOf(l).some(h=>r.includes(h)))&&a?`${this.messages.interviewOf} ${o} (${a})`:`${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??=T(async()=>{const{register:e}=await import("./InterviewEditorElement-BSwkegEp.js");return{register:e}},__vite__mapDeps([42,1,2,3,4,5,6,7,8,9,10,11,43,14,44,41,15,13,16,17,18,19,20]),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 Fe.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 Fe.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),this.sweepScenarios(e);const n=s.findIndex(({item:o})=>o.interview?o.interview===this.currentInterview:o.track===this.current),r=s[n];if(this.revealOpenEvent(t,r?.item.interview??r?.item.track),r){const o=this.kindOf(r.item),a=this.byId("crumb-kind");a.textContent=this.kindLabel(o),a.dataset.kind=o,this.byId("crumb-title").textContent=this.optionLabel(r.item,r.index)}}revealed;revealOpenEvent(e,t){this.listShown||t===void 0||t===this.revealed||(this.revealed=t,requestAnimationFrame(()=>{const i=e.querySelector("[data-open]");if(!i)return;const s=e.getBoundingClientRect(),n=i.getBoundingClientRect();n.top>=s.top&&n.bottom<=s.bottom||e.scrollTo({top:e.scrollTop+n.top-s.top-Math.max(0,(s.height-n.height)/2),behavior:"smooth"})}))}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=Fe.groupingRemembered();columns;folded=new Set;kindsShown=new Set(["observation","interview","reading"]);query="";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),a=document.createElement("button");a.type="button",a.className="filter-chip",a.dataset.kind=n,a.setAttribute("aria-pressed",String(o));const d=document.createElement("span");d.textContent={observation:t.kindObservations,reading:t.kindReadings,interview:t.kindInterviews}[n];const l=document.createElement("span");return l.className="filter-count",l.textContent=String(r),a.append(d,l),a.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())}),a}))}renderEvents(e,t){const i=this.messages,s=this.byId("event-list"),n=t.filter(({item:b})=>this.kindsShown.has(this.kindOf(b)));this.renderFilter(t),this.byId("events-count").textContent=String(n.length);const r=b=>{const v=[b.track?.event.interpretationOf].flat().filter(y=>y!==void 0);return n.map(({item:y})=>y).filter(y=>y.track?.kind==="observer"&&v.some(S=>y.track.event.id===S||y.track.recording?.id===S))},o=n.some(({item:b})=>this.kindOf(b)==="reading"),a=this.byId("group-readings");a.hidden=!o,a.setAttribute("aria-pressed",String(this.grouping));const d=this.grouping?Fe.grouped(n,{kind:b=>this.kindOf(b),read:r}):n,l=new Map(n.map(({item:b,index:v})=>[b,v])),h=b=>!this.listShown&&(b.interview?b.interview===this.currentInterview:b.track===this.current),u=d.filter(({item:b,under:v})=>v===void 0||this.query.trim()!==""||!this.folded.has(l.get(v))||h(b)).map(({item:b,index:v,under:y})=>{const S=this.kindOf(b),k=b.track?.event??b.interview,I={at:v,kind:S,title:this.optionLabel(b,v),meta:[k.time?String(k.time).replace("T"," "):"",k.id??""].filter(Boolean).join(" · "),by:S==="observation"?"":this.authorsSaid(k.by),open:h(b),...y?{nested:!0}:{}},C=this.grouping&&S==="observation"?d.filter(R=>R.under===b).length:0;if(C>0&&(I.readings={count:C,folded:this.folded.has(v)}),b.track?.kind==="observer"){const R=e.interviews.filter(M=>e.intervieweesOf(M).includes(b.track)).map(M=>({at:e.tracks.length+e.interviews.indexOf(M),title:this.optionLabel({interview:M},0)}));R.length>0&&(I.links={heading:i.passagesHeading,to:R})}else if(b.track){const R=[b.track.event.interpretationOf].flat().filter(M=>M!==void 0).map(M=>e.tracks.find(Z=>Z.kind==="observer"&&(Z.event.id===M||Z.recording?.id===M))).filter(M=>M!==void 0).filter(M=>M!==y?.track).map(M=>({at:e.tracks.indexOf(M),title:this.labelOf(M,e.tracks.indexOf(M))}));R.length>0&&(I.links={heading:y?i.alsoAbout:i.interpretationOf,to:R})}return I}),p=new Fe(s,b=>this.openEvent(b),b=>this.openEvent(b),void 0,b=>{this.folded.delete(b)||this.folded.add(b),this.refreshOverview()});p.render(u,i,(b,{card:v,body:y,links:S})=>this.dress(e,t.find(({index:k})=>k===b.at).item,b.at,v,y,S));const m=this.byId("events-search");m.placeholder=i.searchEvents,m.setAttribute("aria-label",i.searchEvents),m.hidden=t.length<5;const f=p.search(this.query),g=this.byId("events-none");g.textContent=i.noEventFound,g.hidden=this.query.trim()===""||f>0}dress(e,t,i,s,n,r){const o=this.messages,a=r.textContent!=="",d=t.track?.kind==="reading"?this.findingsOf(t.track):void 0,l=zn.of(d);if(l){s.dataset.verdict=l;const p=document.createElement("span");p.className="verdict",p.textContent=o.readingVerdict[l],r.prepend(p,...a?[document.createTextNode(" · ")]:[])}const h=t.track!==void 0&&ae.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=A.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?A.LOCK:A.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=A.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),d&&d.length>0&&n.append(this.findingsList(d)),t.track?.kind==="reading"&&t.track.recording){const p=_n.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 a=document.createElement("span");a.className="finding-against",a.textContent=` (${t.findingAgainst[s.against??"established"]})`,n.append(a)}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||(!ae.sealed(s.event)&&this.current===s&&this.commit(),t.seal(s,!ae.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&&ae.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&&ae.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())}refreshCaseState(){const e=!(this.session?.dirty??!1);this.byId("save-case").disabled=e,this.byId("save-options").disabled=e;const t=this.byId("save-menu");if(e)try{t.hidePopover?.()}catch{}const i=this.byId("share-case");i.disabled=this.sourceUrl===void 0,i.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"";const s=this.byId("read-case");s.hidden=!this.hasAttribute(vt)&&this.readAddress()===void 0,this.session&&s.parentElement!==i.parentElement?i.before(s):!this.session&&s.parentElement!==this.editor&&(s.slot="head-actions",this.editor.append(s))}switcher;readAddress(){return this.session?this.sourceUrl:this.editor.address}read(){const e=this.readAddress();if(this.hasAttribute(vt)){const i=this.holdForReading();if(nn.ask(this,rn,i))return;$e.releaseCopies()}if(e===void 0)return;const t=this.session?this.sharedTrack:void 0;window.open(`${wi.home()}/play/?file=${encodeURIComponent(e)}${t?`&events=${encodeURIComponent(De.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`${wi.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){cn.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()})}sweepScenarios(e){tt.register(),this.byId("scenario-sweep").show({caseJson:()=>e.json,load:async i=>{const s=e.tracks.find(n=>n.event.url===i);if(!s)throw new Error(`No event of the case lists ${i}`);return await this.loadTrack(s),s.recording},keep:i=>{let s=0;for(const{recording:n,title:r,readingUrl:o}of i){const a=e.tracks.find(l=>l.event.url===o),d=a?e.accountOf(a):void 0;!a||!d||(e.addObservation(n,this.today(),r,{account:d,...a.event.by?{by:a.event.by}:{}}),s++)}return s>0&&this.refreshOverview(),s}})}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(e=!0){if(this.session)return;const t=this.editor.sightingData,i=t.time,s=typeof i=="object"?i.value:i,n=s?De.rr0TimeOf(s):void 0,r=this.said.read(t.observer?.title),o=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=ae.around(t,n,r,o,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,t),this.dateModeFor=void 0,this.refreshRow(),e&&this.addStartQuestionnaires()}async addStartQuestionnaires(){const e=this.session,t=e?.tracks.find(r=>r.kind==="observer"),i=this.caseStart?.questionnaires??[];if(!e||!t||i.length===0)return[];const{QuestionnaireTemplates:s}=await T(async()=>{const{QuestionnaireTemplates:r}=await Promise.resolve().then(()=>hs);return{QuestionnaireTemplates:r}},void 0,import.meta.url),n=[];for(const r of i){const o=await s.load(r).catch(()=>{});!o||this.session!==e||n.push(e.addQuestionnaire(t,this.today(),o,this.caseStart?.recipient))}return n.length>0&&(this.refreshRow(),this.scheduleDirtyCheck()),n}async feedObservation(e){const t=this.session,i=t?.intervieweeOf(e.event);if(!t||!i||ae.sealed(i.event)){e.report(0);return}this.commit(),await this.loadTrack(i);const[{QuestionnaireFeed:s},{QuestionnaireTemplates:n}]=await Promise.all([T(()=>import("./QuestionnaireFeed-CpZqkxlt.js"),__vite__mapDeps([45,46,41,1,6,7,13,14,2,3,4,5,8,9,10,11,15,16,17,18,19,20]),import.meta.url),T(()=>Promise.resolve().then(()=>hs),void 0,import.meta.url)]),r=await n.load(e.json.questionnaire?.id??n.DEFAULT);if(!r||!i.recording){e.report(0);return}const o=structuredClone(i.recording),a=s.apply(o,e.json,r,e.event.id);a.length>0&&(t.keep(i,o),t.touch(),this.current===i&&this.showTrack(i),this.refreshRow(),this.scheduleDirtyCheck()),e.report(a.length)}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:Zn(De.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)&&dt.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,a]of[["case-id","id"],["case-title","title"]]){const d=this.input(o);d!==t&&(d.value=String(e.json[a]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),s=this.items(e);i.replaceChildren(...s.map((o,a)=>new Option(this.optionLabel(o,a),String(a))));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&&ae.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{duplicateIds:t,unresolved:i}=e.problems(),s=[...t.map(r=>this.messages.idDuplicated.replace("{id}",r)),...i.map(({reference:r})=>this.messages.readingUnresolved.replace("{id}",r))],n=this.byId("case-problems");n.hidden=s.length===0,n.textContent=s.join(" ")}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??=a=>{const d=a.composedPath();(a instanceof KeyboardEvent?a.key==="Escape":!d.includes(this.dialog)&&!d.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 T(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CGVsMdje.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(ne.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 a=(i?this.input("title").value:n).trim(),d=a!==""?a:this.said.read(o.observer?.title),l=this.input("author").value.trim(),h=e.addObservation(o,r!==""?r:void 0,d,i?{account:i,by:l!==""?[{title:l}]: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 et.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 s of t.tracks)await this.loadTrack(s)}catch{return!1}const i=await this.archive(e);return t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),this.download(i.blob,i.name),!0}async archive(e){const t=this.session,i=t.files(e,!0),s=e?t.attachments():[];if(i.length===1&&s.length===0)return{blob:new Blob([i[0].content],{type:"application/json"}),name:i[0].path};const{zipSync:n,strToU8:r}=await T(async()=>{const{zipSync:a,strToU8:d}=await import("./browser-CltifEM0.js");return{zipSync:a,strToU8:d}},[],import.meta.url),o={};for(const a of i)o[a.path]=r(a.content);for(const a of s)o[a.path]=new Uint8Array(await a.blob.arrayBuffer());return{blob:new Blob([n(o)],{type:"application/zip"}),name:`${t.json.id??"case"}.zip`}}async sendCase(e){const t=this.session;if(!t)return;this.commit();let i;try{for(const a of t.tracks)await this.loadTrack(a);i=await this.archive(!0)}catch(a){e.report("failed",a instanceof Error?a.message:String(a));return}const s=new File([i.blob],i.name,{type:i.blob.type}),n=e.body.replaceAll("{file}",i.name),r=navigator;if(typeof r.share=="function"&&r.canShare?.({files:[s]}))try{await r.share({files:[s],title:e.subject,text:n}),e.report("shared",i.name);return}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return}this.download(i.blob,i.name);const o=document.createElement("a");o.href=`mailto:${e.email?encodeURIComponent(e.email).replace("%40","@"):""}?subject=${encodeURIComponent(e.subject)}&body=${encodeURIComponent(`${n}
3174
3174
 
3175
3175
  ${e.attach.replaceAll("{file}",i.name)}`)}`,o.click(),e.report("prepared",i.name)}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}}function Eo(){Ks(),customElements.get(ki)||customElements.define(ki,De)}const No=Object.freeze(Object.defineProperty({__proto__:null,CASE_EDITOR_ELEMENT_NAME:ki,CaseEditorElement:De,register:Eo},Symbol.toStringTag,{value:"Module"}));export{B as C,Ce as I,xs as M,J as Q,xt as S,hs as a,No as b};