@rr0/ufoathome 0.198.1 → 0.199.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist-embed-scene/rr0-scene.mjs +4 -4
  2. package/dist-embed-sighting/CaseMessages_en-BC0lku35.js +1 -0
  3. package/dist-embed-sighting/CaseMessages_es-Cbktn5vj.js +1 -0
  4. package/dist-embed-sighting/CaseMessages_fr-D_6J6ONO.js +1 -0
  5. package/dist-embed-sighting/CaseMessages_it-CYyww4oG.js +1 -0
  6. package/dist-embed-sighting/{CaseReportExport-BetcYOov.js → CaseReportExport-CAuwP-Ec.js} +1 -1
  7. package/dist-embed-sighting/rr0-sighting.mjs +70 -59
  8. package/dist-embed-sighting-editor/{CaseEditorMessages_en-CpJLWbJD.js → CaseEditorMessages_en-pog3M_U6.js} +1 -1
  9. package/{dist-embed-ufoathome/CaseEditorMessages_es-C5YOqVpF.js → dist-embed-sighting-editor/CaseEditorMessages_es-Dz1N0VpM.js} +1 -1
  10. package/{dist-embed-ufoathome/CaseEditorMessages_fr-rMlMgrqV.js → dist-embed-sighting-editor/CaseEditorMessages_fr-BOKVeIXM.js} +1 -1
  11. package/{dist-embed-ufoathome/CaseEditorMessages_it-Bkiv2Hun.js → dist-embed-sighting-editor/CaseEditorMessages_it-BKAkbKq-.js} +1 -1
  12. package/dist-embed-sighting-editor/CaseElement--JmpOsUW.js +131 -0
  13. package/dist-embed-sighting-editor/CaseMessages_en-BC0lku35.js +1 -0
  14. package/dist-embed-sighting-editor/CaseMessages_es-Cbktn5vj.js +1 -0
  15. package/dist-embed-sighting-editor/CaseMessages_fr-D_6J6ONO.js +1 -0
  16. package/dist-embed-sighting-editor/CaseMessages_it-CYyww4oG.js +1 -0
  17. package/dist-embed-sighting-editor/{CaseReportExport-U-dk4A7z.js → CaseReportExport-nFM_7lq4.js} +1 -1
  18. package/dist-embed-sighting-editor/{SightingElement-BhyoU_gg.js → SightingElement-DsR4mBCh.js} +1 -1
  19. package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +123 -111
  20. package/dist-embed-ufoathome/{AdsbLolArchiveProvider-CUkfGJbL.js → AdsbLolArchiveProvider-B9MGq-iQ.js} +1 -1
  21. package/dist-embed-ufoathome/{BallesterGuaspAssessor-CB2F8A6P.js → BallesterGuaspAssessor-BehuINgj.js} +1 -1
  22. package/dist-embed-ufoathome/{BeamEditor-Q_m3KK0S.js → BeamEditor-CFYAfywp.js} +1 -1
  23. package/dist-embed-ufoathome/{BeamSystem-CVMU5DeE.js → BeamSystem-Bt5Dnpzy.js} +1 -1
  24. package/dist-embed-ufoathome/{BodyEditor-BwsMj37A.js → BodyEditor-B96fap0d.js} +1 -1
  25. package/dist-embed-ufoathome/{CaseEditorElement-BrcX9sp0.js → CaseEditorElement-D-RKShTH.js} +88 -77
  26. package/dist-embed-ufoathome/{CaseEditorMessages_en-CpJLWbJD.js → CaseEditorMessages_en-pog3M_U6.js} +1 -1
  27. package/{dist-embed-sighting-editor/CaseEditorMessages_es-C5YOqVpF.js → dist-embed-ufoathome/CaseEditorMessages_es-Dz1N0VpM.js} +1 -1
  28. package/{dist-embed-sighting-editor/CaseEditorMessages_fr-rMlMgrqV.js → dist-embed-ufoathome/CaseEditorMessages_fr-BOKVeIXM.js} +1 -1
  29. package/{dist-embed-sighting-editor/CaseEditorMessages_it-Bkiv2Hun.js → dist-embed-ufoathome/CaseEditorMessages_it-BKAkbKq-.js} +1 -1
  30. package/dist-embed-ufoathome/CaseElement-BFDRYL5v.js +131 -0
  31. package/dist-embed-ufoathome/CaseMessages_en-BC0lku35.js +1 -0
  32. package/dist-embed-ufoathome/CaseMessages_es-Cbktn5vj.js +1 -0
  33. package/dist-embed-ufoathome/CaseMessages_fr-D_6J6ONO.js +1 -0
  34. package/dist-embed-ufoathome/CaseMessages_it-CYyww4oG.js +1 -0
  35. package/dist-embed-ufoathome/{CaseReportExport--IhmS67e.js → CaseReportExport-VrulN0VG.js} +3 -3
  36. package/dist-embed-ufoathome/{ColumnResize-CMfGWQHi.js → ColumnResize-DD0wwlp2.js} +7 -6
  37. package/dist-embed-ufoathome/{ContrailSystem-CuFduINP.js → ContrailSystem-BKeTHlcZ.js} +1 -1
  38. package/dist-embed-ufoathome/{ControlPasses-BS7yyZOR.js → ControlPasses-D3vc-NmG.js} +1 -1
  39. package/dist-embed-ufoathome/{CoverageAssessor-BwXJv4OD.js → CoverageAssessor-Be38W7Im.js} +1 -1
  40. package/dist-embed-ufoathome/{Flightradar24Provider-Cd4o260r.js → Flightradar24Provider-DdPjGVJg.js} +1 -1
  41. package/dist-embed-ufoathome/{GLTFLoader-BegH9SUA.js → GLTFLoader-D1_vI_Fe.js} +1 -1
  42. package/dist-embed-ufoathome/{GeoJsonExport-Czm1iAIW.js → GeoJsonExport-B2qogWLj.js} +1 -1
  43. package/dist-embed-ufoathome/{GeographicFigures-CKg7JYgf.js → GeographicFigures-Ds8kfyn7.js} +1 -1
  44. package/dist-embed-ufoathome/{HeadlightSystem-DIk-C7_5.js → HeadlightSystem-BdhHphIq.js} +1 -1
  45. package/dist-embed-ufoathome/{HynekAssessor-BybLMdda.js → HynekAssessor-MqnQfg3F.js} +1 -1
  46. package/dist-embed-ufoathome/{InterviewEditorElement-CbTakhyi.js → InterviewEditorElement-DjQuGytO.js} +1 -1
  47. package/dist-embed-ufoathome/{InterviewElement-fI19BieO.js → InterviewElement-BrlawcDm.js} +1 -1
  48. package/dist-embed-ufoathome/{KmlExport-De-2dnYz.js → KmlExport-AzofE76s.js} +1 -1
  49. package/dist-embed-ufoathome/{LaserBeam-CouNB7Pe.js → LaserBeam-Ced8VujI.js} +1 -1
  50. package/dist-embed-ufoathome/{LaunchEditor-BNInX90c.js → LaunchEditor-D-5OJi90.js} +1 -1
  51. package/dist-embed-ufoathome/{LaunchPlume-DVxzb0wy.js → LaunchPlume-DdeLDyDg.js} +1 -1
  52. package/dist-embed-ufoathome/{LaunchSimulation-CCvSd6qD.js → LaunchSimulation-BeCHjgE5.js} +1 -1
  53. package/dist-embed-ufoathome/{ModelSource-BZ1U1VU1.js → ModelSource-LY5T91ay.js} +1 -1
  54. package/dist-embed-ufoathome/{ModelThumbnails-Ckdb3qoW.js → ModelThumbnails-C25E4WMl.js} +1 -1
  55. package/dist-embed-ufoathome/{ModelViewer-B9PZN5c7.js → ModelViewer-D6JaOQS7.js} +1 -1
  56. package/dist-embed-ufoathome/{ModuleConformance-8JN5JVgE.js → ModuleConformance-DGjaEwAM.js} +2 -2
  57. package/dist-embed-ufoathome/{ModuleSession-ClSpEZMn.js → ModuleSession-pXE1aOJF.js} +3 -3
  58. package/dist-embed-ufoathome/{ModuleThree-CRG8PTLA.js → ModuleThree-xQDeVLs0.js} +1 -1
  59. package/dist-embed-ufoathome/{ModulesPanelElement-D4Hos-mF.js → ModulesPanelElement-Bio6lzC6.js} +3 -3
  60. package/dist-embed-ufoathome/{NearestApproach-DrJN7h_1.js → NearestApproach-DAiByBN2.js} +1 -1
  61. package/dist-embed-ufoathome/{PictureRegistration-LxhNTA4v.js → PictureRegistration-Dbr0O7NF.js} +1 -1
  62. package/dist-embed-ufoathome/{PoherAssessor-RyKMyps7.js → PoherAssessor-C7NN73NP.js} +1 -1
  63. package/dist-embed-ufoathome/{RailwaySystem-BOQvJ2r4.js → RailwaySystem-D3u3j_tw.js} +1 -1
  64. package/dist-embed-ufoathome/{ReentryEditor-B1H_TUMf.js → ReentryEditor-s-AkSgbU.js} +1 -1
  65. package/dist-embed-ufoathome/{ReentrySimulation-C7XZlAED.js → ReentrySimulation-2UWwXU7K.js} +1 -1
  66. package/dist-embed-ufoathome/{ReferenceSystem-BcsjHgaw.js → ReferenceSystem-BhEFpIis.js} +1 -1
  67. package/dist-embed-ufoathome/{ShareDialogElement-DHlxoHWP.js → ShareDialogElement-C9Uiwt0F.js} +11 -11
  68. package/dist-embed-ufoathome/{SightingElement-COJwKNNg.js → SightingElement-DTADTDwh.js} +2 -2
  69. package/dist-embed-ufoathome/{TraceSystem-BBCpq8-v.js → TraceSystem-BcWYbjQM.js} +1 -1
  70. package/dist-embed-ufoathome/{VideoButton-CGQI7iUA.js → VideoButton-CgfBskVu.js} +1 -1
  71. package/dist-embed-ufoathome/{WaterSystem-BrIS0Wzy.js → WaterSystem-BsGtTimO.js} +1 -1
  72. package/dist-embed-ufoathome/rr0-ufoathome.mjs +3 -3
  73. package/dist-embed-ufoathome/{surroundingsSources-Dg6vMWL7.js → surroundingsSources-B--F7TR5.js} +1 -1
  74. package/dist-embed-ufoathome/{trafficRuntime-BT5Ol_v5.js → trafficRuntime-B97u9ZY_.js} +1 -1
  75. package/package.json +1 -1
  76. package/dist-embed-sighting/CaseMessages_en-G5J5w1_d.js +0 -1
  77. package/dist-embed-sighting/CaseMessages_es-D7Rp1_1K.js +0 -1
  78. package/dist-embed-sighting/CaseMessages_fr-B8eZ1NIJ.js +0 -1
  79. package/dist-embed-sighting/CaseMessages_it-Cu02nVVo.js +0 -1
  80. package/dist-embed-sighting-editor/CaseElement-IzaexO7n.js +0 -121
  81. package/dist-embed-sighting-editor/CaseMessages_en-G5J5w1_d.js +0 -1
  82. package/dist-embed-sighting-editor/CaseMessages_es-D7Rp1_1K.js +0 -1
  83. package/dist-embed-sighting-editor/CaseMessages_fr-B8eZ1NIJ.js +0 -1
  84. package/dist-embed-sighting-editor/CaseMessages_it-Cu02nVVo.js +0 -1
  85. package/dist-embed-ufoathome/CaseElement-Ca8ctACA.js +0 -121
  86. package/dist-embed-ufoathome/CaseMessages_en-G5J5w1_d.js +0 -1
  87. package/dist-embed-ufoathome/CaseMessages_es-D7Rp1_1K.js +0 -1
  88. package/dist-embed-ufoathome/CaseMessages_fr-B8eZ1NIJ.js +0 -1
  89. package/dist-embed-ufoathome/CaseMessages_it-Cu02nVVo.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DqGmxMZD.js","./rr0-ufoathome.mjs","./ModelThumbnails-Ckdb3qoW.js","./ShareDialogElement-DHlxoHWP.js","./SaidPosition-CXZLm-ck.js","./Sighting-Ch4eiBNK.js","./VisualAids-DI-hEL46.js","./Decor-Dn-cvniW.js","./RecordingIssue-BlWT8Xsu.js","./Obstacles-v9SkfBD7.js","./ModelSource-BZ1U1VU1.js","./ModelViewer-B9PZN5c7.js","./SightingFileEditor-Cllslp2u.js","./index-C8cdeM8E.js","./sightingSchema-CgwoRMl-.js","./surroundingsSources-Dg6vMWL7.js","./ModuleSession-ClSpEZMn.js","./ModulesPanelElement-D4Hos-mF.js","./ParameterForm-DcVFxrcO.js","./ColumnResize-CMfGWQHi.js","./TimelineTracks-BgZmkKhn.js","./ReentryArchive-CeXHrU7L.js","./ReferenceTimeline-2kBldQeG.js","./upperAirSources-BGuLpdwu.js","./Account-C4jhsVtN.js","./PictureRegistration-LxhNTA4v.js","./TraceImport-CntRHXoJ.js","./GeoExportTexts-3a51cuxQ.js","./KmlExport-De-2dnYz.js","./GeographicFigures-CKg7JYgf.js","./GeoJsonExport-Czm1iAIW.js","./BodyEditor-BwsMj37A.js","./GhostSearchView-Dlhj3xWa.js","./PictureFetch-C3wgf1ZV.js","./interviewJson-D-i14LTf.js","./InterviewEditorElement-CbTakhyi.js","./InterviewMedia-CvAxC62V.js","./InterviewElement-fI19BieO.js"])))=>i.map(i=>d[i]);
2
- import{C as se,F as We,H as ze,M as je,_ as L,d as _s,P as hi,e as he,f as Qe,g as F,h as X,i as H,r as Hs,I as Si,s as ci,U as ui,S as Xe,O as _e,j as Rt,k as $s,m as Ws,n as Dt,o as At,p as ks,b as js,c as Gs,q as gt,t as Ks,u as Vs,v as qs,R as Zs,w as Ys}from"./rr0-ufoathome.mjs";import{P as rt,I as M,g as Es,S as ut,l as Js}from"./SaidPosition-CXZLm-ck.js";import{E as fe,P as ot,a as Pt,r as wi,B as et,N as Bt,A as pi,b as xs,W as Fe,c as Ii}from"./ParameterForm-DcVFxrcO.js";import{C as $e,a as Be,c as Xs,I as Qs,b as en,R as tn}from"./ColumnResize-CMfGWQHi.js";import{H as Se,E as at,k as Ti,l as Ae,W as ee,s as be,m as V,n as sn,o as Mi,p as Kt,q as nn,t as Vt,u as Li,v as ue,w as q,x as mi,y as Di,D as Ss,a as Is,z as qt,F as rn,Z as on,N as pe,G as Je,I as Ai,J as Ci,K as an,L as Te,Q as Ts,U as Ct,V as Oi,X as U,Y as lt,_ as dt,$ as Ri,a0 as Pi,a1 as Bi,a2 as ln,a3 as dn,a4 as Ni,a5 as le,a6 as gi,a7 as Ms,a8 as Ls,a9 as hn,aa as Zt,b as cn,ab as un,ac as pn,ad as mn,ae as gn,af as fn,ag as Oe,ah as ft,A as fi,ai as bt,aj as bn,ak as vn,al as wn,am as Fi,an as Yt,ao as zi,ap as Ui,aq as ae,P as Jt,ar as Xt,as as Ve,i as yn,at as kn,au as vt,av as En,aw as _i,ax as Hi,ay as $i,az as Wi,aA as it,g as ji,e as Gi,aB as xn,aC as Ki,aD as Vi,aE as Qt,aF as ei,aG as qi,aH as Zi,aI as Sn,aJ as qe,aK as Yi,aL as wt,aM as ti,f as Ji,aN as ii,aO as J,aP as In,aQ as Xi,r as Tn,S as Ds,c as Mn,d as Qi,B as Ln,h as Dn,R as An}from"./ShareDialogElement-DHlxoHWP.js";import{K as Cn,r as Ot,a as bi,b as re,c as Q,A as ge,m as As,d as On,e as Rn,D as we,s as Nt,I as ye,S as Pn,f as Bn,g as Nn,h as Fn,i as es,j as zn,k as Un,p as _n}from"./Sighting-Ch4eiBNK.js";import{T as yi}from"./TimelineTracks-BgZmkKhn.js";import{H as Hn,o as $n,D as Cs,h as Wn,d as Os,a as jn,b as ts,r as is,c as ss}from"./Decor-Dn-cvniW.js";import{R as Gn}from"./ReentryArchive-CeXHrU7L.js";import{R as Re}from"./ReferenceTimeline-2kBldQeG.js";import{U as Kn}from"./upperAirSources-BGuLpdwu.js";import{S as Vn}from"./Account-C4jhsVtN.js";class de{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===se.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:se.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},a=new de(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===se.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),o=e?e.event.id??this.proposedId(e):"case";let a=1;for(;r.has(`interview-${o}-${a}`);)a++;const d={type:"event",eventType:se.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}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&&de.sealed(e.event)||(t=We.recording(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title))}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===se.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,o=n.interpretationOf===void 0?"observer":"reading",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===se.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===se.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(!de.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 se.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),o=new Set(this.tracks.map(A=>A.event.url)),a=new Set(this.tracks.map(A=>A.recording?.id));let d=this.tracks.filter(A=>A.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:I,interpretation:x,...y}=structuredClone(n),S={version:4,id:`${n.id??r}-interpretation-${d}`,...y,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},O={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??[],O],this.caseChanged=!0;const N={event:O,url:new URL(O.url,this.url).href,kind:"reading",recording:S};return this.tracks.push(N),N}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(de.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"||de.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)+`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DqGmxMZD.js","./rr0-ufoathome.mjs","./ModelThumbnails-C25E4WMl.js","./ShareDialogElement-C9Uiwt0F.js","./SaidPosition-CXZLm-ck.js","./Sighting-Ch4eiBNK.js","./VisualAids-DI-hEL46.js","./Decor-Dn-cvniW.js","./RecordingIssue-BlWT8Xsu.js","./Obstacles-v9SkfBD7.js","./ModelSource-LY5T91ay.js","./ModelViewer-D6JaOQS7.js","./SightingFileEditor-Cllslp2u.js","./index-C8cdeM8E.js","./sightingSchema-CgwoRMl-.js","./surroundingsSources-B--F7TR5.js","./ModuleSession-pXE1aOJF.js","./ModulesPanelElement-Bio6lzC6.js","./ParameterForm-DcVFxrcO.js","./ColumnResize-DD0wwlp2.js","./TimelineTracks-BgZmkKhn.js","./ReentryArchive-CeXHrU7L.js","./ReferenceTimeline-2kBldQeG.js","./upperAirSources-BGuLpdwu.js","./Account-C4jhsVtN.js","./PictureRegistration-Dbr0O7NF.js","./TraceImport-CntRHXoJ.js","./GeoExportTexts-3a51cuxQ.js","./KmlExport-AzofE76s.js","./GeographicFigures-Ds8kfyn7.js","./GeoJsonExport-B2qogWLj.js","./BodyEditor-B96fap0d.js","./GhostSearchView-Dlhj3xWa.js","./PictureFetch-C3wgf1ZV.js","./interviewJson-D-i14LTf.js","./InterviewEditorElement-DjQuGytO.js","./InterviewMedia-CvAxC62V.js","./InterviewElement-BrlawcDm.js"])))=>i.map(i=>d[i]);
2
+ import{C as se,F as je,H as ze,M as Ge,_ as D,d as _s,P as hi,e as he,f as He,g as F,h as Q,i as $,r as $s,I as Si,s as ci,U as ui,S as Qe,O as _e,j as Rt,k as Hs,m as Ws,n as Dt,o as At,p as ks,b as js,c as Gs,q as gt,t as Ks,u as Vs,v as qs,R as Zs,w as Ys}from"./rr0-ufoathome.mjs";import{P as rt,I as L,g as Es,S as ut,l as Js}from"./SaidPosition-CXZLm-ck.js";import{E as fe,P as ot,a as Pt,r as wi,B as et,N as Bt,A as pi,b as xs,W as Fe,c as Ii}from"./ParameterForm-DcVFxrcO.js";import{C as We,a as Be,c as Xs,I as Qs,b as en,R as tn}from"./ColumnResize-DD0wwlp2.js";import{H as Se,E as at,k as Ti,l as Ae,W as te,s as be,m as V,n as sn,o as Mi,p as Kt,q as nn,t as Vt,u as Li,v as ue,w as q,x as mi,y as Di,D as Ss,a as Is,z as qt,F as rn,Z as on,N as pe,G as Xe,I as Ai,J as Ci,K as an,L as Te,Q as Ts,U as Ct,V as Oi,X as U,Y as lt,_ as dt,$ as Ri,a0 as Pi,a1 as Bi,a2 as ln,a3 as dn,a4 as Ni,a5 as le,a6 as gi,a7 as Ms,a8 as Ls,a9 as hn,aa as Zt,b as cn,ab as un,ac as pn,ad as mn,ae as gn,af as fn,ag as Oe,ah as ft,A as fi,ai as bt,aj as bn,ak as vn,al as wn,am as Fi,an as Yt,ao as zi,ap as Ui,aq as ae,P as Jt,ar as Xt,as as qe,i as yn,at as kn,au as vt,av as En,aw as _i,ax as $i,ay as Hi,az as Wi,aA as it,g as ji,e as Gi,aB as xn,aC as Ki,aD as Vi,aE as Qt,aF as ei,aG as qi,aH as Zi,aI as Sn,aJ as Ze,aK as Yi,aL as wt,aM as ti,f as Ji,aN as ii,aO as X,aP as In,aQ as Xi,r as Tn,S as Ds,c as Mn,d as Qi,B as Ln,h as Dn,R as An}from"./ShareDialogElement-C9Uiwt0F.js";import{K as Cn,r as Ot,a as bi,b as re,c as ee,A as ge,m as As,d as On,e as Rn,D as we,s as Nt,I as ye,S as Pn,f as Bn,g as Nn,h as Fn,i as es,j as zn,k as Un,p as _n}from"./Sighting-Ch4eiBNK.js";import{T as yi}from"./TimelineTracks-BgZmkKhn.js";import{H as $n,o as Hn,D as Cs,h as Wn,d as Os,a as jn,b as ts,r as is,c as ss}from"./Decor-Dn-cvniW.js";import{R as Gn}from"./ReentryArchive-CeXHrU7L.js";import{R as Re}from"./ReferenceTimeline-2kBldQeG.js";import{U as Kn}from"./upperAirSources-BGuLpdwu.js";import{S as Vn}from"./Account-C4jhsVtN.js";class de{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===se.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:se.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},a=new de(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===se.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),o=e?e.event.id??this.proposedId(e):"case";let a=1;for(;r.has(`interview-${o}-${a}`);)a++;const d={type:"event",eventType:se.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}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&&de.sealed(e.event)||(t=je.recording(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title))}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===se.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,o=n.interpretationOf===void 0?"observer":"reading",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===se.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===se.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(!de.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 se.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),o=new Set(this.tracks.map(T=>T.event.url)),a=new Set(this.tracks.map(T=>T.recording?.id));let d=this.tracks.filter(T=>T.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:E,interpretation:x,...S}=structuredClone(n),I={version:4,id:`${n.id??r}-interpretation-${d}`,...S,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(de.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"||de.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)+`
3
3
  `})),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)+`
4
4
  `},...n,...o]}}const Ft="rr0-date-input",qn=`
5
5
  rr0-date-input { position: relative; display: inline-flex; align-items: center; gap: .3em; }
@@ -19,7 +19,7 @@ rr0-date-input .edtf-mode:focus-visible { outline: 2px solid #4af; outline-offse
19
19
  rr0-date-input [hidden] { display: none !important; }
20
20
  ${Se.css("rr0-date-input .edtf-helppop")}
21
21
  `;class Zn extends HTMLElement{dateField;shown;wording;helpPopup;build(){if(this.dateField)return;const e=this.getAttribute("name"),t=this.ownerDocument,i=t.createElement("style");i.textContent=qn;const s=t.createElement("span");s.className="edtf-field";const n=t.createElement("input");n.type=this.hasAttribute("date-only")?"date":"datetime-local",n.type!=="date"&&(n.step="60");const r=t.createElement("input");r.type="text",r.hidden=!0;const o=t.createElement("button");o.type="button",o.className="edtf-help",o.textContent="?",o.hidden=!0;const a=t.createElement("div");a.className="edtf-helppop",Se.attach(o,a),this.helpPopup=a,e&&(n.id=`${e}-native`,r.id=e),s.append(n,r,o,a);const d=t.createElement("button");d.type="button",d.className="edtf-mode",this.append(i,s,d),this.dateField=new at({picker:n,text:r,mode:d,help:o},this.wording,l=>this.dispatchEvent(new CustomEvent("datechange",{detail:{time:l},bubbles:!0,composed:!0})),ze.preferencesFor(this)[0]??"en"),o.addEventListener("click",()=>this.toggleHelp()),d.addEventListener("click",()=>this.focus()),this.shown=void 0,this.fillHelp()}connectedCallback(){this.build(),this.holder=this.parentElement?.tagName==="LABEL"?void 0:this.parentElement??void 0,this.holder?.addEventListener("click",this.focusFromLabel),document.addEventListener("pointerdown",this.closeHelpOutside,!0),document.addEventListener("keydown",this.closeHelpOnEscape,!0)}disconnectedCallback(){this.holder?.removeEventListener("click",this.focusFromLabel),this.holder=void 0,document.removeEventListener("pointerdown",this.closeHelpOutside,!0),document.removeEventListener("keydown",this.closeHelpOnEscape,!0)}holder;focusFromLabel=e=>{const t=e.target;!t||this.contains(t)||t.closest("input, select, textarea, button, a, [tabindex], rr0-date-input")!==null||this.focus()};focus(e){this.querySelector(".edtf-field > input:not([hidden])")?.focus(e)}closeHelpOutside=e=>{this.helpPopup&&!this.helpPopup.hidden&&!e.composedPath().includes(this)&&Se.show(this.helpPopup,!1)};closeHelpOnEscape=e=>{e.key==="Escape"&&this.helpPopup&&Se.show(this.helpPopup,!1)};toggleHelp(){this.helpPopup&&Se.show(this.helpPopup,this.helpPopup.hidden)}fillHelp(){const e=this.helpPopup;if(!e||!this.wording)return;const t=this.ownerDocument.createElement("p");t.textContent=this.wording.dateHelpTitle;const i=this.ownerDocument.createElement("ul");for(const s of this.wording.dateHelpLines.split(`
22
- `)){const n=this.ownerDocument.createElement("li");n.textContent=s,i.append(n)}e.replaceChildren(t,i)}set hint(e){this.field.setHint(e)}get field(){return this.build(),this.dateField}get time(){return this.shown}set time(e){this.shown=e,this.field.set(e)}setBounds(e){this.field.setBounds(e)}get precise(){return this.field.isPrecise}setPrecise(e){this.field.setPrecise(e)}set messages(e){this.wording=e,this.dateField&&(this.dateField.setMessages(e,ze.preferencesFor(this)[0]??"en"),this.fillHelp())}}function Rs(){customElements.get(Ft)||customElements.define(Ft,Zn)}class ns{static of(e,t="whole",i){if(t==="whole"||!e.timeline?.keyframes?.length)return JSON.stringify(e,null,2);const s=Cn.thin(e.timeline.keyframes,i);return JSON.stringify({...e,timeline:{...e.timeline,keyframes:s}},null,2)}}function Yn(E,e,t,i,s,n){Ps(E,e,t,r=>r.map(o=>o.id===i?s(o):o),n)}function Ps(E,e,t,i,s){const n=r=>{const o=i(Ot(r)),a=m=>1-o.filter(f=>f.type==="cirrus"===m).reduce((f,g)=>f*(1-g.coverage),1),d=a(!1),l=a(!0),h=o.filter(m=>m.coverage>0&&m.type!=="cirrus").map(m=>m.baseM),c=o.filter(m=>m.coverage>0||(m.instances?.length??0)>0),u=c.length?Math.max(...c.flatMap(m=>[m.darkness??r.cloudDarkness,...(m.instances??[]).map(f=>f.darkness??m.darkness??r.cloudDarkness)])):0,p=o.filter(m=>m.type==="cirrus"&&m.coverage>0).sort((m,f)=>f.coverage-m.coverage)[0];return{...r,cloudLayers:o,lowerCloudCover:d,highCloudCover:l,cloudDarkness:u,iceCrystalAlignment:p?.iceCrystalAlignment,cloudCover:1-(1-d)*(1-l),cloudBaseM:h.length?Math.min(...h):void 0}};if(s==="instant"||E.allKeyframes.length===0)E.addKeyframe(s==="observation"?0:t,n(E.getInterpolatedWeatherAt(t)??e));else for(const r of[...E.allKeyframes])E.addKeyframe(r.t,n(r.weather))}function Jn(E,e,t){const i=(o,a)=>o.x*a.x+o.y*a.y+o.z*a.z,s=i(t,E),n=i(e,E);if(s<=0||n<=.05)return;const r=s/n;return{x:e.x*r-E.x*s,y:e.y*r-E.y*s,z:e.z*r-E.z*s}}class rs{static html(){const e=je.none(),t=i=>`<span data-text="${i}">${e[i]}</span>`;return`<div class="cloud-panel">
22
+ `)){const n=this.ownerDocument.createElement("li");n.textContent=s,i.append(n)}e.replaceChildren(t,i)}set hint(e){this.field.setHint(e)}get field(){return this.build(),this.dateField}get time(){return this.shown}set time(e){this.shown=e,this.field.set(e)}setBounds(e){this.field.setBounds(e)}get precise(){return this.field.isPrecise}setPrecise(e){this.field.setPrecise(e)}set messages(e){this.wording=e,this.dateField&&(this.dateField.setMessages(e,ze.preferencesFor(this)[0]??"en"),this.fillHelp())}}function Rs(){customElements.get(Ft)||customElements.define(Ft,Zn)}class ns{static of(e,t="whole",i){if(t==="whole"||!e.timeline?.keyframes?.length)return JSON.stringify(e,null,2);const s=Cn.thin(e.timeline.keyframes,i);return JSON.stringify({...e,timeline:{...e.timeline,keyframes:s}},null,2)}}function Yn(k,e,t,i,s,n){Ps(k,e,t,r=>r.map(o=>o.id===i?s(o):o),n)}function Ps(k,e,t,i,s){const n=r=>{const o=i(Ot(r)),a=m=>1-o.filter(f=>f.type==="cirrus"===m).reduce((f,g)=>f*(1-g.coverage),1),d=a(!1),l=a(!0),h=o.filter(m=>m.coverage>0&&m.type!=="cirrus").map(m=>m.baseM),c=o.filter(m=>m.coverage>0||(m.instances?.length??0)>0),u=c.length?Math.max(...c.flatMap(m=>[m.darkness??r.cloudDarkness,...(m.instances??[]).map(f=>f.darkness??m.darkness??r.cloudDarkness)])):0,p=o.filter(m=>m.type==="cirrus"&&m.coverage>0).sort((m,f)=>f.coverage-m.coverage)[0];return{...r,cloudLayers:o,lowerCloudCover:d,highCloudCover:l,cloudDarkness:u,iceCrystalAlignment:p?.iceCrystalAlignment,cloudCover:1-(1-d)*(1-l),cloudBaseM:h.length?Math.min(...h):void 0}};if(s==="instant"||k.allKeyframes.length===0)k.addKeyframe(s==="observation"?0:t,n(k.getInterpolatedWeatherAt(t)??e));else for(const r of[...k.allKeyframes])k.addKeyframe(r.t,n(r.weather))}function Jn(k,e,t){const i=(o,a)=>o.x*a.x+o.y*a.y+o.z*a.z,s=i(t,k),n=i(e,k);if(s<=0||n<=.05)return;const r=s/n;return{x:e.x*r-k.x*s,y:e.y*r-k.y*s,z:e.z*r-k.z*s}}class rs{static html(){const e=Ge.none(),t=i=>`<span data-text="${i}">${e[i]}</span>`;return`<div class="cloud-panel">
23
23
  <p data-text="intro">${e.intro}</p>
24
24
  <div class="cloud-fields">
25
25
  <label>${t("editScope")}<select id="cloud-scope"><option value="instant" data-text="scopeInstant">${e.scopeInstant}</option><option value="observation" data-text="scopeObservation">${e.scopeObservation}</option></select></label>
@@ -32,21 +32,21 @@ ${Se.css("rr0-date-input .edtf-helppop")}
32
32
  <label><input id="cloud-manipulate" type="checkbox">${t("manipulate")}</label>
33
33
  <div id="cloud-instance-parameters" class="cloud-parameters"></div>
34
34
  </div><p data-text="individualHelp">${e.individualHelp}</p></details>
35
- <p id="cloud-status" role="status"></p></div>`}static localize(e,t){for(const i of e.querySelectorAll("[data-text]"))i.textContent=t[i.dataset.text]}}const Xn=je.catalog({en:()=>L(()=>import("./CloudParameterTexts_en-NIa0gfgA.js"),[],import.meta.url).then(E=>E.cloudParameterTexts_en),fr:()=>L(()=>import("./CloudParameterTexts_fr-Bv-jc2dq.js"),[],import.meta.url).then(E=>E.cloudParameterTexts_fr),es:()=>L(()=>import("./CloudParameterTexts_es-DXu4T30p.js"),[],import.meta.url).then(E=>E.cloudParameterTexts_es),it:()=>L(()=>import("./CloudParameterTexts_it-C3RrkRwI.js"),[],import.meta.url).then(E=>E.cloudParameterTexts_it)});class B{static METRES="m";static number(e,t,i,s,n,r={}){return{type:"number",key:e,label:t,min:i,max:s,step:n,...r}}static LAYER={kind:"cloud-layer",title:"cloudLayer",parameters:[{type:"choice",key:"type",required:!0,label:"cloudType",choices:[{value:"cumulus",label:"cumulus"},{value:"stratus",label:"stratus"},{value:"stratocumulus",label:"stratocumulus"},{value:"cirrus",label:"cirrus"},{value:"unknown",label:"unknown"}]},B.number("baseM","base",0,2e4,1,{unit:B.METRES,required:!0}),B.number("thicknessM","thickness",10,8e3,1,{unit:B.METRES,required:!0}),B.number("coverage","coverage",0,100,1,{unit:"%",scale:100,required:!0}),B.number("sizeM","cloudSize",50,2e4,10,{unit:B.METRES,required:!0}),B.number("density","density",0,2,.01,{required:!0}),B.number("darkness","darkness",0,1,.01,{effective:(e,t)=>t?.generalDarkness}),B.number("iceCrystalAlignment","crystalAlignment",0,1,.01,{visibleWhen:e=>e.type==="cirrus",effective:()=>bi}),B.number("windDirectionDeg","layerWindDirection",0,360,.1,{unit:"°",placeholder:"generalWind"}),B.number("windSpeed","layerWindSpeed",0,120,.01,{unit:"m/s",placeholder:"generalWind"}),B.number("seed","patternSeed",0,9999,1)]};static INSTANCE={kind:"cloud-instance",title:"individualCloud",parameters:[{type:"position",key:"eastM",secondKey:"northM",saidKey:"saidPosition",native:"local",step:1,label:"position"},B.number("baseM","cloudBase",0,2e4,1,{unit:B.METRES,required:!0}),B.number("thicknessM","cloudThickness",10,8e3,1,{unit:B.METRES,required:!0}),B.number("widthM","cloudWidth",50,2e4,10,{unit:B.METRES,required:!0}),B.number("depthM","cloudDepth",50,2e4,10,{unit:B.METRES,required:!0}),B.number("rotationDeg","cloudRotation",-360,360,1,{unit:"°",required:!0}),B.number("density","cloudDensity",0,2,.01,{required:!0}),B.number("darkness","darkness",0,1,.01,{placeholder:"layerDarkness"})]}}function Qn(E,e,t,i,s="en",n){let r=je.none();E.innerHTML=rs.html();const o=k=>E.querySelector("#"+k),a={},d=new fe({header:E.querySelector("#cloud-layer-list"),body:E.querySelector("#cloud-layer-parameters"),ids:{list:"cloud-layer",remove:"cloud-layer-delete",add:"cloud-layer-add"},onSelect:()=>a.pickLayer(),onAdd:()=>a.addLayer(),onRemove:()=>a.removeLayer()}),l=new fe({header:E.querySelector("#cloud-instance-list"),body:E.querySelector("#cloud-instance-parameters"),ids:{list:"cloud-instance",remove:"cloud-instance-delete",add:"cloud-instance-add"},optional:!0,actions:[{id:"cloud-instance-point",glyph:"🎯",onClick:()=>a.pointAtCloud()}],onSelect:()=>a.pickCloud(),onAdd:()=>a.addCloud(),onRemove:()=>a.removeCloud()}),h=()=>{d.setLabels({list:r.layer,remove:r.deleteLayer,add:r.addLayer,empty:r.emptyLayers}),l.setLabels({list:r.individualCloud,remove:r.deleteCloud,add:r.addIndividualCloud,none:r.none,actions:{"cloud-instance-point":r.pointAtCloud}})};h();const c=E.querySelector("#cloud-status"),u=()=>o("cloud-scope").value,p=()=>{const k=Ot(re(e.ufoElement.sighting,e.ufoElement.currentTime));return k.find(T=>T.id===d.value)??k[0]},m=()=>p()?.instances?.find(k=>k.id===l.value),f=E.querySelector("#cloud-layer-parameters"),g=E.querySelector("#cloud-instance-parameters"),b=new ot(f,s,"cloudLayer."),v=new ot(g,s,"cloudInstance."),I=()=>{const k=m();g.hidden=!k,k&&v.sync()};let x=-1;const y=()=>{const k=e.ufoElement.currentTime,T=E.getRootNode().activeElement;if(k===x&&T instanceof HTMLInputElement&&E.contains(T))return;x=k;const D=Ot(re(e.ufoElement.sighting,e.ufoElement.currentTime));d.setItems(D.map((W,G)=>({id:W.id,label:`${G+1} · ${W.type} · ${Math.round(W.baseM)} m`})),d.value);const $=p();if(f.hidden=!$,!$){l.setItems([],""),I();return}b.sync();const Y=l.value;l.setItems(($.instances??[]).map((W,G)=>({id:W.id,label:`${r.cloud} ${G+1}`})),$.instances?.some(W=>W.id===Y)?Y:""),I()},S=(k,T=!0)=>{if(!p())return;e.ufoElement.pause(),t(T);const D=e.ufoElement.currentTime,$=e.ufoElement.sighting;Yn($.weatherTrack,re($,D),D,p().id,k,u()),e.ufoElement.refresh(),c.textContent=u()==="observation"?r.savedAcrossObservation:`${(D/1e3).toFixed(1)} s · ${r.savedAtThisTime}`},O=k=>{b.show(rt.resolve(B.LAYER,k),new Pt(()=>p(),(T,D)=>S($=>{const Y=structuredClone($);return T(Y),Y},D.key!=="iceCrystalAlignment"),()=>({generalDarkness:re(e.ufoElement.sighting,e.ufoElement.currentTime).cloudDarkness})),()=>{}),v.show(rt.resolve(B.INSTANCE,k),new Pt(()=>m(),T=>{const D=l.value;S($=>({...$,instances:$.instances?.map(Y=>{if(Y.id!==D)return Y;const W=structuredClone(Y);return T(W),W})}))},void 0,n),()=>{})};E.addEventListener("focusin",()=>e.ufoElement.pause()),a.pickLayer=()=>{l.show(""),y()},a.pickCloud=I;const N=k=>{e.ufoElement.pause(),t();const T=e.ufoElement.sighting,D=e.ufoElement.currentTime;Ps(T.weatherTrack,re(T,D),D,k,u()),e.ufoElement.refresh(),y()};a.addLayer=()=>{const k=re(e.ufoElement.sighting,e.ufoElement.currentTime),T={id:crypto.randomUUID(),type:"cumulus",baseM:1500,thicknessM:800,coverage:.5,sizeM:1400,density:1,darkness:k.cloudDarkness};N(D=>[...D,T]),d.show(T.id),y()},a.removeLayer=()=>{const k=p()?.id;k&&N(T=>T.filter(D=>D.id!==k))};const A=e.ufoElement.canvasElement,te=o("cloud-manipulate");let Z;const Ce=k=>{const T=A.getBoundingClientRect();return{x:(k.clientX-T.left)/T.width*2-1,y:1-(k.clientY-T.top)/T.height*2}};te.addEventListener("change",()=>{A.style.touchAction=te.checked?"none":"",A.style.cursor=te.checked?"crosshair":""}),A.addEventListener("click",k=>{te.checked&&(k.preventDefault(),k.stopImmediatePropagation())},!0),A.addEventListener("pointerdown",k=>{if(!te.checked||k.button!==0)return;k.preventDefault(),k.stopImmediatePropagation(),e.ufoElement.pause();const T=Ce(k),D=e.pickCloudAt(T.x,T.y);if(!D){c.textContent=r.noCloudHere;return}d.show(D.layerId),y(),l.show(D.instanceId),I();const Y=(u()==="observation"?e.ufoElement.sighting.weatherTrack.allKeyframes.map(W=>W.weather):[re(e.ufoElement.sighting,e.ufoElement.currentTime)]).flatMap(W=>Ot(W).filter(G=>G.id===D.layerId).flatMap(G=>(G.instances??[]).filter(Ie=>Ie.id===D.instanceId).map(Ie=>Ie.baseM)));Z={minBase:Math.min(...Y),pointerId:k.pointerId,id:D.instanceId,center:D.center,ray:e.cloudDirectionAt(T.x,T.y),delta:{x:0,y:0,z:0}},A.setPointerCapture(k.pointerId),A.style.cursor="grabbing",c.textContent=r.cloudSelected},!0),A.addEventListener("pointermove",k=>{if(!Z||k.pointerId!==Z.pointerId)return;k.preventDefault(),k.stopImmediatePropagation();const T=Ce(k),D=Jn(Z.ray,e.cloudDirectionAt(T.x,T.y),Z.center);if(!D)return;D.y=Math.max(D.y,-Z.minBase);const $=Z.delta,Y=Z.id;S(W=>({...W,instances:W.instances?.map(G=>G.id!==Y?G:{...G,eastM:G.eastM+D.x-$.x,northM:G.northM-D.z+$.z,baseM:G.baseM+D.y-$.y})})),Z.delta=D,I()},!0);const Ge=k=>{!Z||k.pointerId!==Z.pointerId||(Z=void 0,A.hasPointerCapture(k.pointerId)&&A.releasePointerCapture(k.pointerId),A.style.cursor=te.checked?"crosshair":"")};return A.addEventListener("pointerup",Ge),A.addEventListener("pointercancel",Ge),A.addEventListener("lostpointercapture",Ge),a.addCloud=()=>{const k=p();if(!k)return;const T=crypto.randomUUID(),D=e.ufoElement.sighting,$=e.ufoElement.currentTime,Y=Q(D,$),W=Ti($,D.weatherTrack,re(D,0),Q(D,0),Y,k.id),G=e.cloudDirectionAt(0,0),Ie=k.baseM+k.thicknessM*.4-(Y?.elevationM??0)-1.6,Ke=Ie*G.y>0?Math.max(500,Math.min(2e4,Ie/G.y)):5e3,pt={id:T,eastM:W.x+G.x*Ke,northM:-(W.z+G.z*Ke),baseM:k.baseM,thicknessM:k.thicknessM,widthM:1800,depthM:1200,rotationDeg:0,density:1,darkness:k.darkness};S(mt=>({...mt,instances:[...mt.instances??[],pt]})),y(),l.show(T),I(),c.textContent+=r.cloudAdded},a.removeCloud=()=>{const k=l.value;k&&(S(T=>({...T,instances:T.instances?.filter(D=>D.id!==k)})),y())},a.pointAtCloud=()=>{const k=p(),T=k?.instances?.find(mt=>mt.id===l.value);if(!T)return;e.ufoElement.pause();const D=e.ufoElement.sighting,$=e.ufoElement.currentTime,Y=Q(D,$),W=Ti($,D.weatherTrack,re(D,0),Q(D,0),Y,k.id),G=T.eastM-W.x,Ie=T.northM+W.z,Ke=Math.hypot(G,Ie),pt=T.baseM+T.thicknessM/2-(Y?.elevationM??0)-1.6-Ke**2/(2*6371e3);Ke===0&&pt===0||i((Math.atan2(G,Ie)*180/Math.PI+360)%360,Math.atan2(pt,Ke)*180/Math.PI)},Promise.all([_s.load(s),Xn.load(s)]).then(([k,T])=>{r=k,O(T),rs.localize(E,r),h(),x=-1,y()}),{sync:y,stopManipulation(){Z=void 0,te.checked=!1,A.style.touchAction="",A.style.cursor=""},reset(){Z=void 0,te.checked=!1,A.style.cursor="",A.style.touchAction="",l.show(""),x=-1,y()}}}class C{constructor(e){this.root=e;const t=i=>{const s=i.target?.closest?.(".section-title");return s&&C.sectionOf(s)?.hasAttribute("data-foldable")?s:void 0};e.addEventListener("click",i=>{const s=t(i);s&&!this.listedNow(C.sectionOf(s))&&this.unfold(C.sectionOf(s),!C.sectionOf(s).hasAttribute("data-unfolded"))}),e.addEventListener("keydown",i=>{const s=i.key;if(s!=="Enter"&&s!==" ")return;const n=t(i);!n||this.listedNow(C.sectionOf(n))||(i.preventDefault(),this.unfold(C.sectionOf(n),!C.sectionOf(n).hasAttribute("data-unfolded")))});for(const i of e.querySelectorAll(".form-section")){if(i.dataset.fold!=="all"&&!i.querySelector(".adv"))continue;const s=document.createElement("button");s.type="button",s.className="more-toggle",s.setAttribute("aria-expanded","false"),s.addEventListener("click",()=>this.setOpen(i,!i.hasAttribute("data-open")));const n=i.querySelector(":scope > .section-title");i.dataset.fold==="all"&&n?n.after(s):i.append(s),this.toggles.set(i,s)}if(typeof ResizeObserver<"u"){const i=new Map,s=new ResizeObserver(n=>{let r=!1;for(const o of n){const a=Math.round(o.contentRect.width);i.get(o.target)!==a&&(i.set(o.target,a),r=!0)}r&&this.refresh()});for(const n of this.toggles.keys())s.observe(n)}}static TITLED=".form-section[data-foldable]";static titles(e="",t=""){return[`${C.TITLED}${t} > .section-title${e}`,`${C.TITLED}${t} > .section-head > .section-title${e}`].join(", ")}static TITLES=C.titles();static CSS=`
36
- ${C.TITLED}:not([data-unfolded]) > :not(.section-title, .section-head) { display: none !important; }
35
+ <p id="cloud-status" role="status"></p></div>`}static localize(e,t){for(const i of e.querySelectorAll("[data-text]"))i.textContent=t[i.dataset.text]}}const Xn=Ge.catalog({en:()=>D(()=>import("./CloudParameterTexts_en-NIa0gfgA.js"),[],import.meta.url).then(k=>k.cloudParameterTexts_en),fr:()=>D(()=>import("./CloudParameterTexts_fr-Bv-jc2dq.js"),[],import.meta.url).then(k=>k.cloudParameterTexts_fr),es:()=>D(()=>import("./CloudParameterTexts_es-DXu4T30p.js"),[],import.meta.url).then(k=>k.cloudParameterTexts_es),it:()=>D(()=>import("./CloudParameterTexts_it-C3RrkRwI.js"),[],import.meta.url).then(k=>k.cloudParameterTexts_it)});class N{static METRES="m";static number(e,t,i,s,n,r={}){return{type:"number",key:e,label:t,min:i,max:s,step:n,...r}}static LAYER={kind:"cloud-layer",title:"cloudLayer",parameters:[{type:"choice",key:"type",required:!0,label:"cloudType",choices:[{value:"cumulus",label:"cumulus"},{value:"stratus",label:"stratus"},{value:"stratocumulus",label:"stratocumulus"},{value:"cirrus",label:"cirrus"},{value:"unknown",label:"unknown"}]},N.number("baseM","base",0,2e4,1,{unit:N.METRES,required:!0}),N.number("thicknessM","thickness",10,8e3,1,{unit:N.METRES,required:!0}),N.number("coverage","coverage",0,100,1,{unit:"%",scale:100,required:!0}),N.number("sizeM","cloudSize",50,2e4,10,{unit:N.METRES,required:!0}),N.number("density","density",0,2,.01,{required:!0}),N.number("darkness","darkness",0,1,.01,{effective:(e,t)=>t?.generalDarkness}),N.number("iceCrystalAlignment","crystalAlignment",0,1,.01,{visibleWhen:e=>e.type==="cirrus",effective:()=>bi}),N.number("windDirectionDeg","layerWindDirection",0,360,.1,{unit:"°",placeholder:"generalWind"}),N.number("windSpeed","layerWindSpeed",0,120,.01,{unit:"m/s",placeholder:"generalWind"}),N.number("seed","patternSeed",0,9999,1)]};static INSTANCE={kind:"cloud-instance",title:"individualCloud",parameters:[{type:"position",key:"eastM",secondKey:"northM",saidKey:"saidPosition",native:"local",step:1,label:"position"},N.number("baseM","cloudBase",0,2e4,1,{unit:N.METRES,required:!0}),N.number("thicknessM","cloudThickness",10,8e3,1,{unit:N.METRES,required:!0}),N.number("widthM","cloudWidth",50,2e4,10,{unit:N.METRES,required:!0}),N.number("depthM","cloudDepth",50,2e4,10,{unit:N.METRES,required:!0}),N.number("rotationDeg","cloudRotation",-360,360,1,{unit:"°",required:!0}),N.number("density","cloudDensity",0,2,.01,{required:!0}),N.number("darkness","darkness",0,1,.01,{placeholder:"layerDarkness"})]}}function Qn(k,e,t,i,s="en",n){let r=Ge.none();k.innerHTML=rs.html();const o=y=>k.querySelector("#"+y),a={},d=new fe({header:k.querySelector("#cloud-layer-list"),body:k.querySelector("#cloud-layer-parameters"),ids:{list:"cloud-layer",remove:"cloud-layer-delete",add:"cloud-layer-add"},onSelect:()=>a.pickLayer(),onAdd:()=>a.addLayer(),onRemove:()=>a.removeLayer()}),l=new fe({header:k.querySelector("#cloud-instance-list"),body:k.querySelector("#cloud-instance-parameters"),ids:{list:"cloud-instance",remove:"cloud-instance-delete",add:"cloud-instance-add"},optional:!0,actions:[{id:"cloud-instance-point",glyph:"🎯",onClick:()=>a.pointAtCloud()}],onSelect:()=>a.pickCloud(),onAdd:()=>a.addCloud(),onRemove:()=>a.removeCloud()}),h=()=>{d.setLabels({list:r.layer,remove:r.deleteLayer,add:r.addLayer,empty:r.emptyLayers}),l.setLabels({list:r.individualCloud,remove:r.deleteCloud,add:r.addIndividualCloud,none:r.none,actions:{"cloud-instance-point":r.pointAtCloud}})};h();const c=k.querySelector("#cloud-status"),u=()=>o("cloud-scope").value,p=()=>{const y=Ot(re(e.ufoElement.sighting,e.ufoElement.currentTime));return y.find(M=>M.id===d.value)??y[0]},m=()=>p()?.instances?.find(y=>y.id===l.value),f=k.querySelector("#cloud-layer-parameters"),g=k.querySelector("#cloud-instance-parameters"),b=new ot(f,s,"cloudLayer."),v=new ot(g,s,"cloudInstance."),E=()=>{const y=m();g.hidden=!y,y&&v.sync()};let x=-1;const S=()=>{const y=e.ufoElement.currentTime,M=k.getRootNode().activeElement;if(y===x&&M instanceof HTMLInputElement&&k.contains(M))return;x=y;const A=Ot(re(e.ufoElement.sighting,e.ufoElement.currentTime));d.setItems(A.map((W,G)=>({id:W.id,label:`${G+1} · ${W.type} · ${Math.round(W.baseM)} m`})),d.value);const H=p();if(f.hidden=!H,!H){l.setItems([],""),E();return}b.sync();const J=l.value;l.setItems((H.instances??[]).map((W,G)=>({id:W.id,label:`${r.cloud} ${G+1}`})),H.instances?.some(W=>W.id===J)?J:""),E()},I=(y,M=!0)=>{if(!p())return;e.ufoElement.pause(),t(M);const A=e.ufoElement.currentTime,H=e.ufoElement.sighting;Yn(H.weatherTrack,re(H,A),A,p().id,y,u()),e.ufoElement.refresh(),c.textContent=u()==="observation"?r.savedAcrossObservation:`${(A/1e3).toFixed(1)} s · ${r.savedAtThisTime}`},C=y=>{b.show(rt.resolve(N.LAYER,y),new Pt(()=>p(),(M,A)=>I(H=>{const J=structuredClone(H);return M(J),J},A.key!=="iceCrystalAlignment"),()=>({generalDarkness:re(e.ufoElement.sighting,e.ufoElement.currentTime).cloudDarkness})),()=>{}),v.show(rt.resolve(N.INSTANCE,y),new Pt(()=>m(),M=>{const A=l.value;I(H=>({...H,instances:H.instances?.map(J=>{if(J.id!==A)return J;const W=structuredClone(J);return M(W),W})}))},void 0,n),()=>{})};k.addEventListener("focusin",()=>e.ufoElement.pause()),a.pickLayer=()=>{l.show(""),S()},a.pickCloud=E;const R=y=>{e.ufoElement.pause(),t();const M=e.ufoElement.sighting,A=e.ufoElement.currentTime;Ps(M.weatherTrack,re(M,A),A,y,u()),e.ufoElement.refresh(),S()};a.addLayer=()=>{const y=re(e.ufoElement.sighting,e.ufoElement.currentTime),M={id:crypto.randomUUID(),type:"cumulus",baseM:1500,thicknessM:800,coverage:.5,sizeM:1400,density:1,darkness:y.cloudDarkness};R(A=>[...A,M]),d.show(M.id),S()},a.removeLayer=()=>{const y=p()?.id;y&&R(M=>M.filter(A=>A.id!==y))};const T=e.ufoElement.canvasElement,Z=o("cloud-manipulate");let Y;const Ce=y=>{const M=T.getBoundingClientRect();return{x:(y.clientX-M.left)/M.width*2-1,y:1-(y.clientY-M.top)/M.height*2}};Z.addEventListener("change",()=>{T.style.touchAction=Z.checked?"none":"",T.style.cursor=Z.checked?"crosshair":""}),T.addEventListener("click",y=>{Z.checked&&(y.preventDefault(),y.stopImmediatePropagation())},!0),T.addEventListener("pointerdown",y=>{if(!Z.checked||y.button!==0)return;y.preventDefault(),y.stopImmediatePropagation(),e.ufoElement.pause();const M=Ce(y),A=e.pickCloudAt(M.x,M.y);if(!A){c.textContent=r.noCloudHere;return}d.show(A.layerId),S(),l.show(A.instanceId),E();const J=(u()==="observation"?e.ufoElement.sighting.weatherTrack.allKeyframes.map(W=>W.weather):[re(e.ufoElement.sighting,e.ufoElement.currentTime)]).flatMap(W=>Ot(W).filter(G=>G.id===A.layerId).flatMap(G=>(G.instances??[]).filter(Ie=>Ie.id===A.instanceId).map(Ie=>Ie.baseM)));Y={minBase:Math.min(...J),pointerId:y.pointerId,id:A.instanceId,center:A.center,ray:e.cloudDirectionAt(M.x,M.y),delta:{x:0,y:0,z:0}},T.setPointerCapture(y.pointerId),T.style.cursor="grabbing",c.textContent=r.cloudSelected},!0),T.addEventListener("pointermove",y=>{if(!Y||y.pointerId!==Y.pointerId)return;y.preventDefault(),y.stopImmediatePropagation();const M=Ce(y),A=Jn(Y.ray,e.cloudDirectionAt(M.x,M.y),Y.center);if(!A)return;A.y=Math.max(A.y,-Y.minBase);const H=Y.delta,J=Y.id;I(W=>({...W,instances:W.instances?.map(G=>G.id!==J?G:{...G,eastM:G.eastM+A.x-H.x,northM:G.northM-A.z+H.z,baseM:G.baseM+A.y-H.y})})),Y.delta=A,E()},!0);const Ke=y=>{!Y||y.pointerId!==Y.pointerId||(Y=void 0,T.hasPointerCapture(y.pointerId)&&T.releasePointerCapture(y.pointerId),T.style.cursor=Z.checked?"crosshair":"")};return T.addEventListener("pointerup",Ke),T.addEventListener("pointercancel",Ke),T.addEventListener("lostpointercapture",Ke),a.addCloud=()=>{const y=p();if(!y)return;const M=crypto.randomUUID(),A=e.ufoElement.sighting,H=e.ufoElement.currentTime,J=ee(A,H),W=Ti(H,A.weatherTrack,re(A,0),ee(A,0),J,y.id),G=e.cloudDirectionAt(0,0),Ie=y.baseM+y.thicknessM*.4-(J?.elevationM??0)-1.6,Ve=Ie*G.y>0?Math.max(500,Math.min(2e4,Ie/G.y)):5e3,pt={id:M,eastM:W.x+G.x*Ve,northM:-(W.z+G.z*Ve),baseM:y.baseM,thicknessM:y.thicknessM,widthM:1800,depthM:1200,rotationDeg:0,density:1,darkness:y.darkness};I(mt=>({...mt,instances:[...mt.instances??[],pt]})),S(),l.show(M),E(),c.textContent+=r.cloudAdded},a.removeCloud=()=>{const y=l.value;y&&(I(M=>({...M,instances:M.instances?.filter(A=>A.id!==y)})),S())},a.pointAtCloud=()=>{const y=p(),M=y?.instances?.find(mt=>mt.id===l.value);if(!M)return;e.ufoElement.pause();const A=e.ufoElement.sighting,H=e.ufoElement.currentTime,J=ee(A,H),W=Ti(H,A.weatherTrack,re(A,0),ee(A,0),J,y.id),G=M.eastM-W.x,Ie=M.northM+W.z,Ve=Math.hypot(G,Ie),pt=M.baseM+M.thicknessM/2-(J?.elevationM??0)-1.6-Ve**2/(2*6371e3);Ve===0&&pt===0||i((Math.atan2(G,Ie)*180/Math.PI+360)%360,Math.atan2(pt,Ve)*180/Math.PI)},Promise.all([_s.load(s),Xn.load(s)]).then(([y,M])=>{r=y,C(M),rs.localize(k,r),h(),x=-1,S()}),{sync:S,stopManipulation(){Y=void 0,Z.checked=!1,T.style.touchAction="",T.style.cursor=""},reset(){Y=void 0,Z.checked=!1,T.style.cursor="",T.style.touchAction="",l.show(""),x=-1,S()}}}class O{constructor(e){this.root=e;const t=i=>{const s=i.target?.closest?.(".section-title");return s&&O.sectionOf(s)?.hasAttribute("data-foldable")?s:void 0};e.addEventListener("click",i=>{const s=t(i);s&&!this.listedNow(O.sectionOf(s))&&this.unfold(O.sectionOf(s),!O.sectionOf(s).hasAttribute("data-unfolded"))}),e.addEventListener("keydown",i=>{const s=i.key;if(s!=="Enter"&&s!==" ")return;const n=t(i);!n||this.listedNow(O.sectionOf(n))||(i.preventDefault(),this.unfold(O.sectionOf(n),!O.sectionOf(n).hasAttribute("data-unfolded")))});for(const i of e.querySelectorAll(".form-section")){if(i.dataset.fold!=="all"&&!i.querySelector(".adv"))continue;const s=document.createElement("button");s.type="button",s.className="more-toggle",s.setAttribute("aria-expanded","false"),s.addEventListener("click",()=>this.setOpen(i,!i.hasAttribute("data-open")));const n=i.querySelector(":scope > .section-title");i.dataset.fold==="all"&&n?n.after(s):i.append(s),this.toggles.set(i,s)}if(typeof ResizeObserver<"u"){const i=new Map,s=new ResizeObserver(n=>{let r=!1;for(const o of n){const a=Math.round(o.contentRect.width);i.get(o.target)!==a&&(i.set(o.target,a),r=!0)}r&&this.refresh()});for(const n of this.toggles.keys())s.observe(n)}}static TITLED=".form-section[data-foldable]";static titles(e="",t=""){return[`${O.TITLED}${t} > .section-title${e}`,`${O.TITLED}${t} > .section-head > .section-title${e}`].join(", ")}static TITLES=O.titles();static CSS=`
36
+ ${O.TITLED}:not([data-unfolded]) > :not(.section-title, .section-head) { display: none !important; }
37
37
  /* A title in a head of its own (beside a choice that is part of what it folds): the head stays, the title alone in it. */
38
- ${C.TITLED}:not([data-unfolded]) > .section-head > :not(.section-title) { display: none !important; }
38
+ ${O.TITLED}:not([data-unfolded]) > .section-head > :not(.section-title) { display: none !important; }
39
39
  /* Folded, a line of a list: as little room under its title as over it. The room over it is the same either way, so that the title stays
40
40
  where it is when it opens; only what is under it grows. */
41
- ${C.TITLED} { padding-top: 10px; }
42
- ${C.TITLED}:not([data-unfolded]) { padding-bottom: 9px; }
43
- ${C.TITLES} { display: flex; align-items: center; gap: 8px; margin: 0 0 -2px; cursor: pointer; user-select: none; }
44
- ${C.titles(":hover")} { color: var(--ink, CanvasText); }
45
- ${C.titles(":focus-visible")} { outline: 2px solid var(--sky, Highlight); outline-offset: 3px; border-radius: 4px; }
46
- ${C.titles("::before")} { content: "›"; display: inline-block; width: .6em; font-size: 1.5em; line-height: .7; letter-spacing: 0;
41
+ ${O.TITLED} { padding-top: 10px; }
42
+ ${O.TITLED}:not([data-unfolded]) { padding-bottom: 9px; }
43
+ ${O.TITLES} { display: flex; align-items: center; gap: 8px; margin: 0 0 -2px; cursor: pointer; user-select: none; }
44
+ ${O.titles(":hover")} { color: var(--ink, CanvasText); }
45
+ ${O.titles(":focus-visible")} { outline: 2px solid var(--sky, Highlight); outline-offset: 3px; border-radius: 4px; }
46
+ ${O.titles("::before")} { content: "›"; display: inline-block; width: .6em; font-size: 1.5em; line-height: .7; letter-spacing: 0;
47
47
  transition: transform .12s ease; }
48
- ${C.titles("::before","[data-unfolded]")} { transform: rotate(90deg); }
49
- @media (prefers-reduced-motion: reduce) { ${C.titles("::before")} { transition: none; } }
48
+ ${O.titles("::before","[data-unfolded]")} { transform: rotate(90deg); }
49
+ @media (prefers-reduced-motion: reduce) { ${O.titles("::before")} { transition: none; } }
50
50
  .form-section:not([data-open], [data-fits]) .adv { display: none !important; }
51
51
  .form-section[data-fold="all"]:not([data-open], [data-foldable]) > :not(.section-title, .more-toggle) { display: none !important; }
52
52
  /* Folded by its title like every other, a section held back whole needs no second fold under it. */
@@ -61,11 +61,11 @@ ${C.titles("::before","[data-unfolded]")} { transform: rotate(90deg); }
61
61
  .more-toggle[aria-expanded="true"]::before { transform: rotate(90deg); }
62
62
  .more-toggle[hidden] { display: none; }
63
63
  @media (prefers-reduced-motion: reduce) { .more-toggle::before { transition: none; } }
64
- `;messages;toggles=new Map;setMessages(e){this.messages=e,this.refresh()}refresh(){this.markTitles(),this.refreshIndex();const e=this.messages;if(e)for(const[t,i]of this.toggles){const s=this.fits(t,i);t.toggleAttribute("data-fits",s);const n=t.hasAttribute("data-open"),r=t.dataset.fold==="all",o=this.count(t);i.hidden=!r&&o===0||s;const a=r?n?e.hideSettings:o===0?e.showSettingsAny:(o===1?e.showSettingsOne:e.showSettings).replaceAll("{n}",String(o)):n?e.lessSettings:e.moreSettings.replaceAll("{n}",String(o));i.textContent!==a&&(i.textContent=a),i.setAttribute("aria-expanded",String(n))}}fits(e,t){if(e.dataset.fold==="all")return!1;const i=()=>e.getBoundingClientRect().height;if(i()===0)return!1;const s=e.hasAttribute("data-open"),n=t.hidden;e.removeAttribute("data-fits"),t.hidden=!1,e.removeAttribute("data-open");const r=i();e.setAttribute("data-open",""),t.hidden=!0;const o=i()<=r+.5;return e.toggleAttribute("data-open",s),t.hidden=n,o}reveal(e){const t=e.closest(".group-panel");let i;for(let n=e.closest(".form-section");n&&t?.contains(n);n=n.parentElement?.closest(".form-section")??null)n.hasAttribute("data-foldable")&&(i=n);t&&i&&(this.chosen.set(t,i),this.refreshIndex());for(let n=e.closest(".form-section");n;n=n.parentElement?.closest(".form-section")??null)n.hasAttribute("data-unfolded")||this.unfold(n,!0);const s=e.closest(".form-section");s&&this.toggles.has(s)&&!s.hasAttribute("data-open")&&this.setOpen(s,!0)}unfold(e,t){e.toggleAttribute("data-unfolded",t),e.querySelector(C.TITLE)?.setAttribute("aria-expanded",String(t)),t&&this.refresh()}index;chosen=new WeakMap;listed=[];listedParts=[];indexKey="";indexFrame;indexIn(e,t){this.index={nav:e,panel:t},e.addEventListener("click",s=>{const n=s.target?.closest?.("[data-part]");if(n){this.listedParts[Number(n.dataset.part)]?.click(),this.refreshIndex();return}const r=s.target?.closest?.("[data-section]"),o=r?this.listed[Number(r.dataset.section)]:void 0,a=o?.closest(".group-panel");!o||!a||(this.chosen.set(a,o),this.refreshIndex(),a.scrollTop=0)});const i=()=>{this.indexFrame===void 0&&(this.indexFrame=requestAnimationFrame(()=>{this.indexFrame=void 0,this.refreshIndex()}))};typeof ResizeObserver<"u"&&new ResizeObserver(i).observe(e.parentElement??e),typeof MutationObserver<"u"&&new MutationObserver(i).observe(this.root,{subtree:!0,attributes:!0,attributeFilter:["hidden"]}),this.refreshIndex()}static titleText(e){if(!e)return"";const t=e.cloneNode(!0);for(const i of t.querySelectorAll("rr0-hint, button, [aria-hidden='true'], [hidden]"))i.remove();return(t.textContent??"").replace(/\s+/g," ").trim()}static iconOf(e){const t=e.querySelector(C.TITLE),i=[e.dataset.icon,t?.id,t?.querySelector("[id]")?.id,e.id];for(const s of i){const n=s?M.section(s):void 0;if(n)return n}}get indexed(){const e=this.index?.nav;return e!==void 0&&e.isConnected&&getComputedStyle(e).display!=="none"}listedNow(e){return this.listed.includes(e)&&this.indexed}refreshIndex(){const e=this.index;if(!e)return;const i=this.indexed?e.panel():void 0,s=u=>{for(let p=u;p&&p!==i;p=p.parentElement)if(p.hidden)return!1;return!0},n=i?[...i.querySelectorAll(":scope > .group-tabs > .subgroup-tab, :scope > .subtabs-row > .group-tabs > .subgroup-tab")].filter(u=>!u.hidden):[],r=n.length>1;this.listedParts=r?n:[];const o=i&&!r?[...i.querySelectorAll(C.TITLED)].filter(u=>s(u)&&!u.parentElement?.closest(`${C.TITLED}`)):[];let a=i?this.chosen.get(i):void 0;(!a||!o.includes(a))&&(a=o[0]);for(const u of this.listed)o.includes(u)||(u.removeAttribute("data-elsewhere"),u.removeAttribute("data-chosen"));for(const u of o)u.toggleAttribute("data-elsewhere",u!==a),u.toggleAttribute("data-chosen",u===a);a&&!a.hasAttribute("data-unfolded")&&(a.setAttribute("data-unfolded",""),a.querySelector(C.TITLE)?.setAttribute("aria-expanded","true")),this.listed=o;const d=r?n.map(u=>C.titleText(u)):o.map(u=>C.titleText(u.querySelector(C.TITLE))),l=r?n.findIndex(u=>u.getAttribute("aria-expanded")==="true"):a?o.indexOf(a):-1,h=`${r?"parts":"sections"}
64
+ `;messages;toggles=new Map;setMessages(e){this.messages=e,this.refresh()}refresh(){this.markTitles(),this.refreshIndex();const e=this.messages;if(e)for(const[t,i]of this.toggles){const s=this.fits(t,i);t.toggleAttribute("data-fits",s);const n=t.hasAttribute("data-open"),r=t.dataset.fold==="all",o=this.count(t);i.hidden=!r&&o===0||s;const a=r?n?e.hideSettings:o===0?e.showSettingsAny:(o===1?e.showSettingsOne:e.showSettings).replaceAll("{n}",String(o)):n?e.lessSettings:e.moreSettings.replaceAll("{n}",String(o));i.textContent!==a&&(i.textContent=a),i.setAttribute("aria-expanded",String(n))}}fits(e,t){if(e.dataset.fold==="all")return!1;const i=()=>e.getBoundingClientRect().height;if(i()===0)return!1;const s=e.hasAttribute("data-open"),n=t.hidden;e.removeAttribute("data-fits"),t.hidden=!1,e.removeAttribute("data-open");const r=i();e.setAttribute("data-open",""),t.hidden=!0;const o=i()<=r+.5;return e.toggleAttribute("data-open",s),t.hidden=n,o}reveal(e){const t=e.closest(".group-panel");let i;for(let n=e.closest(".form-section");n&&t?.contains(n);n=n.parentElement?.closest(".form-section")??null)n.hasAttribute("data-foldable")&&(i=n);t&&i&&(this.chosen.set(t,i),this.refreshIndex());for(let n=e.closest(".form-section");n;n=n.parentElement?.closest(".form-section")??null)n.hasAttribute("data-unfolded")||this.unfold(n,!0);const s=e.closest(".form-section");s&&this.toggles.has(s)&&!s.hasAttribute("data-open")&&this.setOpen(s,!0)}unfold(e,t){e.toggleAttribute("data-unfolded",t),e.querySelector(O.TITLE)?.setAttribute("aria-expanded",String(t)),t&&this.refresh()}index;chosen=new WeakMap;listed=[];listedParts=[];indexKey="";indexFrame;indexIn(e,t){this.index={nav:e,panel:t},e.addEventListener("click",s=>{const n=s.target?.closest?.("[data-part]");if(n){this.listedParts[Number(n.dataset.part)]?.click(),this.refreshIndex();return}const r=s.target?.closest?.("[data-section]"),o=r?this.listed[Number(r.dataset.section)]:void 0,a=o?.closest(".group-panel");!o||!a||(this.chosen.set(a,o),this.refreshIndex(),a.scrollTop=0)});const i=()=>{this.indexFrame===void 0&&(this.indexFrame=requestAnimationFrame(()=>{this.indexFrame=void 0,this.refreshIndex()}))};typeof ResizeObserver<"u"&&new ResizeObserver(i).observe(e.parentElement??e),typeof MutationObserver<"u"&&new MutationObserver(i).observe(this.root,{subtree:!0,attributes:!0,attributeFilter:["hidden"]}),this.refreshIndex()}static titleText(e){if(!e)return"";const t=e.cloneNode(!0);for(const i of t.querySelectorAll("rr0-hint, button, [aria-hidden='true'], [hidden]"))i.remove();return(t.textContent??"").replace(/\s+/g," ").trim()}static iconOf(e){const t=e.querySelector(O.TITLE),i=[e.dataset.icon,t?.id,t?.querySelector("[id]")?.id,e.id];for(const s of i){const n=s?L.section(s):void 0;if(n)return n}}get indexed(){const e=this.index?.nav;return e!==void 0&&e.isConnected&&getComputedStyle(e).display!=="none"}listedNow(e){return this.listed.includes(e)&&this.indexed}refreshIndex(){const e=this.index;if(!e)return;const i=this.indexed?e.panel():void 0,s=u=>{for(let p=u;p&&p!==i;p=p.parentElement)if(p.hidden)return!1;return!0},n=i?[...i.querySelectorAll(":scope > .group-tabs > .subgroup-tab, :scope > .subtabs-row > .group-tabs > .subgroup-tab")].filter(u=>!u.hidden):[],r=n.length>1;this.listedParts=r?n:[];const o=i&&!r?[...i.querySelectorAll(O.TITLED)].filter(u=>s(u)&&!u.parentElement?.closest(`${O.TITLED}`)):[];let a=i?this.chosen.get(i):void 0;(!a||!o.includes(a))&&(a=o[0]);for(const u of this.listed)o.includes(u)||(u.removeAttribute("data-elsewhere"),u.removeAttribute("data-chosen"));for(const u of o)u.toggleAttribute("data-elsewhere",u!==a),u.toggleAttribute("data-chosen",u===a);a&&!a.hasAttribute("data-unfolded")&&(a.setAttribute("data-unfolded",""),a.querySelector(O.TITLE)?.setAttribute("aria-expanded","true")),this.listed=o;const d=r?n.map(u=>O.titleText(u)):o.map(u=>O.titleText(u.querySelector(O.TITLE))),l=r?n.findIndex(u=>u.getAttribute("aria-expanded")==="true"):a?o.indexOf(a):-1,h=`${r?"parts":"sections"}
65
65
  ${d.join(`
66
66
  `)}
67
67
  ${l}
68
- ${this.messages?.sectionIndex??""}`;if(h===this.indexKey)return;this.indexKey=h;const c=e.nav;this.messages?.sectionIndex&&c.setAttribute("aria-label",this.messages.sectionIndex),c.replaceChildren(...d.map((u,p)=>{const m=document.createElement("button");m.type="button",m.className="section-link",r?m.dataset.part=String(p):m.dataset.section=String(p);const f=document.createElement("span");f.className="section-icon";const g=r?n[p].querySelector("svg")?.outerHTML:C.iconOf(o[p]);g?f.innerHTML=g:f.textContent=u.slice(0,1);const b=document.createElement("span");return b.className="section-text",b.textContent=u,m.append(f,b),m.title=u,p===l&&m.setAttribute("aria-current","true"),m}))}static INDEX_CSS=`
68
+ ${this.messages?.sectionIndex??""}`;if(h===this.indexKey)return;this.indexKey=h;const c=e.nav;this.messages?.sectionIndex&&c.setAttribute("aria-label",this.messages.sectionIndex),c.replaceChildren(...d.map((u,p)=>{const m=document.createElement("button");m.type="button",m.className="section-link",r?m.dataset.part=String(p):m.dataset.section=String(p);const f=document.createElement("span");f.className="section-icon";const g=r?n[p].querySelector("svg")?.outerHTML:O.iconOf(o[p]);g?f.innerHTML=g:f.textContent=u.slice(0,1);const b=document.createElement("span");return b.className="section-text",b.textContent=u,m.append(f,b),m.title=u,p===l&&m.setAttribute("aria-current","true"),m}))}static INDEX_CSS=`
69
69
  .section-index { display: none; container: section-index / inline-size; }
70
70
  .section-index > .section-link { display: flex; align-items: center; justify-content: space-between; gap: 10px; width: 100%; margin: 0;
71
71
  padding: 10px 14px 10px 18px; border: 0; border-radius: 0; background: none; color: var(--ink-dim, inherit); text-align: start;
@@ -89,9 +89,9 @@ ${this.messages?.sectionIndex??""}`;if(h===this.indexKey)return;this.indexKey=h;
89
89
  .form-section[data-elsewhere] { display: none !important; }
90
90
  /* The parts of a group, listed in the index: their strip of tabs goes, what stands beside it (the Phenomenon's view) stays. */
91
91
  .group-panel > .group-tabs:has(> .subgroup-tab), .group-panel > .subtabs-row > .group-tabs:has(> .subgroup-tab) { display: none !important; }
92
- ${C.titles("","[data-chosen]")} { cursor: default; }
93
- ${C.titles("::before","[data-chosen]")} { display: none; }
94
- `;markTitles(){for(const e of this.root.querySelectorAll(".form-section > .section-title, .form-section > .section-head > .section-title")){const t=C.sectionOf(e),i=!e.hidden&&(e.textContent??"").trim()!=="";t.toggleAttribute("data-foldable",i),i!==e.hasAttribute("role")&&(i?(e.tabIndex=0,e.setAttribute("role","button"),e.setAttribute("aria-expanded",String(t.hasAttribute("data-unfolded")))):(e.removeAttribute("tabindex"),e.removeAttribute("role"),e.removeAttribute("aria-expanded")))}}static TITLE=":scope > .section-title, :scope > .section-head > .section-title";static sectionOf(e){const t=e.parentElement,i=t?.classList.contains("section-head")?t.parentElement:t;return i?.classList.contains("form-section")?i:void 0}setOpen(e,t){e.toggleAttribute("data-open",t),this.refresh()}count(e){const t=s=>{for(let n=s;n&&n!==e;n=n.parentElement)if(n.hidden)return!1;return!0};return(e.dataset.fold==="all"?[...e.querySelectorAll(":scope > label, :scope > .field")]:[...e.querySelectorAll(".adv")]).filter(t).length}}class Bs{constructor(e){this.host=e,wi()}static CSS=`${et.CSS}${Ae.CSS}
92
+ ${O.titles("","[data-chosen]")} { cursor: default; }
93
+ ${O.titles("::before","[data-chosen]")} { display: none; }
94
+ `;markTitles(){for(const e of this.root.querySelectorAll(".form-section > .section-title, .form-section > .section-head > .section-title")){const t=O.sectionOf(e),i=!e.hidden&&(e.textContent??"").trim()!=="";t.toggleAttribute("data-foldable",i),i!==e.hasAttribute("role")&&(i?(e.tabIndex=0,e.setAttribute("role","button"),e.setAttribute("aria-expanded",String(t.hasAttribute("data-unfolded")))):(e.removeAttribute("tabindex"),e.removeAttribute("role"),e.removeAttribute("aria-expanded")))}}static TITLE=":scope > .section-title, :scope > .section-head > .section-title";static sectionOf(e){const t=e.parentElement,i=t?.classList.contains("section-head")?t.parentElement:t;return i?.classList.contains("form-section")?i:void 0}setOpen(e,t){e.toggleAttribute("data-open",t),this.refresh()}count(e){const t=s=>{for(let n=s;n&&n!==e;n=n.parentElement)if(n.hidden)return!1;return!0};return(e.dataset.fold==="all"?[...e.querySelectorAll(":scope > label, :scope > .field")]:[...e.querySelectorAll(".adv")]).filter(t).length}}class Bs{constructor(e){this.host=e,wi()}static CSS=`${et.CSS}${Ae.CSS}
95
95
  :is(label, .field)[data-basis="assumed"] :is(input, .edtf-field input) { font-style: italic; }
96
96
  /* ("> .basis-mark" in :has keeps the weight the rule had when the mark was the label's own child, over the form's flex labels.)
97
97
  A field with its basis: its name and the mark on the first line, the value and its unit on the next, the law under them. Left to
@@ -130,8 +130,8 @@ ${C.titles("::before","[data-chosen]")} { display: none; }
130
130
  .parameter-rows > .parameter-row .scope { color: var(--ink-faint); font-size: 13px; }
131
131
  .extrapolation { grid-column: 1 / -1; margin: 0; padding: 8px 10px; border-radius: 8px; background: var(--warn-bg); font-size: 13px; color: var(--ink); }
132
132
  @container (max-width: 640px) { .moon-gauge { grid-template-columns: minmax(0, 1fr); } .parameter-rows > .parameter-row { grid-template-columns: minmax(0, 1fr) auto; } }
133
- `;fields=[];model=ee.MODELS[0];sections=[];observerShown;attach(e){this.fields.push(e);const t=document.createElement(et.TAG);t.addEventListener("basischange",n=>this.said(e,n.detail.entry));const i=e.label.firstElementChild;i?i.after(t):e.label.prepend(t);const s=document.createElement("span");s.className="law",e.label.append(s),e.input.addEventListener("input",()=>this.retyped(e)),e.input.addEventListener("change",()=>this.retyped(e))}refresh(){this.refreshFields(),this.renderObserver(),this.host.lawsChanged()}get errorModel(){return this.model}refreshFields(){for(const e of this.fields)this.refreshField(e)}entryOf(e){const t=e.path();return t===void 0?void 0:this.host.sighting.provenance.at(t)}refreshField(e,t){const i=this.host.messages();if(!i)return;const s=this.entryOf(e),n=s?.basis??"stated",r=e.label.querySelector(et.TAG);r.hows=ee.HOW[e.kind].map(l=>({value:l,label:i.how[l]??l})),r.messages={title:i.basisTitle,basis:i.basis,basisField:i.basisField,howField:i.howField,rationaleField:i.rationaleField};const o=this.host.valueSources?.();r.sourceMessages=o?.messages,r.choices=o?.choices??{},r.entry=s,r.hidden=e.path()===void 0,e.label.dataset.basis=n;const a=e.label.querySelector(".law");if(t){this.showLaw(a,[Object.assign(document.createElement("span"),{className:"law-reset",textContent:i.basisReset.replace("{basis}",i.basis[t])})]);return}const d=e.value();this.showLaw(a,d===void 0?[]:this.lawNodes(this.model.law({kind:e.kind,value:d,basis:n,how:s?.how},this.conditions),e.kind))}showLaw(e,t){const i=t.map(s=>s instanceof HTMLElement?`${s.className}|${s.textContent}|${s.title}|${s.dataset.status??""}`:s.textContent).join(`
134
- `);e.dataset.said!==i&&(e.dataset.said=i,e.replaceChildren(...t))}lawNodes(e,t){const i=this.host.messages(),s=Object.assign(document.createElement("span"),{className:"law-symbol",textContent:e.shape==="uninformative"?"∅":"≈"});let n=i.laws[e.note];for(const[a,d]of Object.entries(e.params??{}))n=n.replaceAll(`{${a}}`,this.number(ee.rounded(d)));e.low!==void 0&&(n=n.replaceAll("{low}",this.withUnit(e.low,t))),e.high!==void 0&&(n=n.replaceAll("{high}",this.withUnit(e.high,t)));const r=Object.assign(document.createElement("span"),{textContent:n});e.sources.length>0&&(r.title=i.lawSources.replace("{sources}",e.sources.join(", ")));const o=Object.assign(document.createElement("span"),{className:"lead-status",textContent:i.status[e.status]});return o.dataset.status=e.status,[s,r,o]}number(e){return e.toLocaleString(document.documentElement.lang||void 0,{maximumFractionDigits:Math.abs(e)<1?6:2})}withUnit(e,t){const i=ee.rounded(e);switch(t){case"duration":return i>=90?`${this.number(ee.rounded(i/60))} min`:`${this.number(i)} s`;case"time":return`${this.number(i)} min`;case"distance":return`${this.number(i)} m`;default:return`${this.number(i)}°`}}retyped(e){const t=e.path(),i=t===void 0?void 0:this.host.sighting.provenance.at(t);if(!t||!i||i.basis==="stated"&&i.how===void 0){this.refreshField(e);return}this.host.sighting.provenance.clear(t),this.refreshField(e,i.basis==="stated"?void 0:i.basis),setTimeout(()=>this.refreshField(e),4e3)}said(e,t){const i=e.path();i!==void 0&&(t?this.host.sighting.provenance.set(i,{...t,...e.value()!==void 0?{of:this.valueAt(i)}:{}}):this.host.sighting.provenance.clear(i),this.host.changed(),this.refreshField(e))}valueAt(e){const t=s=>s&&typeof s=="object"&&!Array.isArray(s)&&"value"in s?s.value:s;let i=this.host.recordingJson();for(const s of e.split("."))i=i&&typeof i=="object"?t(i[s]):void 0;return t(i)}get conditions(){return this.host.sighting.account?.conditions}setConditions(e){const t={...this.conditions??{},...e};for(const i of Object.keys(t))t[i]===void 0&&delete t[i];this.host.conditionsChanged(Object.keys(t).length>0?t:void 0),this.host.changed(),this.refresh()}placeObserverSections(e){const t=()=>{const s=document.createElement("div");return s.className="form-section witness-error",this.sections.push(s),s},i=[t(),t(),t(),t()];i.forEach((s,n)=>{s.dataset.icon=["witness-conditions","viewing-conditions","moon-gauge","error-parameters"][n]}),e.after(...i),this.renderObserver()}renderObserver(){if(this.sections.length===0)return;const e=this.host.messages();if(!e)return;const t=this.conditions??{},i={messages:e,model:this.model,conditions:JSON.stringify([t,this.host.sighting.provenance.at("time")?.how,this.daylight()])},s=this.observerShown;if(s&&s.messages===i.messages&&s.model===i.model&&s.conditions===i.conditions)return;this.observerShown=i;const[n,r,o,a]=this.sections,d=m=>Object.assign(document.createElement("h3"),{className:"section-title",textContent:m}),l=(m,f,g)=>{const b=document.createElement("label");return b.append(Object.assign(document.createElement("span"),{textContent:m}),f),g&&b.append(` ${g}`),b},h=(m,f,g="1")=>{const b=document.createElement("input");return b.type="number",b.min="0",b.step=g,b.value=m===void 0?"":String(m),b.addEventListener("change",()=>f(b.value.trim()===""||!Number.isFinite(Number(b.value))?void 0:Number(b.value))),b},c=(m,f,g)=>{const b=document.createElement("select");return b.append(new Option(e.unknownChoice,""),...f.map(([v,I])=>new Option(I,v))),b.value=m??"",b.addEventListener("change",()=>g(b.value===""?void 0:b.value)),b},u=(m,f,g,b)=>{const v=document.createElement("label"),I=document.createElement("input");return I.type="checkbox",I.checked=f===!0,I.addEventListener("change",()=>g(I.checked?!0:void 0)),v.append(I,` ${m}`),b&&v.append(Ae.of(b)),v},p=document.createElement("select");p.append(new Option(e.unknownChoice,""),new Option(e.independentYes,"yes"),new Option(e.independentNo,"no")),p.value=t.independent===void 0?"":t.independent?"yes":"no",p.addEventListener("change",()=>this.setConditions({independent:p.value===""?void 0:p.value==="yes"})),n.replaceChildren(d(e.sectionAccountConditions),l(e.delayField,h(t.delayDays,m=>this.setConditions({delayDays:m})),e.delayUnit),l(e.versionField,h(t.version,m=>this.setConditions({version:m}))),l(e.wordField,c(t.word,Object.entries(e.words),m=>this.setConditions({word:m}))),l(e.exposureField,c(t.exposure,Object.entries(e.exposures),m=>this.setConditions({exposure:m}))),l(e.independenceField,p)),r.replaceChildren(d(e.sectionViewing),u(e.darkAdapted,t.darkAdapted,m=>this.setConditions({darkAdapted:m})),u(e.correctedVision,t.correctedVision,m=>this.setConditions({correctedVision:m}),e.correctedVisionHint),u(e.glare,t.glare,m=>this.setConditions({glare:m})),Object.assign(document.createElement("p"),{className:"section-intro",textContent:e.viewingNote})),o.replaceChildren(d(e.sectionMoon),Object.assign(document.createElement("p"),{className:"section-intro",textContent:e.moonIntro}),this.moonGauge(t)),this.renderParameters(a,t)}moonGauge(e){const t=this.host.messages(),i=ee.moonFactor(e),s=document.createElement("div");s.className="moon-gauge";const n=document.createElement("div");n.className="moon-picture";const r=12,o=i===void 0?void 0:Math.min(70,r*i);n.innerHTML=`<svg viewBox="0 0 150 150" width="150" height="150" aria-hidden="true"><circle cx="75" cy="72" r="${r}" fill="#efe9d6"/>${o!==void 0?`<circle cx="75" cy="72" r="${o}" fill="none" stroke="#f5c451" stroke-width="1.5" stroke-dasharray="4 3"/>`:""}</svg>`,n.append(Object.assign(document.createElement("span"),{textContent:t.moonReal}));const a=document.createElement("div");a.className="moon-side";const d=document.createElement("label"),l=document.createElement("input");l.type="number",l.min="0",l.step="0.1",l.placeholder="1,7",l.value=e.moonShownDeg===void 0?"":String(e.moonShownDeg),l.addEventListener("change",()=>this.setConditions({moonShownDeg:l.value.trim()===""||!(Number(l.value)>0)?void 0:Number(l.value)})),d.append(Object.assign(document.createElement("span"),{textContent:t.moonField}),l," °");const h=Object.assign(document.createElement("span"),{className:"section-intro",textContent:t.moonHint}),c=this.model.parameters().find(m=>m.id==="size");let u=t.parameters[c.note];for(const[m,f]of Object.entries(c.params??{}))u=u.replaceAll(`{${m}}`,this.number(f));const p=Object.assign(document.createElement("p"),{className:"note",textContent:i===void 0?t.moonNone.replace("{law}",`${u}, ${t.status[c.status]}`):t.moonFactor.replace("{k}",this.number(ee.rounded(i)))});return a.append(d,h,p),s.append(n,a),s}renderParameters(e,t){const i=this.host.messages(),s=document.createElement("div");s.className="section-head";const n=document.createElement("label");n.className="model-pick";const r=document.createElement("select");for(const l of ee.MODELS)r.append(new Option(i.models[l.id]??l.title,l.id));r.value=this.model.id,r.addEventListener("change",()=>{this.model=ee.byId(r.value),this.refresh()}),n.append(i.errorModelField,r),s.append(Object.assign(document.createElement("h3"),{className:"section-title",textContent:i.sectionErrorParameters}),n);const o=this.host.sighting.provenance.at("time")?.how,a=document.createElement("div");a.className="parameter-rows";for(const l of this.model.parameters(t,o)){const h=document.createElement("div");h.className="parameter-row";let c=i.parameters[l.note];for(const[m,f]of Object.entries(l.params??{}))c=c.replaceAll(`{${m}}`,this.number(ee.rounded(f)));const u=Object.assign(document.createElement("span"),{className:"lead-status",textContent:i.status[l.status]});u.dataset.status=l.status;const p=document.createElement("span");p.append(c,Object.assign(document.createElement("span"),{className:"scope",textContent:` · ${i.parameterScopes[l.id]}`})),h.append(Object.assign(document.createElement("strong"),{textContent:i.parameterNames[l.id]}),p,u),a.append(h)}const d=[s,Object.assign(document.createElement("p"),{className:"section-intro",textContent:i.parametersIntro}),a];this.daylight()&&d.push(Object.assign(document.createElement("p"),{className:"extrapolation",textContent:i.extrapolation})),e.replaceChildren(...d)}daylight(){const e=this.host.sighting.event,t=e.place?.[0];if(!t||!e.time)return!1;const i=be(e.time,t.lng,e.utcOffsetHours);return i!==void 0&&V("Sun",i,{lat:t.lat,lng:t.lng,elevationM:0}).altitudeDeg>0}}class z{constructor(e,t){this.model=e,this.conditions=t}static BOUND_SIGMA=3;static TAIL_SIGMA=2;static POINT_SIZE_DEG=.1;static MOVED_DEG=2;static STILL_DEG=.5;static SWEEP_SIGMA_DEG=5*Math.SQRT2;static STILL_SEEN_MOVING_MAX_DEG=10;static GROWTH=1.5;static BRIGHTENING_MAG=.5;static READING_STATUS={grouped:"consolidated","still-seen-moving":"consolidated","moving-seen-still":"argued","brightening-as-approach":"argued"};static ELEVATION_SIGMA_DEG=5;fit(e,t){const i=this.model.law({kind:"time",value:0,how:e.timeHow},this.conditions),s=Math.max(.5,(i.high??6)/2);let n;const r=24;for(let o=0;o<=r;o++){const a=-3*s+2*z.BOUND_SIGMA*s*o/r,d=t.at(a);if(!d)continue;const l=this.variantAt(e,t,a,s,i.status,d);(!n||l.cost<n.cost)&&(n=l)}return n??{candidate:t.id,label:t.label,verdict:"incompatible",cost:1/0,reason:"never-seen",moved:[],readings:[],parameters:{clockMinutes:0,headingDeg:0,elevationFactor:1,sizeFactor:1},modelId:this.model.id}}search(e,t){const i={consolidated:0,contested:1,incompatible:2};return t.map(s=>this.fit(e,s)).sort((s,n)=>i[s.verdict]-i[n.verdict]||s.cost-n.cost)}variantAt(e,t,i,s,n,r){const o=[];let a;Math.abs(i)>.05&&o.push({field:"time",stated:0,variant:i,parameter:"clock",amount:i,z:i/s,status:n});let d=0,l=1;if(e.aim){const v=this.model.law({kind:"heading",value:e.aim.azimuthDeg,how:e.headingHow},this.conditions),I=((v.high??e.aim.azimuthDeg+45)-e.aim.azimuthDeg)/2;d=((r.aim.azimuthDeg-e.aim.azimuthDeg)%360+540)%360-180,Math.abs(d)>.5&&o.push({field:"heading",stated:e.aim.azimuthDeg,variant:(r.aim.azimuthDeg+360)%360,parameter:"heading",amount:d,z:d/I,status:v.status});const x=e.aim.altitudeDeg,y=this.model.law({kind:"elevation",value:x},this.conditions),S=y.low??x,O=y.high??x,N=r.aim.altitudeDeg,A=N>O?(N-O)/z.ELEVATION_SIGMA_DEG:N<S?(S-N)/z.ELEVATION_SIGMA_DEG:0;l=x>0?N/x:1,Math.abs(N-x)>.5&&o.push({field:"elevation",stated:x,variant:N,parameter:"elevation",amount:l,z:A,status:A>0?"argued":y.status})}let h=1;if(e.widthDeg!==void 0&&e.widthDeg>0){const v=Math.max(r.widthDeg,z.POINT_SIZE_DEG),I=this.model.law({kind:"angularSize",value:e.widthDeg,how:e.sizeHow},this.conditions),x=I.low??e.widthDeg,y=I.high??e.widthDeg,S=v>y?Math.log(v/y)/Math.log(1.5):v<x?Math.log(x/v)/Math.log(1.5):0;h=e.widthDeg/v,Math.abs(Math.log(h))>Math.log(1.1)&&o.push({field:"size",stated:e.widthDeg,variant:v,parameter:"size",amount:h,z:S,status:I.status})}const{readings:c,lacking:u}=this.structural(e,t,i,r);let p;if(!u&&!c.some(v=>v.reading==="still-seen-moving"||v.reading==="moving-seen-still")){const v=this.motionFit(e,t,i,r);v&&(p=v.factor,o.push(...v.moved))}const m=Math.sqrt(o.reduce((v,I)=>v+I.z*I.z,0)),f=o.find(v=>Math.abs(v.z)>z.BOUND_SIGMA);f&&(a=f.field==="size"?"size":f.field==="duration"||f.field==="sweep"?"motion":"direction"),!a&&u&&(a=u);const g=o.some(v=>v.status==="contested"||Math.abs(v.z)>z.TAIL_SIGMA)||c.some(v=>v.status!=="consolidated"),b=a?"incompatible":g?"contested":"consolidated";return{candidate:t.id,label:t.label,verdict:b,cost:ee.rounded(m),moved:o,readings:c,...a?{reason:a}:{},parameters:{clockMinutes:i,headingDeg:d,elevationFactor:l,sizeFactor:h,...p!==void 0?{durationFactor:p}:{}},modelId:this.model.id}}motionFit(e,t,i,s){const n=e.motion;if(!n||n.spanMinutes<=0||n.sweepDeg<z.MOVED_DEG)return;const r=n.spanMinutes*60,o=this.model.law({kind:"duration",value:r},this.conditions),a=Math.log((o.high??r*3)/r)/2;let d;const l=24;for(let c=0;c<=l;c++){const u=Math.exp(a*z.BOUND_SIGMA*(2*c/l-1)),p=t.at(i+n.spanMinutes*u);if(!p)continue;const m=z.separation(s.aim,p.aim),f=Math.log(u)/a,g=(m-n.sweepDeg)/z.SWEEP_SIGMA_DEG;(!d||f**2+g**2<d.zDuration**2+d.zSweep**2)&&(d={factor:u,sweep:m,zDuration:f,zSweep:g})}if(!d||d.sweep<z.STILL_DEG)return;const h=[];return Math.abs(Math.log(d.factor))>Math.log(1.1)&&h.push({field:"duration",stated:r,variant:r*d.factor,parameter:"duration",amount:d.factor,z:d.zDuration,status:o.status}),Math.abs(d.sweep-n.sweepDeg)>1&&h.push({field:"sweep",stated:n.sweepDeg,variant:d.sweep,parameter:"sweep",amount:d.sweep-n.sweepDeg,z:d.zSweep,status:"argued"}),{factor:d.factor,moved:h}}structural(e,t,i,s){const n=t.readings??[],r=[],o=e.motion,a=o&&o.spanMinutes>0?t.at(i+o.spanMinutes):void 0;if(o&&a){const l=z.separation(s.aim,a.aim);if(o.sweepDeg>=z.MOVED_DEG&&l<z.STILL_DEG){if(o.sweepDeg>z.STILL_SEEN_MOVING_MAX_DEG)return{readings:[],lacking:"motion"};r.push(["still-seen-moving","motion"])}else o.sweepDeg<z.STILL_DEG&&l>=z.MOVED_DEG&&r.push(["moving-seen-still","motion"])}if(e.growth!==void 0&&e.growth>=z.GROWTH&&a&&a.widthDeg/Math.max(s.widthDeg,1e-6)<z.GROWTH)if(s.magnitude===void 0||a.magnitude===void 0||s.magnitude-a.magnitude>=z.BRIGHTENING_MAG)r.push(["brightening-as-approach","growth"]);else return{readings:[],lacking:"growth"};const d=n.includes("grouped")?[{reading:"grouped",status:z.READING_STATUS.grouped}]:[];for(const[l,h]of r){if(!n.includes(l))return{readings:d,lacking:h};d.push({reading:l,status:z.READING_STATUS[l]})}return{readings:d}}static separation(e,t){const i=Math.PI/180,s=Math.sin(e.altitudeDeg*i)*Math.sin(t.altitudeDeg*i)+Math.cos(e.altitudeDeg*i)*Math.cos(t.altitudeDeg*i)*Math.cos((e.azimuthDeg-t.azimuthDeg)*i);return Math.acos(Math.max(-1,Math.min(1,s)))/i}}class Ue{constructor(e,t){this.reasons=t;for(const i of e){const s=i.knownPhenomenaProbabilities??i.knownPhenomenonProbabilities??{};this.scores.set(i.question,s);for(const n of Object.keys(s))this.phenomena.includes(n)||this.phenomena.push(n)}}static BASE_URL="https://raw.githubusercontent.com/RR0/rr0.org/master/";static VERSIONS={"poher-1977":"time/1/9/7/7/Poher_Matrice/","rr0-2026":"time/2/0/2/6/10/Poher_Matrice_RR0/"};static DEFAULT_VERSION="rr0-2026";scores=new Map;phenomena=[];has(e){return this.scores.has(e)}reason(e,t){return this.reasons?.cells[e]?.[t]}rank(e){const t=e.filter(s=>this.scores.has(s.question));return this.phenomena.map(s=>{const n=[],r=[];let o=0,a=0;for(const d of t){const l=this.scores.get(d.question)[s];l!==void 0&&(a++,o+=l,l===0&&(d.firm?n:r).push(d.question))}return{phenomenon:s,excludedBy:n,doubtedBy:r,mean:a>0?o/a:0,added:this.reasons?.phenomena[s]!==void 0}}).sort((s,n)=>(s.excludedBy.length>0?1:0)-(n.excludedBy.length>0?1:0)||s.excludedBy.length-n.excludedBy.length||n.mean-s.mean)}static async load(e,t,i){const s=["fr","en","it"].includes(t)?t:"en",n=`${Ue.BASE_URL}${Ue.VERSIONS[e]}`,[r,o,a]=await Promise.all([i(`${n}matrix.json`),i(`${n}Matrix_${s}.json`),e==="poher-1977"?void 0:i(`${n}reasons.json`)]);return{matrix:new Ue(r,a),labels:o}}}class ki{constructor(e,t){this.model=e,this.conditions=t}of(e){const t=[],i=(n,r=!0)=>t.push({question:n,firm:r});e.sunAltitudeDeg!==void 0&&i(e.sunAltitudeDeg>0?"Hour.Day":e.sunAltitudeDeg<-6?"Hour.Night":"Hour.Twilight");const s=(n,r,o)=>{if(r===void 0)return;const a=c=>o.find(([u])=>c<u)?.[1]??o[o.length-1][1],d=this.model.law({kind:n,value:r},this.conditions),l=a(r),h=d.shape==="range"&&a(d.low??r)===l&&a(d.high??r)===l;i(l,h)};if(s("duration",e.durationSeconds,[[10,"Duration.LessThan10s"],[3600,"Duration.AFewMn"],[1/0,"Duration.Above1h"]]),s("elevation",e.elevationDeg,[[5,"AngularHeight.LowOnHorizon"],[30,"AngularHeight.LessThan30d"],[1/0,"AngularHeight.HighInSky"]]),s("angularSize",e.widthDeg,[[.2,"ApparentSize.Pointlike"],[1,"ApparentSize.SimilarToMoon30s"],[1/0,"ApparentSize.SeveralDegrees"]]),e.cloudCover!==void 0&&(e.cloudCover<.2?i("WeatherConditions.NiceAndAlmostClearSky"):e.cloudCover>.8&&i("WeatherConditions.Overcast")),e.lightning&&i("WeatherConditions.Thunder"),e.lowVisibility&&i("WeatherConditions.LowVisibility"),e.sweepDeg!==void 0&&(e.sweepDeg<1?i("Path.Stationary",!1):i((e.straysDeg??0)<Math.max(1,e.sweepDeg*.1)?"Path.StraightLineContinuous":"Path.Complex",!1)),e.speedDegPerS!==void 0){const n=e.speedDegPerS;i((e.speedVariation??0)>3?"AngularSpeed.Variable":n<.01?"AngularSpeed.VeryLowOrStationary":n>10?"AngularSpeed.VeryHighStreaking":"AngularSpeed.SlowLikePlaneAtHighAltitude",!1)}if(e.count!==void 0&&i(e.count>1?"ObjectsCount.Several":"ObjectsCount.Single"),e.aligned&&i("Formation.Line"),e.round!==void 0&&i(e.round?"ObjectShape.Round":"ObjectShape.Other",!1),e.colors&&e.colors.length>0){const n=e.colors.length>1?"Color.MutipleLights":ki.colorClass(e.colors[0]);n&&i(n)}return e.brightness!==void 0&&e.brightness>=.5&&i("Luminosity.Intense",!1),e.observers!==void 0&&i(e.observers>1?"IndependentWitnessesCount.Several":"IndependentWitnessesCount.Single",this.conditions?.independent!==!1),e.sound&&i("Noise.Perceived"),e.nakedEye&&i("Detection.NakedEye"),t}static colorClass(e){const t=/^#([0-9a-f]{6})$/i.exec(e);if(!t)return;const i=parseInt(t[1],16),[s,n,r]=[i>>16&255,i>>8&255,i&255],o=Math.max(s,n,r),a=Math.min(s,n,r);return o-a<40?"Color.White":s===o&&n<s*.85&&r<s*.6?"Color.RedOrange":n===o&&s<n*.7?"Color.Green":void 0}}class ne{constructor(e,t){this.host=e,this.section=t}static CSS=`
133
+ `;fields=[];model=te.MODELS[0];sections=[];observerShown;attach(e){this.fields.push(e);const t=document.createElement(et.TAG);t.addEventListener("basischange",n=>this.said(e,n.detail.entry));const i=e.label.firstElementChild;i?i.after(t):e.label.prepend(t);const s=document.createElement("span");s.className="law",e.label.append(s),e.input.addEventListener("input",()=>this.retyped(e)),e.input.addEventListener("change",()=>this.retyped(e))}refresh(){this.refreshFields(),this.renderObserver(),this.host.lawsChanged()}get errorModel(){return this.model}refreshFields(){for(const e of this.fields)this.refreshField(e)}entryOf(e){const t=e.path();return t===void 0?void 0:this.host.sighting.provenance.at(t)}refreshField(e,t){const i=this.host.messages();if(!i)return;const s=this.entryOf(e),n=s?.basis??"stated",r=e.label.querySelector(et.TAG);r.hows=te.HOW[e.kind].map(l=>({value:l,label:i.how[l]??l})),r.messages={title:i.basisTitle,basis:i.basis,basisField:i.basisField,howField:i.howField,rationaleField:i.rationaleField};const o=this.host.valueSources?.();r.sourceMessages=o?.messages,r.choices=o?.choices??{},r.entry=s,r.hidden=e.path()===void 0,e.label.dataset.basis=n;const a=e.label.querySelector(".law");if(t){this.showLaw(a,[Object.assign(document.createElement("span"),{className:"law-reset",textContent:i.basisReset.replace("{basis}",i.basis[t])})]);return}const d=e.value();this.showLaw(a,d===void 0?[]:this.lawNodes(this.model.law({kind:e.kind,value:d,basis:n,how:s?.how},this.conditions),e.kind))}showLaw(e,t){const i=t.map(s=>s instanceof HTMLElement?`${s.className}|${s.textContent}|${s.title}|${s.dataset.status??""}`:s.textContent).join(`
134
+ `);e.dataset.said!==i&&(e.dataset.said=i,e.replaceChildren(...t))}lawNodes(e,t){const i=this.host.messages(),s=Object.assign(document.createElement("span"),{className:"law-symbol",textContent:e.shape==="uninformative"?"∅":"≈"});let n=i.laws[e.note];for(const[a,d]of Object.entries(e.params??{}))n=n.replaceAll(`{${a}}`,this.number(te.rounded(d)));e.low!==void 0&&(n=n.replaceAll("{low}",this.withUnit(e.low,t))),e.high!==void 0&&(n=n.replaceAll("{high}",this.withUnit(e.high,t)));const r=Object.assign(document.createElement("span"),{textContent:n});e.sources.length>0&&(r.title=i.lawSources.replace("{sources}",e.sources.join(", ")));const o=Object.assign(document.createElement("span"),{className:"lead-status",textContent:i.status[e.status]});return o.dataset.status=e.status,[s,r,o]}number(e){return e.toLocaleString(document.documentElement.lang||void 0,{maximumFractionDigits:Math.abs(e)<1?6:2})}withUnit(e,t){const i=te.rounded(e);switch(t){case"duration":return i>=90?`${this.number(te.rounded(i/60))} min`:`${this.number(i)} s`;case"time":return`${this.number(i)} min`;case"distance":return`${this.number(i)} m`;default:return`${this.number(i)}°`}}retyped(e){const t=e.path(),i=t===void 0?void 0:this.host.sighting.provenance.at(t);if(!t||!i||i.basis==="stated"&&i.how===void 0){this.refreshField(e);return}this.host.sighting.provenance.clear(t),this.refreshField(e,i.basis==="stated"?void 0:i.basis),setTimeout(()=>this.refreshField(e),4e3)}said(e,t){const i=e.path();i!==void 0&&(t?this.host.sighting.provenance.set(i,{...t,...e.value()!==void 0?{of:this.valueAt(i)}:{}}):this.host.sighting.provenance.clear(i),this.host.changed(),this.refreshField(e))}valueAt(e){const t=s=>s&&typeof s=="object"&&!Array.isArray(s)&&"value"in s?s.value:s;let i=this.host.recordingJson();for(const s of e.split("."))i=i&&typeof i=="object"?t(i[s]):void 0;return t(i)}get conditions(){return this.host.sighting.account?.conditions}setConditions(e){const t={...this.conditions??{},...e};for(const i of Object.keys(t))t[i]===void 0&&delete t[i];this.host.conditionsChanged(Object.keys(t).length>0?t:void 0),this.host.changed(),this.refresh()}placeObserverSections(e){const t=()=>{const s=document.createElement("div");return s.className="form-section witness-error",this.sections.push(s),s},i=[t(),t(),t(),t()];i.forEach((s,n)=>{s.dataset.icon=["witness-conditions","viewing-conditions","moon-gauge","error-parameters"][n]}),e.after(...i),this.renderObserver()}renderObserver(){if(this.sections.length===0)return;const e=this.host.messages();if(!e)return;const t=this.conditions??{},i={messages:e,model:this.model,conditions:JSON.stringify([t,this.host.sighting.provenance.at("time")?.how,this.daylight()])},s=this.observerShown;if(s&&s.messages===i.messages&&s.model===i.model&&s.conditions===i.conditions)return;this.observerShown=i;const[n,r,o,a]=this.sections,d=m=>Object.assign(document.createElement("h3"),{className:"section-title",textContent:m}),l=(m,f,g)=>{const b=document.createElement("label");return b.append(Object.assign(document.createElement("span"),{textContent:m}),f),g&&b.append(` ${g}`),b},h=(m,f,g="1")=>{const b=document.createElement("input");return b.type="number",b.min="0",b.step=g,b.value=m===void 0?"":String(m),b.addEventListener("change",()=>f(b.value.trim()===""||!Number.isFinite(Number(b.value))?void 0:Number(b.value))),b},c=(m,f,g)=>{const b=document.createElement("select");return b.append(new Option(e.unknownChoice,""),...f.map(([v,E])=>new Option(E,v))),b.value=m??"",b.addEventListener("change",()=>g(b.value===""?void 0:b.value)),b},u=(m,f,g,b)=>{const v=document.createElement("label"),E=document.createElement("input");return E.type="checkbox",E.checked=f===!0,E.addEventListener("change",()=>g(E.checked?!0:void 0)),v.append(E,` ${m}`),b&&v.append(Ae.of(b)),v},p=document.createElement("select");p.append(new Option(e.unknownChoice,""),new Option(e.independentYes,"yes"),new Option(e.independentNo,"no")),p.value=t.independent===void 0?"":t.independent?"yes":"no",p.addEventListener("change",()=>this.setConditions({independent:p.value===""?void 0:p.value==="yes"})),n.replaceChildren(d(e.sectionAccountConditions),l(e.delayField,h(t.delayDays,m=>this.setConditions({delayDays:m})),e.delayUnit),l(e.versionField,h(t.version,m=>this.setConditions({version:m}))),l(e.wordField,c(t.word,Object.entries(e.words),m=>this.setConditions({word:m}))),l(e.exposureField,c(t.exposure,Object.entries(e.exposures),m=>this.setConditions({exposure:m}))),l(e.independenceField,p)),r.replaceChildren(d(e.sectionViewing),u(e.darkAdapted,t.darkAdapted,m=>this.setConditions({darkAdapted:m})),u(e.correctedVision,t.correctedVision,m=>this.setConditions({correctedVision:m}),e.correctedVisionHint),u(e.glare,t.glare,m=>this.setConditions({glare:m})),Object.assign(document.createElement("p"),{className:"section-intro",textContent:e.viewingNote})),o.replaceChildren(d(e.sectionMoon),Object.assign(document.createElement("p"),{className:"section-intro",textContent:e.moonIntro}),this.moonGauge(t)),this.renderParameters(a,t)}moonGauge(e){const t=this.host.messages(),i=te.moonFactor(e),s=document.createElement("div");s.className="moon-gauge";const n=document.createElement("div");n.className="moon-picture";const r=12,o=i===void 0?void 0:Math.min(70,r*i);n.innerHTML=`<svg viewBox="0 0 150 150" width="150" height="150" aria-hidden="true"><circle cx="75" cy="72" r="${r}" fill="#efe9d6"/>${o!==void 0?`<circle cx="75" cy="72" r="${o}" fill="none" stroke="#f5c451" stroke-width="1.5" stroke-dasharray="4 3"/>`:""}</svg>`,n.append(Object.assign(document.createElement("span"),{textContent:t.moonReal}));const a=document.createElement("div");a.className="moon-side";const d=document.createElement("label"),l=document.createElement("input");l.type="number",l.min="0",l.step="0.1",l.placeholder="1,7",l.value=e.moonShownDeg===void 0?"":String(e.moonShownDeg),l.addEventListener("change",()=>this.setConditions({moonShownDeg:l.value.trim()===""||!(Number(l.value)>0)?void 0:Number(l.value)})),d.append(Object.assign(document.createElement("span"),{textContent:t.moonField}),l," °");const h=Object.assign(document.createElement("span"),{className:"section-intro",textContent:t.moonHint}),c=this.model.parameters().find(m=>m.id==="size");let u=t.parameters[c.note];for(const[m,f]of Object.entries(c.params??{}))u=u.replaceAll(`{${m}}`,this.number(f));const p=Object.assign(document.createElement("p"),{className:"note",textContent:i===void 0?t.moonNone.replace("{law}",`${u}, ${t.status[c.status]}`):t.moonFactor.replace("{k}",this.number(te.rounded(i)))});return a.append(d,h,p),s.append(n,a),s}renderParameters(e,t){const i=this.host.messages(),s=document.createElement("div");s.className="section-head";const n=document.createElement("label");n.className="model-pick";const r=document.createElement("select");for(const l of te.MODELS)r.append(new Option(i.models[l.id]??l.title,l.id));r.value=this.model.id,r.addEventListener("change",()=>{this.model=te.byId(r.value),this.refresh()}),n.append(i.errorModelField,r),s.append(Object.assign(document.createElement("h3"),{className:"section-title",textContent:i.sectionErrorParameters}),n);const o=this.host.sighting.provenance.at("time")?.how,a=document.createElement("div");a.className="parameter-rows";for(const l of this.model.parameters(t,o)){const h=document.createElement("div");h.className="parameter-row";let c=i.parameters[l.note];for(const[m,f]of Object.entries(l.params??{}))c=c.replaceAll(`{${m}}`,this.number(te.rounded(f)));const u=Object.assign(document.createElement("span"),{className:"lead-status",textContent:i.status[l.status]});u.dataset.status=l.status;const p=document.createElement("span");p.append(c,Object.assign(document.createElement("span"),{className:"scope",textContent:` · ${i.parameterScopes[l.id]}`})),h.append(Object.assign(document.createElement("strong"),{textContent:i.parameterNames[l.id]}),p,u),a.append(h)}const d=[s,Object.assign(document.createElement("p"),{className:"section-intro",textContent:i.parametersIntro}),a];this.daylight()&&d.push(Object.assign(document.createElement("p"),{className:"extrapolation",textContent:i.extrapolation})),e.replaceChildren(...d)}daylight(){const e=this.host.sighting.event,t=e.place?.[0];if(!t||!e.time)return!1;const i=be(e.time,t.lng,e.utcOffsetHours);return i!==void 0&&V("Sun",i,{lat:t.lat,lng:t.lng,elevationM:0}).altitudeDeg>0}}class z{constructor(e,t){this.model=e,this.conditions=t}static BOUND_SIGMA=3;static TAIL_SIGMA=2;static POINT_SIZE_DEG=.1;static MOVED_DEG=2;static STILL_DEG=.5;static SWEEP_SIGMA_DEG=5*Math.SQRT2;static STILL_SEEN_MOVING_MAX_DEG=10;static GROWTH=1.5;static BRIGHTENING_MAG=.5;static READING_STATUS={grouped:"consolidated","still-seen-moving":"consolidated","moving-seen-still":"argued","brightening-as-approach":"argued"};static ELEVATION_SIGMA_DEG=5;fit(e,t){const i=this.model.law({kind:"time",value:0,how:e.timeHow},this.conditions),s=Math.max(.5,(i.high??6)/2);let n;const r=24;for(let o=0;o<=r;o++){const a=-3*s+2*z.BOUND_SIGMA*s*o/r,d=t.at(a);if(!d)continue;const l=this.variantAt(e,t,a,s,i.status,d);(!n||l.cost<n.cost)&&(n=l)}return n??{candidate:t.id,label:t.label,verdict:"incompatible",cost:1/0,reason:"never-seen",moved:[],readings:[],parameters:{clockMinutes:0,headingDeg:0,elevationFactor:1,sizeFactor:1},modelId:this.model.id}}search(e,t){const i={consolidated:0,contested:1,incompatible:2};return t.map(s=>this.fit(e,s)).sort((s,n)=>i[s.verdict]-i[n.verdict]||s.cost-n.cost)}variantAt(e,t,i,s,n,r){const o=[];let a;Math.abs(i)>.05&&o.push({field:"time",stated:0,variant:i,parameter:"clock",amount:i,z:i/s,status:n});let d=0,l=1;if(e.aim){const v=this.model.law({kind:"heading",value:e.aim.azimuthDeg,how:e.headingHow},this.conditions),E=((v.high??e.aim.azimuthDeg+45)-e.aim.azimuthDeg)/2;d=((r.aim.azimuthDeg-e.aim.azimuthDeg)%360+540)%360-180,Math.abs(d)>.5&&o.push({field:"heading",stated:e.aim.azimuthDeg,variant:(r.aim.azimuthDeg+360)%360,parameter:"heading",amount:d,z:d/E,status:v.status});const x=e.aim.altitudeDeg,S=this.model.law({kind:"elevation",value:x},this.conditions),I=S.low??x,C=S.high??x,R=r.aim.altitudeDeg,T=R>C?(R-C)/z.ELEVATION_SIGMA_DEG:R<I?(I-R)/z.ELEVATION_SIGMA_DEG:0;l=x>0?R/x:1,Math.abs(R-x)>.5&&o.push({field:"elevation",stated:x,variant:R,parameter:"elevation",amount:l,z:T,status:T>0?"argued":S.status})}let h=1;if(e.widthDeg!==void 0&&e.widthDeg>0){const v=Math.max(r.widthDeg,z.POINT_SIZE_DEG),E=this.model.law({kind:"angularSize",value:e.widthDeg,how:e.sizeHow},this.conditions),x=E.low??e.widthDeg,S=E.high??e.widthDeg,I=v>S?Math.log(v/S)/Math.log(1.5):v<x?Math.log(x/v)/Math.log(1.5):0;h=e.widthDeg/v,Math.abs(Math.log(h))>Math.log(1.1)&&o.push({field:"size",stated:e.widthDeg,variant:v,parameter:"size",amount:h,z:I,status:E.status})}const{readings:c,lacking:u}=this.structural(e,t,i,r);let p;if(!u&&!c.some(v=>v.reading==="still-seen-moving"||v.reading==="moving-seen-still")){const v=this.motionFit(e,t,i,r);v&&(p=v.factor,o.push(...v.moved))}const m=Math.sqrt(o.reduce((v,E)=>v+E.z*E.z,0)),f=o.find(v=>Math.abs(v.z)>z.BOUND_SIGMA);f&&(a=f.field==="size"?"size":f.field==="duration"||f.field==="sweep"?"motion":"direction"),!a&&u&&(a=u);const g=o.some(v=>v.status==="contested"||Math.abs(v.z)>z.TAIL_SIGMA)||c.some(v=>v.status!=="consolidated"),b=a?"incompatible":g?"contested":"consolidated";return{candidate:t.id,label:t.label,verdict:b,cost:te.rounded(m),moved:o,readings:c,...a?{reason:a}:{},parameters:{clockMinutes:i,headingDeg:d,elevationFactor:l,sizeFactor:h,...p!==void 0?{durationFactor:p}:{}},modelId:this.model.id}}motionFit(e,t,i,s){const n=e.motion;if(!n||n.spanMinutes<=0||n.sweepDeg<z.MOVED_DEG)return;const r=n.spanMinutes*60,o=this.model.law({kind:"duration",value:r},this.conditions),a=Math.log((o.high??r*3)/r)/2;let d;const l=24;for(let c=0;c<=l;c++){const u=Math.exp(a*z.BOUND_SIGMA*(2*c/l-1)),p=t.at(i+n.spanMinutes*u);if(!p)continue;const m=z.separation(s.aim,p.aim),f=Math.log(u)/a,g=(m-n.sweepDeg)/z.SWEEP_SIGMA_DEG;(!d||f**2+g**2<d.zDuration**2+d.zSweep**2)&&(d={factor:u,sweep:m,zDuration:f,zSweep:g})}if(!d||d.sweep<z.STILL_DEG)return;const h=[];return Math.abs(Math.log(d.factor))>Math.log(1.1)&&h.push({field:"duration",stated:r,variant:r*d.factor,parameter:"duration",amount:d.factor,z:d.zDuration,status:o.status}),Math.abs(d.sweep-n.sweepDeg)>1&&h.push({field:"sweep",stated:n.sweepDeg,variant:d.sweep,parameter:"sweep",amount:d.sweep-n.sweepDeg,z:d.zSweep,status:"argued"}),{factor:d.factor,moved:h}}structural(e,t,i,s){const n=t.readings??[],r=[],o=e.motion,a=o&&o.spanMinutes>0?t.at(i+o.spanMinutes):void 0;if(o&&a){const l=z.separation(s.aim,a.aim);if(o.sweepDeg>=z.MOVED_DEG&&l<z.STILL_DEG){if(o.sweepDeg>z.STILL_SEEN_MOVING_MAX_DEG)return{readings:[],lacking:"motion"};r.push(["still-seen-moving","motion"])}else o.sweepDeg<z.STILL_DEG&&l>=z.MOVED_DEG&&r.push(["moving-seen-still","motion"])}if(e.growth!==void 0&&e.growth>=z.GROWTH&&a&&a.widthDeg/Math.max(s.widthDeg,1e-6)<z.GROWTH)if(s.magnitude===void 0||a.magnitude===void 0||s.magnitude-a.magnitude>=z.BRIGHTENING_MAG)r.push(["brightening-as-approach","growth"]);else return{readings:[],lacking:"growth"};const d=n.includes("grouped")?[{reading:"grouped",status:z.READING_STATUS.grouped}]:[];for(const[l,h]of r){if(!n.includes(l))return{readings:d,lacking:h};d.push({reading:l,status:z.READING_STATUS[l]})}return{readings:d}}static separation(e,t){const i=Math.PI/180,s=Math.sin(e.altitudeDeg*i)*Math.sin(t.altitudeDeg*i)+Math.cos(e.altitudeDeg*i)*Math.cos(t.altitudeDeg*i)*Math.cos((e.azimuthDeg-t.azimuthDeg)*i);return Math.acos(Math.max(-1,Math.min(1,s)))/i}}class Ue{constructor(e,t){this.reasons=t;for(const i of e){const s=i.knownPhenomenaProbabilities??i.knownPhenomenonProbabilities??{};this.scores.set(i.question,s);for(const n of Object.keys(s))this.phenomena.includes(n)||this.phenomena.push(n)}}static BASE_URL="https://raw.githubusercontent.com/RR0/rr0.org/master/";static VERSIONS={"poher-1977":"time/1/9/7/7/Poher_Matrice/","rr0-2026":"time/2/0/2/6/10/Poher_Matrice_RR0/"};static DEFAULT_VERSION="rr0-2026";scores=new Map;phenomena=[];has(e){return this.scores.has(e)}reason(e,t){return this.reasons?.cells[e]?.[t]}rank(e){const t=e.filter(s=>this.scores.has(s.question));return this.phenomena.map(s=>{const n=[],r=[];let o=0,a=0;for(const d of t){const l=this.scores.get(d.question)[s];l!==void 0&&(a++,o+=l,l===0&&(d.firm?n:r).push(d.question))}return{phenomenon:s,excludedBy:n,doubtedBy:r,mean:a>0?o/a:0,added:this.reasons?.phenomena[s]!==void 0}}).sort((s,n)=>(s.excludedBy.length>0?1:0)-(n.excludedBy.length>0?1:0)||s.excludedBy.length-n.excludedBy.length||n.mean-s.mean)}static async load(e,t,i){const s=["fr","en","it"].includes(t)?t:"en",n=`${Ue.BASE_URL}${Ue.VERSIONS[e]}`,[r,o,a]=await Promise.all([i(`${n}matrix.json`),i(`${n}Matrix_${s}.json`),e==="poher-1977"?void 0:i(`${n}reasons.json`)]);return{matrix:new Ue(r,a),labels:o}}}class ki{constructor(e,t){this.model=e,this.conditions=t}of(e){const t=[],i=(n,r=!0)=>t.push({question:n,firm:r});e.sunAltitudeDeg!==void 0&&i(e.sunAltitudeDeg>0?"Hour.Day":e.sunAltitudeDeg<-6?"Hour.Night":"Hour.Twilight");const s=(n,r,o)=>{if(r===void 0)return;const a=c=>o.find(([u])=>c<u)?.[1]??o[o.length-1][1],d=this.model.law({kind:n,value:r},this.conditions),l=a(r),h=d.shape==="range"&&a(d.low??r)===l&&a(d.high??r)===l;i(l,h)};if(s("duration",e.durationSeconds,[[10,"Duration.LessThan10s"],[3600,"Duration.AFewMn"],[1/0,"Duration.Above1h"]]),s("elevation",e.elevationDeg,[[5,"AngularHeight.LowOnHorizon"],[30,"AngularHeight.LessThan30d"],[1/0,"AngularHeight.HighInSky"]]),s("angularSize",e.widthDeg,[[.2,"ApparentSize.Pointlike"],[1,"ApparentSize.SimilarToMoon30s"],[1/0,"ApparentSize.SeveralDegrees"]]),e.cloudCover!==void 0&&(e.cloudCover<.2?i("WeatherConditions.NiceAndAlmostClearSky"):e.cloudCover>.8&&i("WeatherConditions.Overcast")),e.lightning&&i("WeatherConditions.Thunder"),e.lowVisibility&&i("WeatherConditions.LowVisibility"),e.sweepDeg!==void 0&&(e.sweepDeg<1?i("Path.Stationary",!1):i((e.straysDeg??0)<Math.max(1,e.sweepDeg*.1)?"Path.StraightLineContinuous":"Path.Complex",!1)),e.speedDegPerS!==void 0){const n=e.speedDegPerS;i((e.speedVariation??0)>3?"AngularSpeed.Variable":n<.01?"AngularSpeed.VeryLowOrStationary":n>10?"AngularSpeed.VeryHighStreaking":"AngularSpeed.SlowLikePlaneAtHighAltitude",!1)}if(e.count!==void 0&&i(e.count>1?"ObjectsCount.Several":"ObjectsCount.Single"),e.aligned&&i("Formation.Line"),e.round!==void 0&&i(e.round?"ObjectShape.Round":"ObjectShape.Other",!1),e.colors&&e.colors.length>0){const n=e.colors.length>1?"Color.MutipleLights":ki.colorClass(e.colors[0]);n&&i(n)}return e.brightness!==void 0&&e.brightness>=.5&&i("Luminosity.Intense",!1),e.observers!==void 0&&i(e.observers>1?"IndependentWitnessesCount.Several":"IndependentWitnessesCount.Single",this.conditions?.independent!==!1),e.sound&&i("Noise.Perceived"),e.nakedEye&&i("Detection.NakedEye"),t}static colorClass(e){const t=/^#([0-9a-f]{6})$/i.exec(e);if(!t)return;const i=parseInt(t[1],16),[s,n,r]=[i>>16&255,i>>8&255,i&255],o=Math.max(s,n,r),a=Math.min(s,n,r);return o-a<40?"Color.White":s===o&&n<s*.85&&r<s*.6?"Color.RedOrange":n===o&&s<n*.7?"Color.Green":void 0}}class ne{constructor(e,t){this.host=e,this.section=t}static CSS=`
135
135
  .candidates { display: grid; gap: 8px; }
136
136
  .candidate { border: 1px solid var(--line-strong); border-radius: 10px; background: var(--ground); }
137
137
  .candidate-head { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; gap: 10px; align-items: center; width: 100%; min-height: 46px; padding: 0 14px;
@@ -178,7 +178,7 @@ ${C.titles("::before","[data-chosen]")} { display: none; }
178
178
  .variant-badge { position: absolute; top: 10px; left: 10px; z-index: 5; display: inline-flex; align-items: center; gap: 10px; padding: 4px 6px 4px 12px;
179
179
  border-radius: 999px; background: rgba(127, 212, 255, .94); color: #07111c; font: 600 13px/1.3 var(--sans); }
180
180
  .variant-badge button { min-height: 28px; padding: 0 10px; border: 0; border-radius: 999px; background: rgba(7, 10, 18, .85); color: #e8ecf4; font: 600 12px/1 var(--sans); }
181
- `;static PLANETS=["Venus","Mars","Jupiter","Saturn"];static STARS=6;static STAR_MAG=1.5;static SATELLITES=4;static AIRCRAFT=12;static AIRCRAFT_RANGE_KM=80;static SPAN_M=35;static FT_M=.3048;statementT=0;poher;poherState="idle";poherVersion=ne.storedVersion();static VERSION_STORAGE="ufoathome.poherMatrixVersion";kindsLoading=new WeakSet;phenomenonOf=new Map;variants=[];shown;open=new Set;statement(){const e=this.host.sighting,t=e.timeline,i=t.sourceIds[0];if(!i)return;const s=t.allKeyframes.find(d=>d.shapes.some(l=>l.sourceId===i))?.t??0;this.statementT=s;const n=t.getInterpolatedShapeAt(s,i);if(!n?.aim)return;const r={aim:n.aim,widthDeg:n.angular?.widthDeg,timeHow:e.provenance.at("time")?.how},o=[...t.allKeyframes].reverse().find(d=>d.t>s&&t.getShapeAt(d.t,i)?.aim),a=o?t.getInterpolatedShapeAt(o.t,i):void 0;if(o&&a?.aim){r.motion={sweepDeg:z.separation(n.aim,a.aim),spanMinutes:(o.t-s)/6e4};const d=n.angular?.widthDeg,l=a.angular?.widthDeg;d&&l&&(r.growth=l/d)}return r}tracks(e){const t=this.host.start();if(!t)return[];const i=this.host.messages().candidates.bodies,s=o=>({id:o,label:i[o]??o,at:a=>{const d=new Date(t.date.getTime()+this.statementT+a*6e4),l=V(o,d,t.observer);if(l.altitudeDeg<0)return;const h=V("Sun",d,t.observer).altitudeDeg,c=o==="Moon"?-10:nn(o,d);if(!(c>this.host.limitAt(h)))return{aim:{azimuthDeg:l.azimuthDeg,altitudeDeg:l.altitudeDeg},widthDeg:o==="Moon"?ee.MOON_DEG:.01,magnitude:c}},readings:["still-seen-moving"]});this.phenomenonOf.clear();const n=[s("Moon")];this.phenomenonOf.set("Moon","Moon");for(const o of ne.PLANETS)n.push(s(o)),this.phenomenonOf.set(o,"Planets");n.push(...this.starTracks(t,e));const r=this.host.satellites();if(r){const o=new Map,a=l=>(o.has(l.getTime())||o.set(l.getTime(),r.positionsAt(l)),o.get(l.getTime())),d=[...r.passes].sort((l,h)=>(l.peak.magnitude??99)-(h.peak.magnitude??99)).slice(0,ne.SATELLITES);for(const l of d){const h=`satellite-${l.object.norad}`;n.push({id:h,label:l.object.name,at:c=>{const u=a(new Date(t.date.getTime()+this.statementT+c*6e4))?.find(p=>p.object.norad===l.object.norad);if(!(!u||u.altitudeDeg<0||u.sunlitFraction<.5))return{aim:{azimuthDeg:u.azimuthDeg,altitudeDeg:u.altitudeDeg},widthDeg:.01,magnitude:u.magnitude}},readings:["brightening-as-approach"]}),this.phenomenonOf.set(h,"OrbitingSatellites")}}return n.push(...this.burningTracks(t),...this.aircraftTracks(t),...this.interpretationTracks()),n}starTracks(e,t){const i=this.host.messages().candidates,s=h=>new Date(e.date.getTime()+this.statementT+h*6e4),n=h=>V("Sun",h,e.observer).altitudeDeg,r=this.host.limitAt(n(s(0))),o=t.aim,a=Math.PI/180,d=h=>o?Math.acos(Math.min(1,Math.sin(o.altitudeDeg*a)*Math.sin(h.altitudeDeg*a)+Math.cos(o.altitudeDeg*a)*Math.cos(h.altitudeDeg*a)*Math.cos((h.azimuthDeg-o.azimuthDeg)*a)))/a:0;return sn.filter(h=>h.mag<=Math.min(r,ne.STAR_MAG)).map(h=>({star:h,position:Mi(h.raHours,h.decDeg,s(0),e.observer)})).filter(({position:h})=>h.altitudeDeg>0).sort((h,c)=>d(h.position)-d(c.position)||h.star.mag-c.star.mag).slice(0,ne.STARS).map(({star:h})=>{const c=`star-${h.name}`;return this.phenomenonOf.set(c,"Stars"),{id:c,label:i.star.replace("{name}",this.host.starName(h.name)),at:u=>{const p=s(u),m=Mi(h.raHours,h.decDeg,p,e.observer);if(!(m.altitudeDeg<0||h.mag>this.host.limitAt(n(p))))return{aim:{azimuthDeg:m.azimuthDeg,altitudeDeg:m.altitudeDeg},widthDeg:.01,magnitude:h.mag}},readings:["still-seen-moving"]}})}interpretationTracks(){const e=this.host.messages().candidates,t=this.host.sighting.timeline.sourceIds[0];return this.host.interpretations().flatMap(({id:i,label:s,interpretation:n})=>{const{interpretation:r,phenomenonOf:o,loaded:a}=this.host.computed(n);this.kindsLoading.has(n)||(this.kindsLoading.add(n),a.then(()=>{this.host.interpretations().some(h=>h.interpretation===n)&&this.refresh()}));const d=r.bodies.find(h=>t!==void 0&&h.explains?.includes(t))??r.bodies[0];if(!d)return[];const l=o.get(d.id);return l&&this.phenomenonOf.set(`interpretation-${i}`,l),[{id:`interpretation-${i}`,label:e.interpretation.replace("{name}",s),at:h=>{const c=this.host.projectionAt(d,this.statementT+h*6e4);return c?{aim:c.aim,widthDeg:c.angular.widthDeg}:void 0}}]})}burningTracks(e){const t=this.host.messages().candidates,{reentries:i,fireballs:s}=this.host.burning(),n={lat:e.observer.lat,lng:e.observer.lng,heightM:e.observer.elevationM},r=(o,a)=>{const d=`${a?"fireball":"reentry"}-${o.id}`;this.phenomenonOf.set(d,a?"Meteorits":"AtmosphericSatellitesReentry");const l=o.object?.name??o.id;return{id:d,label:(a?t.fireball:t.reentry).replace("{name}",l),at:h=>{const c=this.statementT+h*6e4,u=Kt.viewsAt([o],c,n).filter(g=>g.head.altitudeDeg>=0);if(u.length===0)return;const p=V("Sun",new Date(e.date.getTime()+c),e.observer).altitudeDeg,m=u.reduce((g,b)=>b.magnitude<g.magnitude?b:g);if(m.magnitude>this.host.limitAt(p))return;let f=0;for(const g of u)for(const b of u)f=Math.max(f,Math.hypot(g.head.azimuthDeg-b.head.azimuthDeg,g.head.altitudeDeg-b.head.altitudeDeg));return{aim:{azimuthDeg:m.head.azimuthDeg,altitudeDeg:m.head.altitudeDeg},widthDeg:Math.max(.01,f),magnitude:m.magnitude}},readings:["grouped","brightening-as-approach"]}};return[...i.map(o=>r(o,!1)),...s.map(o=>r(o,!0))]}aircraftTracks(e){const t=this.host.traffic();if(!t)return[];const i=this.host.messages().candidates,s={lat:e.observer.lat,lng:e.observer.lng,heightM:e.observer.elevationM},n=t.startMs+this.statementT,r=(a,d)=>{const l=a.points;if(l.length===0||d<l[0].t||d>l[l.length-1].t)return;let h=0;for(;h<l.length-2&&l[h+1].t<d;)h++;const c=l[h],u=l[Math.min(h+1,l.length-1)],p=u.t>c.t?(d-c.t)/(u.t-c.t):0;return{lat:c.lat+(u.lat-c.lat)*p,lng:c.lng+(u.lng-c.lng)*p,heightM:(c.altitudeFt+(u.altitudeFt-c.altitudeFt)*p)*ne.FT_M}};return t.tracks.map(a=>({track:a,point:r(a,n)})).filter(a=>a.point!==void 0).map(a=>({...a,seen:Kt.seenFrom(s,a.point)})).filter(a=>a.seen.distanceKm<=ne.AIRCRAFT_RANGE_KM).sort((a,d)=>a.seen.distanceKm-d.seen.distanceKm).slice(0,ne.AIRCRAFT).map(({track:a,point:d})=>{const l=t.describe(a),h=`aircraft-${a.icao}`;this.phenomenonOf.set(h,l?.category==="A7"?"Helicopters":d.heightM>15e3*ne.FT_M?"HighAltitudePlanes":"LowAltitudePlanes");const c=l?.restricted?a.icao.toString(16).toUpperCase():[l?.type,l?.registration].filter(Boolean).join(" ")||a.icao.toString(16).toUpperCase();return{id:h,label:i.aircraft.replace("{name}",c),at:u=>{const p=r(a,n+u*6e4);if(!p)return;const m=Kt.seenFrom(s,p);if(m.altitudeDeg<0||m.distanceKm>ne.AIRCRAFT_RANGE_KM)return;const f=Math.atan2(ne.SPAN_M,m.distanceKm*1e3)*180/Math.PI;return{aim:{azimuthDeg:m.azimuthDeg,altitudeDeg:m.altitudeDeg},widthDeg:f}},readings:["grouped","moving-seen-still","brightening-as-approach"]}})}ranking(){if(!this.poher)return;const e=new ki(this.host.model(),this.host.conditions()).of(this.host.facts()).filter(t=>this.poher.matrix.has(t.question));return{rows:this.poher.matrix.rank(e),answers:e}}languageChanged(){this.poherState!=="loading"&&(this.poherState="idle",this.poher=void 0)}loadPoher(){if(this.poherState!=="idle")return;this.poherState="loading";const e=this.poherVersion;this.host.poher(e).then(t=>{e===this.poherVersion&&(this.poher=t,this.poherState="ready",this.refresh())},()=>{e===this.poherVersion&&(this.poherState="failed",this.refresh())})}refresh(){const e=this.host.messages().candidates,t=this.statement(),i=this.host.start();this.variants=t&&i?new z(this.host.model(),this.host.conditions()).search(t,this.tracks(t)):[];const n=[Object.assign(document.createElement("h3"),{className:"section-title",textContent:e.title})];this.loadPoher();const r=this.ranking();if(n.push(this.versionChoice()),this.poherState==="loading"&&n.push(this.note(e.poherLoading)),this.poherState==="failed"&&n.push(this.note(e.poherFailed)),r&&n.push(this.answersBlock(r.answers)),!t)n.push(this.note(e.noDirection));else if(!i)n.push(this.note(e.noSky));else{const d=document.createElement("div");d.className="candidates",d.append(...this.variants.map(l=>this.row(l,r?.rows.find(h=>h.phenomenon===this.phenomenonOf.get(l.candidate))))),n.push(d,this.note(e.costNote))}const o=this.keptBlock();o&&n.push(o),r&&n.push(this.poherBlock(r.rows)),n.push(this.note(e.scopeNote)),this.section.replaceChildren(...n);const a=this.shown&&this.variants.find(d=>d.candidate===this.shown.candidate);this.show(a&&a.verdict!=="incompatible"?a:void 0)}keep(e){const t=this.phenomenonOf.get(e.candidate),i=e.candidate.startsWith("interpretation-")?this.host.interpretations().find(({id:r})=>`interpretation-${r}`===e.candidate)?.interpretation:void 0,s={title:this.host.messages().candidates.variantLabel.replace("{name}",e.label),bodies:i?structuredClone(i.bodies):[],variant:{candidate:e.candidate,label:e.label,...t?{phenomenon:t}:{},parameters:e.parameters,moved:e.moved.map(r=>({...r})),...e.readings.length>0?{readings:e.readings.map(r=>({...r}))}:{},cost:e.cost,verdict:e.verdict,modelId:e.modelId}},n=this.host.variants().findIndex(r=>r.variant?.candidate===e.candidate&&r.variant?.modelId===e.modelId);n>=0&&this.host.remove(n),this.host.keep(s),this.refresh()}keptBlock(){const e=this.host.variants();if(e.length===0)return;const t=this.host.messages(),i=document.createElement("div");return i.className="kept-variants",i.append(Object.assign(document.createElement("h4"),{textContent:t.candidates.keptTitle.replace("{n}",String(e.length))})),e.forEach((s,n)=>{const r=s.variant;if(!r)return;const o=document.createElement("div");o.className="kept-variant";const a=Object.assign(document.createElement("span"),{className:"verdict",textContent:t.candidates.verdicts[r.verdict]});a.dataset.verdict=r.verdict;const d=Object.assign(document.createElement("span"),{className:"cost",textContent:t.candidates.cost.replace("{x}",this.number(r.cost))}),l=Object.assign(document.createElement("span"),{className:"cost",textContent:t.candidates.keptModel.replace("{model}",t.models[r.modelId]??r.modelId)});o.append(Object.assign(document.createElement("strong"),{textContent:r.label??r.candidate}),a,d,l);const h=this.variants.find(p=>p.candidate===r.candidate);h&&(h.verdict!==r.verdict||Math.abs(h.cost-r.cost)>.05||h.modelId!==r.modelId)&&o.append(Object.assign(document.createElement("span"),{className:"recomputed",textContent:t.candidates.keptRecomputed.replace("{verdict}",t.candidates.verdicts[h.verdict]).replace("{x}",this.number(h.cost))}));const c=document.createElement("button");c.type="button",c.className="pill-btn",c.textContent=t.candidates.seeKept,c.addEventListener("click",()=>this.show({candidate:r.candidate,label:r.label??r.candidate,verdict:r.verdict,cost:r.cost,parameters:r.parameters,moved:r.moved,readings:r.readings??[],modelId:r.modelId}));const u=document.createElement("button");u.type="button",u.className="pill-btn",u.textContent=t.candidates.removeVariant,u.addEventListener("click",()=>{this.host.remove(n),this.refresh()}),o.append(c,u),i.append(o)}),i}static storedVersion(){try{const e=localStorage.getItem(ne.VERSION_STORAGE);if(e&&e in Ue.VERSIONS)return e}catch{}return Ue.DEFAULT_VERSION}versionChoice(){const e=this.host.messages().candidates,t=Object.assign(document.createElement("label"),{className:"poher-version",textContent:e.poherVersion}),i=document.createElement("select");i.style.setProperty("field-sizing","content"),i.style.width="auto",i.style.maxWidth="100%";for(const s of Object.keys(Ue.VERSIONS))i.append(Object.assign(document.createElement("option"),{value:s,textContent:e.poherVersions[s],selected:s===this.poherVersion}));return i.addEventListener("change",()=>{this.poherVersion=i.value;try{localStorage.setItem(ne.VERSION_STORAGE,this.poherVersion)}catch{}this.poherState="idle",this.poher=void 0,this.refresh()}),t.append(i),t}exclusion(e){const t=this.host.messages().candidates;return t.poherExcludedBy.replace("{list}",e.excludedBy.map(i=>{const s=this.poher?.matrix.reason(e.phenomenon,i);return s?`${this.answerLabel(i)} (${t.poherRr0Reason.replace("{why}",s.why)})`:this.answerLabel(i)}).join(", "))}answerLabel(e){const t=this.poher?.labels??{},i=e.slice(0,e.indexOf("."));return`${t[i]??i} : ${t[e]??e.slice(e.indexOf(".")+1)}`}answersBlock(e){const t=this.host.messages().candidates,i=document.createElement("details");i.className="poher-answers",i.append(Object.assign(document.createElement("summary"),{textContent:t.answersTitle.replace("{n}",String(e.length))}));const s=document.createElement("ul");for(const n of e){const r=document.createElement("li");r.append(this.answerLabel(n.question)," ",Object.assign(document.createElement("span"),{className:"firmness",textContent:n.firm?t.firm:t.soft})),r.dataset.firm=String(n.firm),s.append(r)}return i.append(s),i}poherBlock(e){const t=this.host.messages().candidates,i=this.poher?.labels??{},s=new Set(this.phenomenonOf.values()),n=e.filter(h=>!s.has(h.phenomenon)),r=document.createElement("div");r.className="poher-block",r.append(Object.assign(document.createElement("h4"),{textContent:t.poherTitle.replace("{version}",t.poherVersions[this.poherVersion])}),Object.assign(document.createElement("p"),{className:"candidates-note",textContent:this.poher?.matrix.reasons?t.poherIntroRr0:t.poherIntro}));const o=h=>{const c=document.createElement("li");if(c.append(Object.assign(document.createElement("strong"),{textContent:i[h.phenomenon]??h.phenomenon})),h.added&&c.append(" ",Object.assign(document.createElement("span"),{className:"poher-tag",textContent:t.poherAdded})),h.excludedBy.length>0)c.append(" — ",this.exclusion(h));else{const u=document.createElement("span");u.className="poher-bar",u.style.setProperty("--score",String(h.mean)),c.append(" ",u," ",t.poherScore.replace("{x}",this.number(ee.rounded(h.mean)))),h.doubtedBy.length>0&&c.append(Object.assign(document.createElement("span"),{className:"doubt",textContent:` · ${t.poherDoubted.replace("{list}",h.doubtedBy.map(p=>this.answerLabel(p)).join(", "))}`}))}return c},a=n.filter(h=>h.excludedBy.length===0),d=n.filter(h=>h.excludedBy.length>0),l=document.createElement("ul");if(l.className="poher-list",l.append(...a.map(o)),r.append(Object.assign(document.createElement("h5"),{textContent:t.poherPossible}),l),d.length>0){const h=document.createElement("details");h.append(Object.assign(document.createElement("summary"),{textContent:t.poherExcluded.replace("{n}",String(d.length))}));const c=document.createElement("ul");c.className="poher-list",c.append(...d.map(o)),h.append(c),r.append(h)}return r}note(e){return Object.assign(document.createElement("p"),{className:"candidates-note",textContent:e})}row(e,t){const i=this.host.messages().candidates,s=document.createElement("div");s.className="candidate";const n=document.createElement("button");n.type="button",n.className="candidate-head",n.setAttribute("aria-expanded",String(this.open.has(e.candidate)));const r=Object.assign(document.createElement("span"),{className:"verdict",textContent:i.verdicts[e.verdict]});r.dataset.verdict=e.verdict;const o=Object.assign(document.createElement("span"),{className:"cost",textContent:Number.isFinite(e.cost)?i.cost.replace("{x}",this.number(e.cost)):""}),a=Object.assign(document.createElement("span"),{textContent:e.label});if(t){const l=Object.assign(document.createElement("span"),{className:"poher-tag",textContent:i.poherTag.replace("{state}",t.excludedBy.length>0?i.poherStateExcluded:i.poherStatePossible.replace("{x}",this.number(ee.rounded(t.mean))))});l.dataset.excluded=String(t.excludedBy.length>0),a.append(" ",l)}n.append(a,r,o);const d=document.createElement("div");d.className="candidate-body",d.hidden=!this.open.has(e.candidate),s.toggleAttribute("open",!d.hidden),n.addEventListener("click",()=>{this.open.has(e.candidate)?this.open.delete(e.candidate):this.open.add(e.candidate),d.hidden=!d.hidden,s.toggleAttribute("open",!d.hidden),n.setAttribute("aria-expanded",String(!d.hidden))}),t&&t.excludedBy.length>0&&d.append(Object.assign(document.createElement("p"),{className:"candidate-reason",textContent:`${i.poherTag.replace("{state}",i.poherStateExcluded)} — ${this.exclusion(t)}`})),e.verdict==="incompatible"&&d.append(Object.assign(document.createElement("p"),{className:"candidate-reason",textContent:`${i.reasons[e.reason??"direction"]} ${i.notAgainst}`}));for(const l of e.moved)d.append(this.movedRow(l));for(const l of e.readings)d.append(this.readingRow(l));if(e.verdict!=="incompatible"){const l=document.createElement("button");l.type="button",l.className="pill-btn",l.textContent=i.seeVariant,l.addEventListener("click",()=>this.show(e));const h=document.createElement("button");h.type="button",h.className="pill-btn",h.textContent=i.keepVariant,h.addEventListener("click",()=>this.keep(e));const c=document.createElement("div");c.className="candidate-actions",c.append(l,h),d.append(c)}return s.append(n,d),s}readingRow(e){const t=this.host.messages().candidates,i=document.createElement("div");return i.className="moved-row reading-row",i.append(Object.assign(document.createElement("span"),{textContent:t.readingTitle}),Object.assign(document.createElement("span"),{className:"bias",textContent:t.readings[e.reading]}),this.status(e.status)),i}movedRow(e){const t=this.host.messages(),i=document.createElement("div");i.className="moved-row";const[s,n]=this.values(e),r=document.createElement("span");r.append(Object.assign(document.createElement("s"),{textContent:s})," → ",Object.assign(document.createElement("b"),{textContent:n}));const o=e.parameter==="clock"||e.parameter==="heading"||e.parameter==="sweep"?`${e.amount>0?"+":""}${this.number(ee.rounded(e.amount))}`:this.number(ee.rounded(e.amount));return i.append(Object.assign(document.createElement("span"),{textContent:t.candidates.fields[e.field]}),r,Object.assign(document.createElement("span"),{className:"bias",textContent:t.candidates.biases[e.parameter].replace("{x}",o)}),this.status(e.status)),i}status(e){const t=Object.assign(document.createElement("span"),{className:"lead-status",textContent:this.host.messages().status[e]});return t.dataset.status=e,t}values(e){if(e.field==="time"){const i=this.host.start();if(!i)return["",""];const s=n=>n.toLocaleTimeString(document.documentElement.lang||void 0,{hour:"2-digit",minute:"2-digit"});return[s(i.date),s(new Date(i.date.getTime()+e.variant*6e4))]}if(e.field==="duration"){const i=s=>`${this.number(ee.rounded(s))} s`;return[i(e.stated),i(e.variant)]}const t=i=>`${this.number(ee.rounded(i))}°`;return[t(e.stated),t(e.variant)]}number(e){return e.toLocaleString(document.documentElement.lang||void 0,{maximumFractionDigits:2})}show(e){this.shown=e;const t=this.host.sceneCard();t.querySelector(".variant-badge")?.remove();for(const o of Object.values(this.host.fieldLabels()))o?.querySelector(".variant-value")?.remove();if(!e)return;const i=this.host.messages().candidates,s=document.createElement("div");s.className="variant-badge",s.setAttribute("role","status");const n=document.createElement("button");n.type="button",n.textContent=i.backToAccount,n.addEventListener("click",()=>this.show(void 0)),s.append(i.variantLabel.replace("{name}",e.label),n),t.append(s);const r=this.host.fieldLabels();for(const o of e.moved){const a=r[o.field];if(!a)continue;const[d,l]=this.values(o),h=document.createElement("span");h.className="variant-value",h.append(Object.assign(document.createElement("s"),{textContent:d})," → ",Object.assign(document.createElement("b"),{textContent:l})),a.append(h)}}get variant(){return this.shown}}class Ns{constructor(e,t){this.card=e,this.picture=t,this.layer=document.createElement("div"),this.layer.className="scene-field-overlay",this.layer.hidden=!0,this.layer.setAttribute("aria-hidden","true"),e.append(this.layer)}static CSS=`
181
+ `;static PLANETS=["Venus","Mars","Jupiter","Saturn"];static STARS=6;static STAR_MAG=1.5;static SATELLITES=4;static AIRCRAFT=12;static AIRCRAFT_RANGE_KM=80;static SPAN_M=35;static FT_M=.3048;statementT=0;poher;poherState="idle";poherVersion=ne.storedVersion();static VERSION_STORAGE="ufoathome.poherMatrixVersion";kindsLoading=new WeakSet;phenomenonOf=new Map;variants=[];shown;open=new Set;statement(){const e=this.host.sighting,t=e.timeline,i=t.sourceIds[0];if(!i)return;const s=t.allKeyframes.find(d=>d.shapes.some(l=>l.sourceId===i))?.t??0;this.statementT=s;const n=t.getInterpolatedShapeAt(s,i);if(!n?.aim)return;const r={aim:n.aim,widthDeg:n.angular?.widthDeg,timeHow:e.provenance.at("time")?.how},o=[...t.allKeyframes].reverse().find(d=>d.t>s&&t.getShapeAt(d.t,i)?.aim),a=o?t.getInterpolatedShapeAt(o.t,i):void 0;if(o&&a?.aim){r.motion={sweepDeg:z.separation(n.aim,a.aim),spanMinutes:(o.t-s)/6e4};const d=n.angular?.widthDeg,l=a.angular?.widthDeg;d&&l&&(r.growth=l/d)}return r}tracks(e){const t=this.host.start();if(!t)return[];const i=this.host.messages().candidates.bodies,s=o=>({id:o,label:i[o]??o,at:a=>{const d=new Date(t.date.getTime()+this.statementT+a*6e4),l=V(o,d,t.observer);if(l.altitudeDeg<0)return;const h=V("Sun",d,t.observer).altitudeDeg,c=o==="Moon"?-10:nn(o,d);if(!(c>this.host.limitAt(h)))return{aim:{azimuthDeg:l.azimuthDeg,altitudeDeg:l.altitudeDeg},widthDeg:o==="Moon"?te.MOON_DEG:.01,magnitude:c}},readings:["still-seen-moving"]});this.phenomenonOf.clear();const n=[s("Moon")];this.phenomenonOf.set("Moon","Moon");for(const o of ne.PLANETS)n.push(s(o)),this.phenomenonOf.set(o,"Planets");n.push(...this.starTracks(t,e));const r=this.host.satellites();if(r){const o=new Map,a=l=>(o.has(l.getTime())||o.set(l.getTime(),r.positionsAt(l)),o.get(l.getTime())),d=[...r.passes].sort((l,h)=>(l.peak.magnitude??99)-(h.peak.magnitude??99)).slice(0,ne.SATELLITES);for(const l of d){const h=`satellite-${l.object.norad}`;n.push({id:h,label:l.object.name,at:c=>{const u=a(new Date(t.date.getTime()+this.statementT+c*6e4))?.find(p=>p.object.norad===l.object.norad);if(!(!u||u.altitudeDeg<0||u.sunlitFraction<.5))return{aim:{azimuthDeg:u.azimuthDeg,altitudeDeg:u.altitudeDeg},widthDeg:.01,magnitude:u.magnitude}},readings:["brightening-as-approach"]}),this.phenomenonOf.set(h,"OrbitingSatellites")}}return n.push(...this.burningTracks(t),...this.aircraftTracks(t),...this.interpretationTracks()),n}starTracks(e,t){const i=this.host.messages().candidates,s=h=>new Date(e.date.getTime()+this.statementT+h*6e4),n=h=>V("Sun",h,e.observer).altitudeDeg,r=this.host.limitAt(n(s(0))),o=t.aim,a=Math.PI/180,d=h=>o?Math.acos(Math.min(1,Math.sin(o.altitudeDeg*a)*Math.sin(h.altitudeDeg*a)+Math.cos(o.altitudeDeg*a)*Math.cos(h.altitudeDeg*a)*Math.cos((h.azimuthDeg-o.azimuthDeg)*a)))/a:0;return sn.filter(h=>h.mag<=Math.min(r,ne.STAR_MAG)).map(h=>({star:h,position:Mi(h.raHours,h.decDeg,s(0),e.observer)})).filter(({position:h})=>h.altitudeDeg>0).sort((h,c)=>d(h.position)-d(c.position)||h.star.mag-c.star.mag).slice(0,ne.STARS).map(({star:h})=>{const c=`star-${h.name}`;return this.phenomenonOf.set(c,"Stars"),{id:c,label:i.star.replace("{name}",this.host.starName(h.name)),at:u=>{const p=s(u),m=Mi(h.raHours,h.decDeg,p,e.observer);if(!(m.altitudeDeg<0||h.mag>this.host.limitAt(n(p))))return{aim:{azimuthDeg:m.azimuthDeg,altitudeDeg:m.altitudeDeg},widthDeg:.01,magnitude:h.mag}},readings:["still-seen-moving"]}})}interpretationTracks(){const e=this.host.messages().candidates,t=this.host.sighting.timeline.sourceIds[0];return this.host.interpretations().flatMap(({id:i,label:s,interpretation:n})=>{const{interpretation:r,phenomenonOf:o,loaded:a}=this.host.computed(n);this.kindsLoading.has(n)||(this.kindsLoading.add(n),a.then(()=>{this.host.interpretations().some(h=>h.interpretation===n)&&this.refresh()}));const d=r.bodies.find(h=>t!==void 0&&h.explains?.includes(t))??r.bodies[0];if(!d)return[];const l=o.get(d.id);return l&&this.phenomenonOf.set(`interpretation-${i}`,l),[{id:`interpretation-${i}`,label:e.interpretation.replace("{name}",s),at:h=>{const c=this.host.projectionAt(d,this.statementT+h*6e4);return c?{aim:c.aim,widthDeg:c.angular.widthDeg}:void 0}}]})}burningTracks(e){const t=this.host.messages().candidates,{reentries:i,fireballs:s}=this.host.burning(),n={lat:e.observer.lat,lng:e.observer.lng,heightM:e.observer.elevationM},r=(o,a)=>{const d=`${a?"fireball":"reentry"}-${o.id}`;this.phenomenonOf.set(d,a?"Meteorits":"AtmosphericSatellitesReentry");const l=o.object?.name??o.id;return{id:d,label:(a?t.fireball:t.reentry).replace("{name}",l),at:h=>{const c=this.statementT+h*6e4,u=Kt.viewsAt([o],c,n).filter(g=>g.head.altitudeDeg>=0);if(u.length===0)return;const p=V("Sun",new Date(e.date.getTime()+c),e.observer).altitudeDeg,m=u.reduce((g,b)=>b.magnitude<g.magnitude?b:g);if(m.magnitude>this.host.limitAt(p))return;let f=0;for(const g of u)for(const b of u)f=Math.max(f,Math.hypot(g.head.azimuthDeg-b.head.azimuthDeg,g.head.altitudeDeg-b.head.altitudeDeg));return{aim:{azimuthDeg:m.head.azimuthDeg,altitudeDeg:m.head.altitudeDeg},widthDeg:Math.max(.01,f),magnitude:m.magnitude}},readings:["grouped","brightening-as-approach"]}};return[...i.map(o=>r(o,!1)),...s.map(o=>r(o,!0))]}aircraftTracks(e){const t=this.host.traffic();if(!t)return[];const i=this.host.messages().candidates,s={lat:e.observer.lat,lng:e.observer.lng,heightM:e.observer.elevationM},n=t.startMs+this.statementT,r=(a,d)=>{const l=a.points;if(l.length===0||d<l[0].t||d>l[l.length-1].t)return;let h=0;for(;h<l.length-2&&l[h+1].t<d;)h++;const c=l[h],u=l[Math.min(h+1,l.length-1)],p=u.t>c.t?(d-c.t)/(u.t-c.t):0;return{lat:c.lat+(u.lat-c.lat)*p,lng:c.lng+(u.lng-c.lng)*p,heightM:(c.altitudeFt+(u.altitudeFt-c.altitudeFt)*p)*ne.FT_M}};return t.tracks.map(a=>({track:a,point:r(a,n)})).filter(a=>a.point!==void 0).map(a=>({...a,seen:Kt.seenFrom(s,a.point)})).filter(a=>a.seen.distanceKm<=ne.AIRCRAFT_RANGE_KM).sort((a,d)=>a.seen.distanceKm-d.seen.distanceKm).slice(0,ne.AIRCRAFT).map(({track:a,point:d})=>{const l=t.describe(a),h=`aircraft-${a.icao}`;this.phenomenonOf.set(h,l?.category==="A7"?"Helicopters":d.heightM>15e3*ne.FT_M?"HighAltitudePlanes":"LowAltitudePlanes");const c=l?.restricted?a.icao.toString(16).toUpperCase():[l?.type,l?.registration].filter(Boolean).join(" ")||a.icao.toString(16).toUpperCase();return{id:h,label:i.aircraft.replace("{name}",c),at:u=>{const p=r(a,n+u*6e4);if(!p)return;const m=Kt.seenFrom(s,p);if(m.altitudeDeg<0||m.distanceKm>ne.AIRCRAFT_RANGE_KM)return;const f=Math.atan2(ne.SPAN_M,m.distanceKm*1e3)*180/Math.PI;return{aim:{azimuthDeg:m.azimuthDeg,altitudeDeg:m.altitudeDeg},widthDeg:f}},readings:["grouped","moving-seen-still","brightening-as-approach"]}})}ranking(){if(!this.poher)return;const e=new ki(this.host.model(),this.host.conditions()).of(this.host.facts()).filter(t=>this.poher.matrix.has(t.question));return{rows:this.poher.matrix.rank(e),answers:e}}languageChanged(){this.poherState!=="loading"&&(this.poherState="idle",this.poher=void 0)}loadPoher(){if(this.poherState!=="idle")return;this.poherState="loading";const e=this.poherVersion;this.host.poher(e).then(t=>{e===this.poherVersion&&(this.poher=t,this.poherState="ready",this.refresh())},()=>{e===this.poherVersion&&(this.poherState="failed",this.refresh())})}refresh(){const e=this.host.messages().candidates,t=this.statement(),i=this.host.start();this.variants=t&&i?new z(this.host.model(),this.host.conditions()).search(t,this.tracks(t)):[];const n=[Object.assign(document.createElement("h3"),{className:"section-title",textContent:e.title})];this.loadPoher();const r=this.ranking();if(n.push(this.versionChoice()),this.poherState==="loading"&&n.push(this.note(e.poherLoading)),this.poherState==="failed"&&n.push(this.note(e.poherFailed)),r&&n.push(this.answersBlock(r.answers)),!t)n.push(this.note(e.noDirection));else if(!i)n.push(this.note(e.noSky));else{const d=document.createElement("div");d.className="candidates",d.append(...this.variants.map(l=>this.row(l,r?.rows.find(h=>h.phenomenon===this.phenomenonOf.get(l.candidate))))),n.push(d,this.note(e.costNote))}const o=this.keptBlock();o&&n.push(o),r&&n.push(this.poherBlock(r.rows)),n.push(this.note(e.scopeNote)),this.section.replaceChildren(...n);const a=this.shown&&this.variants.find(d=>d.candidate===this.shown.candidate);this.show(a&&a.verdict!=="incompatible"?a:void 0)}keep(e){const t=this.phenomenonOf.get(e.candidate),i=e.candidate.startsWith("interpretation-")?this.host.interpretations().find(({id:r})=>`interpretation-${r}`===e.candidate)?.interpretation:void 0,s={title:this.host.messages().candidates.variantLabel.replace("{name}",e.label),bodies:i?structuredClone(i.bodies):[],variant:{candidate:e.candidate,label:e.label,...t?{phenomenon:t}:{},parameters:e.parameters,moved:e.moved.map(r=>({...r})),...e.readings.length>0?{readings:e.readings.map(r=>({...r}))}:{},cost:e.cost,verdict:e.verdict,modelId:e.modelId}},n=this.host.variants().findIndex(r=>r.variant?.candidate===e.candidate&&r.variant?.modelId===e.modelId);n>=0&&this.host.remove(n),this.host.keep(s),this.refresh()}keptBlock(){const e=this.host.variants();if(e.length===0)return;const t=this.host.messages(),i=document.createElement("div");return i.className="kept-variants",i.append(Object.assign(document.createElement("h4"),{textContent:t.candidates.keptTitle.replace("{n}",String(e.length))})),e.forEach((s,n)=>{const r=s.variant;if(!r)return;const o=document.createElement("div");o.className="kept-variant";const a=Object.assign(document.createElement("span"),{className:"verdict",textContent:t.candidates.verdicts[r.verdict]});a.dataset.verdict=r.verdict;const d=Object.assign(document.createElement("span"),{className:"cost",textContent:t.candidates.cost.replace("{x}",this.number(r.cost))}),l=Object.assign(document.createElement("span"),{className:"cost",textContent:t.candidates.keptModel.replace("{model}",t.models[r.modelId]??r.modelId)});o.append(Object.assign(document.createElement("strong"),{textContent:r.label??r.candidate}),a,d,l);const h=this.variants.find(p=>p.candidate===r.candidate);h&&(h.verdict!==r.verdict||Math.abs(h.cost-r.cost)>.05||h.modelId!==r.modelId)&&o.append(Object.assign(document.createElement("span"),{className:"recomputed",textContent:t.candidates.keptRecomputed.replace("{verdict}",t.candidates.verdicts[h.verdict]).replace("{x}",this.number(h.cost))}));const c=document.createElement("button");c.type="button",c.className="pill-btn",c.textContent=t.candidates.seeKept,c.addEventListener("click",()=>this.show({candidate:r.candidate,label:r.label??r.candidate,verdict:r.verdict,cost:r.cost,parameters:r.parameters,moved:r.moved,readings:r.readings??[],modelId:r.modelId}));const u=document.createElement("button");u.type="button",u.className="pill-btn",u.textContent=t.candidates.removeVariant,u.addEventListener("click",()=>{this.host.remove(n),this.refresh()}),o.append(c,u),i.append(o)}),i}static storedVersion(){try{const e=localStorage.getItem(ne.VERSION_STORAGE);if(e&&e in Ue.VERSIONS)return e}catch{}return Ue.DEFAULT_VERSION}versionChoice(){const e=this.host.messages().candidates,t=Object.assign(document.createElement("label"),{className:"poher-version",textContent:e.poherVersion}),i=document.createElement("select");i.style.setProperty("field-sizing","content"),i.style.width="auto",i.style.maxWidth="100%";for(const s of Object.keys(Ue.VERSIONS))i.append(Object.assign(document.createElement("option"),{value:s,textContent:e.poherVersions[s],selected:s===this.poherVersion}));return i.addEventListener("change",()=>{this.poherVersion=i.value;try{localStorage.setItem(ne.VERSION_STORAGE,this.poherVersion)}catch{}this.poherState="idle",this.poher=void 0,this.refresh()}),t.append(i),t}exclusion(e){const t=this.host.messages().candidates;return t.poherExcludedBy.replace("{list}",e.excludedBy.map(i=>{const s=this.poher?.matrix.reason(e.phenomenon,i);return s?`${this.answerLabel(i)} (${t.poherRr0Reason.replace("{why}",s.why)})`:this.answerLabel(i)}).join(", "))}answerLabel(e){const t=this.poher?.labels??{},i=e.slice(0,e.indexOf("."));return`${t[i]??i} : ${t[e]??e.slice(e.indexOf(".")+1)}`}answersBlock(e){const t=this.host.messages().candidates,i=document.createElement("details");i.className="poher-answers",i.append(Object.assign(document.createElement("summary"),{textContent:t.answersTitle.replace("{n}",String(e.length))}));const s=document.createElement("ul");for(const n of e){const r=document.createElement("li");r.append(this.answerLabel(n.question)," ",Object.assign(document.createElement("span"),{className:"firmness",textContent:n.firm?t.firm:t.soft})),r.dataset.firm=String(n.firm),s.append(r)}return i.append(s),i}poherBlock(e){const t=this.host.messages().candidates,i=this.poher?.labels??{},s=new Set(this.phenomenonOf.values()),n=e.filter(h=>!s.has(h.phenomenon)),r=document.createElement("div");r.className="poher-block",r.append(Object.assign(document.createElement("h4"),{textContent:t.poherTitle.replace("{version}",t.poherVersions[this.poherVersion])}),Object.assign(document.createElement("p"),{className:"candidates-note",textContent:this.poher?.matrix.reasons?t.poherIntroRr0:t.poherIntro}));const o=h=>{const c=document.createElement("li");if(c.append(Object.assign(document.createElement("strong"),{textContent:i[h.phenomenon]??h.phenomenon})),h.added&&c.append(" ",Object.assign(document.createElement("span"),{className:"poher-tag",textContent:t.poherAdded})),h.excludedBy.length>0)c.append(" — ",this.exclusion(h));else{const u=document.createElement("span");u.className="poher-bar",u.style.setProperty("--score",String(h.mean)),c.append(" ",u," ",t.poherScore.replace("{x}",this.number(te.rounded(h.mean)))),h.doubtedBy.length>0&&c.append(Object.assign(document.createElement("span"),{className:"doubt",textContent:` · ${t.poherDoubted.replace("{list}",h.doubtedBy.map(p=>this.answerLabel(p)).join(", "))}`}))}return c},a=n.filter(h=>h.excludedBy.length===0),d=n.filter(h=>h.excludedBy.length>0),l=document.createElement("ul");if(l.className="poher-list",l.append(...a.map(o)),r.append(Object.assign(document.createElement("h5"),{textContent:t.poherPossible}),l),d.length>0){const h=document.createElement("details");h.append(Object.assign(document.createElement("summary"),{textContent:t.poherExcluded.replace("{n}",String(d.length))}));const c=document.createElement("ul");c.className="poher-list",c.append(...d.map(o)),h.append(c),r.append(h)}return r}note(e){return Object.assign(document.createElement("p"),{className:"candidates-note",textContent:e})}row(e,t){const i=this.host.messages().candidates,s=document.createElement("div");s.className="candidate";const n=document.createElement("button");n.type="button",n.className="candidate-head",n.setAttribute("aria-expanded",String(this.open.has(e.candidate)));const r=Object.assign(document.createElement("span"),{className:"verdict",textContent:i.verdicts[e.verdict]});r.dataset.verdict=e.verdict;const o=Object.assign(document.createElement("span"),{className:"cost",textContent:Number.isFinite(e.cost)?i.cost.replace("{x}",this.number(e.cost)):""}),a=Object.assign(document.createElement("span"),{textContent:e.label});if(t){const l=Object.assign(document.createElement("span"),{className:"poher-tag",textContent:i.poherTag.replace("{state}",t.excludedBy.length>0?i.poherStateExcluded:i.poherStatePossible.replace("{x}",this.number(te.rounded(t.mean))))});l.dataset.excluded=String(t.excludedBy.length>0),a.append(" ",l)}n.append(a,r,o);const d=document.createElement("div");d.className="candidate-body",d.hidden=!this.open.has(e.candidate),s.toggleAttribute("open",!d.hidden),n.addEventListener("click",()=>{this.open.has(e.candidate)?this.open.delete(e.candidate):this.open.add(e.candidate),d.hidden=!d.hidden,s.toggleAttribute("open",!d.hidden),n.setAttribute("aria-expanded",String(!d.hidden))}),t&&t.excludedBy.length>0&&d.append(Object.assign(document.createElement("p"),{className:"candidate-reason",textContent:`${i.poherTag.replace("{state}",i.poherStateExcluded)} — ${this.exclusion(t)}`})),e.verdict==="incompatible"&&d.append(Object.assign(document.createElement("p"),{className:"candidate-reason",textContent:`${i.reasons[e.reason??"direction"]} ${i.notAgainst}`}));for(const l of e.moved)d.append(this.movedRow(l));for(const l of e.readings)d.append(this.readingRow(l));if(e.verdict!=="incompatible"){const l=document.createElement("button");l.type="button",l.className="pill-btn",l.textContent=i.seeVariant,l.addEventListener("click",()=>this.show(e));const h=document.createElement("button");h.type="button",h.className="pill-btn",h.textContent=i.keepVariant,h.addEventListener("click",()=>this.keep(e));const c=document.createElement("div");c.className="candidate-actions",c.append(l,h),d.append(c)}return s.append(n,d),s}readingRow(e){const t=this.host.messages().candidates,i=document.createElement("div");return i.className="moved-row reading-row",i.append(Object.assign(document.createElement("span"),{textContent:t.readingTitle}),Object.assign(document.createElement("span"),{className:"bias",textContent:t.readings[e.reading]}),this.status(e.status)),i}movedRow(e){const t=this.host.messages(),i=document.createElement("div");i.className="moved-row";const[s,n]=this.values(e),r=document.createElement("span");r.append(Object.assign(document.createElement("s"),{textContent:s})," → ",Object.assign(document.createElement("b"),{textContent:n}));const o=e.parameter==="clock"||e.parameter==="heading"||e.parameter==="sweep"?`${e.amount>0?"+":""}${this.number(te.rounded(e.amount))}`:this.number(te.rounded(e.amount));return i.append(Object.assign(document.createElement("span"),{textContent:t.candidates.fields[e.field]}),r,Object.assign(document.createElement("span"),{className:"bias",textContent:t.candidates.biases[e.parameter].replace("{x}",o)}),this.status(e.status)),i}status(e){const t=Object.assign(document.createElement("span"),{className:"lead-status",textContent:this.host.messages().status[e]});return t.dataset.status=e,t}values(e){if(e.field==="time"){const i=this.host.start();if(!i)return["",""];const s=n=>n.toLocaleTimeString(document.documentElement.lang||void 0,{hour:"2-digit",minute:"2-digit"});return[s(i.date),s(new Date(i.date.getTime()+e.variant*6e4))]}if(e.field==="duration"){const i=s=>`${this.number(te.rounded(s))} s`;return[i(e.stated),i(e.variant)]}const t=i=>`${this.number(te.rounded(i))}°`;return[t(e.stated),t(e.variant)]}number(e){return e.toLocaleString(document.documentElement.lang||void 0,{maximumFractionDigits:2})}show(e){this.shown=e;const t=this.host.sceneCard();t.querySelector(".variant-badge")?.remove();for(const o of Object.values(this.host.fieldLabels()))o?.querySelector(".variant-value")?.remove();if(!e)return;const i=this.host.messages().candidates,s=document.createElement("div");s.className="variant-badge",s.setAttribute("role","status");const n=document.createElement("button");n.type="button",n.textContent=i.backToAccount,n.addEventListener("click",()=>this.show(void 0)),s.append(i.variantLabel.replace("{name}",e.label),n),t.append(s);const r=this.host.fieldLabels();for(const o of e.moved){const a=r[o.field];if(!a)continue;const[d,l]=this.values(o),h=document.createElement("span");h.className="variant-value",h.append(Object.assign(document.createElement("s"),{textContent:d})," → ",Object.assign(document.createElement("b"),{textContent:l})),a.append(h)}}get variant(){return this.shown}}class Ns{constructor(e,t){this.card=e,this.picture=t,this.layer=document.createElement("div"),this.layer.className="scene-field-overlay",this.layer.hidden=!0,this.layer.setAttribute("aria-hidden","true"),e.append(this.layer)}static CSS=`
182
182
  .scene-field-overlay { position: absolute; z-index: 3; pointer-events: none; }
183
183
  .scene-field-overlay[hidden] { display: none; }
184
184
  .scene-field-overlay > * { position: absolute; }
@@ -204,7 +204,7 @@ ${C.titles("::before","[data-chosen]")} { display: none; }
204
204
  /* Standing on the horizon, never across its line. */
205
205
  .sfo-compass { transform: translate(-50%, calc(-100% - 5px)); padding: 1px 7px; color: #fff; }
206
206
  .sfo-wind svg { transition: transform .15s ease; }
207
- `;layer;hide(){this.layer.hidden=!0,this.layer.replaceChildren()}horizon(e,t){const i=this.element("sfo-horizon");i.style.top=`${e*100}%`,i.append(this.pill(t)),this.show(i)}frame(e){const t=this.element("sfo-frame");t.append(this.pill(e)),this.show(t)}measure(e,t,i,s){const n=this.element("sfo-measure");n.style.left=`${e*100}%`,n.style.top=`${t*100}%`,n.style.width=`${Math.max(i,.02)*100}%`,s&&n.append(this.pill(s)),this.show(n)}orientation(e,t){const i=[];if(t){const s=this.element("sfo-curve"),n=t.line.filter(o=>o.length>1).map(o=>o.map((a,d)=>`${d===0?"M":"L"}${(a.x*100).toFixed(2)} ${(a.y*100).toFixed(2)}`).join(" ")).join(" ");s.innerHTML=`<svg viewBox="0 0 100 100" preserveAspectRatio="none"><path d="${n}"/></svg>`,i.push(s);const r=t.line.flat().filter(o=>o.x>=0&&o.x<=1&&o.y>=0&&o.y<=1).sort((o,a)=>o.x-a.x)[0];if(r){const o=this.pill(t.label);o.classList.add("sfo-horizon-label"),o.style.top=`${r.y*100}%`,i.push(o)}}if(e){for(const n of e.compass){const r=this.pill(n.label);r.classList.add("sfo-compass"),r.style.left=`${n.x*100}%`,r.style.top=`${n.y*100}%`,i.push(r)}const s=this.pill(e.label);s.classList.add("sfo-heading"),i.push(s)}i.length===0?this.hide():this.show(...i)}wind(e,t){const i=this.pill(t);i.classList.add("sfo-wind"),i.insertAdjacentHTML("afterbegin",`<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="transform: rotate(${e}deg)"><path d="M8 13.5V2.5"/><path d="M4 6.5 8 2.5l4 4"/></svg>`),this.show(i)}show(...e){const t=this.card.getBoundingClientRect(),i=this.picture().getBoundingClientRect();Object.assign(this.layer.style,{left:`${i.left-t.left}px`,top:`${i.top-t.top}px`,width:`${i.width}px`,height:`${i.height}px`}),this.layer.replaceChildren(...e),this.layer.hidden=!1}element(e){const t=document.createElement("div");return t.className=e,t}pill(e){const t=this.element("sfo-pill");return t.textContent=e,t}}const er=[{key:"cars",max:999},{key:"trucks",max:999},{key:"people",max:9999},{key:"talking",max:9999},{key:"withinM",max:9999,unit:"m"}],tr=[{key:"distanceM",max:99999,unit:"m"},{key:"vehiclesPerMinute",max:999,unit:"perMinute",step:"0.1"},{key:"trucksPerMinute",max:999,unit:"perMinute",step:"0.1"},{key:"speedKmh",max:200,unit:"km/h"}];class ir{constructor(e,t){this.root=e,this.host=t}messages;basisMessages;localize(e,t){this.messages=e,this.basisMessages=t,this.render()}render(){const e=this.messages;if(!e)return;const t=this.root.querySelector(".section-title");t&&t.replaceChildren(document.createTextNode(e.title)," ",Ae.of(e.hint));const i=this.root.querySelector(".around-body")??this.root,s=this.host.sighting().around??{},n=document.createElement("div");n.className="around-counted",n.append(this.heading(e.counted));for(const l of er){const h=e[l.key==="withinM"?"within":l.key];n.append(this.field(h,`around.${l.key}`,s[l.key],l.max,"1",l.unit??"",c=>this.edit(u=>{c===void 0?delete u[l.key]:u[l.key]=c}),l.key==="withinM"?String(Vt.DEFAULT_WITHIN_M):void 0))}const r=document.createElement("div");r.className="around-roads",r.append(this.heading(e.roads)),(s.roads??[]).forEach((l,h)=>r.append(this.road(l,h,e)));const o=document.createElement("button");o.type="button",o.className="around-add-road",o.textContent=e.addRoad,o.addEventListener("click",()=>this.edit(l=>{l.roads=[...l.roads??[],{distanceM:50,vehiclesPerMinute:5}]},!0)),r.append(o);const a=document.createElement("output");a.className="place-status around-heard";const d=Li.dbA(this.host.sighting().around);a.textContent=Number.isFinite(d)?e.heard.replace("{level}",d.toFixed(0)):e.quiet,i.replaceChildren(n,r,a),Bt.fit(i)}road(e,t,i){const s=document.createElement("div");s.className="around-road";for(const r of tr){const o=r.key==="distanceM"?i.roadDistance:r.key==="speedKmh"?i.speed:i[r.key],a=r.unit==="perMinute"?i.perMinute:r.unit,d=r.key==="distanceM"||r.key==="vehiclesPerMinute";s.append(this.field(o,`around.roads.${t}.${r.key}`,e[r.key],r.max,r.step??"1",a,l=>this.edit(h=>{const c=[...h.roads??[]],u={...c[t]};if(l===void 0){if(d)return;delete u[r.key]}else u[r.key]=l;c[t]=u,h.roads=c}),r.key==="speedKmh"?String(Vt.DEFAULT_SPEED_KMH):void 0))}const n=document.createElement("button");return n.type="button",n.className="around-remove-road",n.title=i.removeRoad,n.setAttribute("aria-label",i.removeRoad),n.textContent="×",n.addEventListener("click",()=>this.edit(r=>{r.roads=(r.roads??[]).filter((d,l)=>l!==t);const o=this.host.sighting().provenance,a=[];for(const d of o.paths()){const l=/^around\.roads\.(\d+)\.(.+)$/.exec(d);if(!l)continue;const h=Number(l[1]),c=o.at(d);o.clear(d),h>t&&c&&a.push([`around.roads.${h-1}.${l[2]}`,c])}for(const[d,l]of a)o.set(d,l)},!0)),s.append(n),s}heading(e){const t=document.createElement("h4");return t.className="around-heading",t.textContent=e,t}field(e,t,i,s,n,r,o,a){const d=document.createElement("label"),l=document.createElement("span");l.textContent=e;const h=document.createElement("input");h.type="number",h.min="0",h.max=String(s),h.step=n,h.dataset.path=t,a&&(h.placeholder=a),h.value=i===void 0?"":String(i);const c=this.basis(t);return c.hidden=i===void 0,h.addEventListener("input",()=>{const u=Number(h.value),p=h.value===""||!Number.isFinite(u)?void 0:u;c.hidden=p===void 0,o(p)}),d.append(l," ",c,h),r&&d.append(` ${r}`),d}basis(e){wi();const t=document.createElement(et.TAG);t.anchorKey=e,this.basisMessages&&(t.messages=this.basisMessages);const i=this.host.valueSources?.();return t.sourceMessages=i?.messages,t.choices=i?.choices??{},t.entry=this.host.sighting().provenance.at(e),t.addEventListener("basischange",s=>{const n=s.detail.entry;this.host.editing(),n?this.host.sighting().provenance.set(e,n):this.host.sighting().provenance.clear(e),this.host.changed()}),t}edit(e,t=!1){const i=this.host.sighting();this.host.editing();const s={...i.around??{}};e(s),i.around=Vt.read(s),this.host.changed(),t?this.render():this.refreshHeard()}refreshHeard(){const e=this.root.querySelector(".around-heard"),t=this.messages;if(!e||!t)return;const i=Li.dbA(this.host.sighting().around);e.textContent=Number.isFinite(i)?t.heard.replace("{level}",i.toFixed(0)):t.quiet}}class xe{constructor(e,t,i,s="observer"){this.root=e,this.host=t,this.actor=s,this.words=i;const n=e.querySelector(".events-body");this.note=document.createElement("p"),this.note.className="events-note",this.reset=document.createElement("button"),this.reset.type="button",this.reset.className="events-reset",this.reset.addEventListener("click",()=>{this.host.editing(),ue.reset(this.host.sighting()),this.host.changed()});const r=document.createElement("div");r.className="events-row",this.fields=document.createElement("div"),this.fields.className="events-fields",n.replaceChildren(this.note,this.reset,r,this.fields);const o=document.createElement("div");o.className="events-timeline",this.empty=document.createElement("p"),this.empty.className="events-empty",this.addButton=document.createElement("button"),this.addButton.type="button",this.addButton.id=`${s}-event-add`,this.addButton.className="events-add",r.append(o,this.empty,this.addButton),this.addMenu=new pi(this.addButton,`${s}-event-kinds`,a=>this.add(a),a=>`${s}-event-kind-${a}`),this.timelineHost=o,this.timeline=new yi(o,a=>this.host.seek(a),{addKeyframeHere:i?.add??"",keyframeHere:i?.add??"",zoomHint:i?.zoomHint??""}),this.deleteButton=document.createElement("button"),this.deleteButton.type="button",this.deleteButton.id=`${s}-event-delete`,this.deleteButton.className="icon-btn events-delete",this.deleteButton.innerHTML=M.TRASH,this.deleteButton.addEventListener("click",()=>this.remove()),i&&this.localizeList()}static CSS=`${et.CSS}${Ae.CSS}
207
+ `;layer;hide(){this.layer.hidden=!0,this.layer.replaceChildren()}horizon(e,t){const i=this.element("sfo-horizon");i.style.top=`${e*100}%`,i.append(this.pill(t)),this.show(i)}frame(e){const t=this.element("sfo-frame");t.append(this.pill(e)),this.show(t)}measure(e,t,i,s){const n=this.element("sfo-measure");n.style.left=`${e*100}%`,n.style.top=`${t*100}%`,n.style.width=`${Math.max(i,.02)*100}%`,s&&n.append(this.pill(s)),this.show(n)}orientation(e,t){const i=[];if(t){const s=this.element("sfo-curve"),n=t.line.filter(o=>o.length>1).map(o=>o.map((a,d)=>`${d===0?"M":"L"}${(a.x*100).toFixed(2)} ${(a.y*100).toFixed(2)}`).join(" ")).join(" ");s.innerHTML=`<svg viewBox="0 0 100 100" preserveAspectRatio="none"><path d="${n}"/></svg>`,i.push(s);const r=t.line.flat().filter(o=>o.x>=0&&o.x<=1&&o.y>=0&&o.y<=1).sort((o,a)=>o.x-a.x)[0];if(r){const o=this.pill(t.label);o.classList.add("sfo-horizon-label"),o.style.top=`${r.y*100}%`,i.push(o)}}if(e){for(const n of e.compass){const r=this.pill(n.label);r.classList.add("sfo-compass"),r.style.left=`${n.x*100}%`,r.style.top=`${n.y*100}%`,i.push(r)}const s=this.pill(e.label);s.classList.add("sfo-heading"),i.push(s)}i.length===0?this.hide():this.show(...i)}wind(e,t){const i=this.pill(t);i.classList.add("sfo-wind"),i.insertAdjacentHTML("afterbegin",`<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="transform: rotate(${e}deg)"><path d="M8 13.5V2.5"/><path d="M4 6.5 8 2.5l4 4"/></svg>`),this.show(i)}show(...e){const t=this.card.getBoundingClientRect(),i=this.picture().getBoundingClientRect();Object.assign(this.layer.style,{left:`${i.left-t.left}px`,top:`${i.top-t.top}px`,width:`${i.width}px`,height:`${i.height}px`}),this.layer.replaceChildren(...e),this.layer.hidden=!1}element(e){const t=document.createElement("div");return t.className=e,t}pill(e){const t=this.element("sfo-pill");return t.textContent=e,t}}const er=[{key:"cars",max:999},{key:"trucks",max:999},{key:"people",max:9999},{key:"talking",max:9999},{key:"withinM",max:9999,unit:"m"}],tr=[{key:"distanceM",max:99999,unit:"m"},{key:"vehiclesPerMinute",max:999,unit:"perMinute",step:"0.1"},{key:"trucksPerMinute",max:999,unit:"perMinute",step:"0.1"},{key:"speedKmh",max:200,unit:"km/h"}];class ir{constructor(e,t){this.root=e,this.host=t}messages;basisMessages;localize(e,t){this.messages=e,this.basisMessages=t,this.render()}render(){const e=this.messages;if(!e)return;const t=this.root.querySelector(".section-title");t&&t.replaceChildren(document.createTextNode(e.title)," ",Ae.of(e.hint));const i=this.root.querySelector(".around-body")??this.root,s=this.host.sighting().around??{},n=document.createElement("div");n.className="around-counted",n.append(this.heading(e.counted));for(const l of er){const h=e[l.key==="withinM"?"within":l.key];n.append(this.field(h,`around.${l.key}`,s[l.key],l.max,"1",l.unit??"",c=>this.edit(u=>{c===void 0?delete u[l.key]:u[l.key]=c}),l.key==="withinM"?String(Vt.DEFAULT_WITHIN_M):void 0))}const r=document.createElement("div");r.className="around-roads",r.append(this.heading(e.roads)),(s.roads??[]).forEach((l,h)=>r.append(this.road(l,h,e)));const o=document.createElement("button");o.type="button",o.className="around-add-road",o.textContent=e.addRoad,o.addEventListener("click",()=>this.edit(l=>{l.roads=[...l.roads??[],{distanceM:50,vehiclesPerMinute:5}]},!0)),r.append(o);const a=document.createElement("output");a.className="place-status around-heard";const d=Li.dbA(this.host.sighting().around);a.textContent=Number.isFinite(d)?e.heard.replace("{level}",d.toFixed(0)):e.quiet,i.replaceChildren(n,r,a),Bt.fit(i)}road(e,t,i){const s=document.createElement("div");s.className="around-road";for(const r of tr){const o=r.key==="distanceM"?i.roadDistance:r.key==="speedKmh"?i.speed:i[r.key],a=r.unit==="perMinute"?i.perMinute:r.unit,d=r.key==="distanceM"||r.key==="vehiclesPerMinute";s.append(this.field(o,`around.roads.${t}.${r.key}`,e[r.key],r.max,r.step??"1",a,l=>this.edit(h=>{const c=[...h.roads??[]],u={...c[t]};if(l===void 0){if(d)return;delete u[r.key]}else u[r.key]=l;c[t]=u,h.roads=c}),r.key==="speedKmh"?String(Vt.DEFAULT_SPEED_KMH):void 0))}const n=document.createElement("button");return n.type="button",n.className="around-remove-road",n.title=i.removeRoad,n.setAttribute("aria-label",i.removeRoad),n.textContent="×",n.addEventListener("click",()=>this.edit(r=>{r.roads=(r.roads??[]).filter((d,l)=>l!==t);const o=this.host.sighting().provenance,a=[];for(const d of o.paths()){const l=/^around\.roads\.(\d+)\.(.+)$/.exec(d);if(!l)continue;const h=Number(l[1]),c=o.at(d);o.clear(d),h>t&&c&&a.push([`around.roads.${h-1}.${l[2]}`,c])}for(const[d,l]of a)o.set(d,l)},!0)),s.append(n),s}heading(e){const t=document.createElement("h4");return t.className="around-heading",t.textContent=e,t}field(e,t,i,s,n,r,o,a){const d=document.createElement("label"),l=document.createElement("span");l.textContent=e;const h=document.createElement("input");h.type="number",h.min="0",h.max=String(s),h.step=n,h.dataset.path=t,a&&(h.placeholder=a),h.value=i===void 0?"":String(i);const c=this.basis(t);return c.hidden=i===void 0,h.addEventListener("input",()=>{const u=Number(h.value),p=h.value===""||!Number.isFinite(u)?void 0:u;c.hidden=p===void 0,o(p)}),d.append(l," ",c,h),r&&d.append(` ${r}`),d}basis(e){wi();const t=document.createElement(et.TAG);t.anchorKey=e,this.basisMessages&&(t.messages=this.basisMessages);const i=this.host.valueSources?.();return t.sourceMessages=i?.messages,t.choices=i?.choices??{},t.entry=this.host.sighting().provenance.at(e),t.addEventListener("basischange",s=>{const n=s.detail.entry;this.host.editing(),n?this.host.sighting().provenance.set(e,n):this.host.sighting().provenance.clear(e),this.host.changed()}),t}edit(e,t=!1){const i=this.host.sighting();this.host.editing();const s={...i.around??{}};e(s),i.around=Vt.read(s),this.host.changed(),t?this.render():this.refreshHeard()}refreshHeard(){const e=this.root.querySelector(".around-heard"),t=this.messages;if(!e||!t)return;const i=Li.dbA(this.host.sighting().around);e.textContent=Number.isFinite(i)?t.heard.replace("{level}",i.toFixed(0)):t.quiet}}class xe{constructor(e,t,i,s="observer"){this.root=e,this.host=t,this.actor=s,this.words=i;const n=e.querySelector(".events-body");this.note=document.createElement("p"),this.note.className="events-note",this.reset=document.createElement("button"),this.reset.type="button",this.reset.className="events-reset",this.reset.addEventListener("click",()=>{this.host.editing(),ue.reset(this.host.sighting()),this.host.changed()});const r=document.createElement("div");r.className="events-row",this.fields=document.createElement("div"),this.fields.className="events-fields",n.replaceChildren(this.note,this.reset,r,this.fields);const o=document.createElement("div");o.className="events-timeline",this.empty=document.createElement("p"),this.empty.className="events-empty",this.addButton=document.createElement("button"),this.addButton.type="button",this.addButton.id=`${s}-event-add`,this.addButton.className="events-add",r.append(o,this.empty,this.addButton),this.addMenu=new pi(this.addButton,`${s}-event-kinds`,a=>this.add(a),a=>`${s}-event-kind-${a}`),this.timelineHost=o,this.timeline=new yi(o,a=>this.host.seek(a),{addKeyframeHere:i?.add??"",keyframeHere:i?.add??"",zoomHint:i?.zoomHint??""}),this.deleteButton=document.createElement("button"),this.deleteButton.type="button",this.deleteButton.id=`${s}-event-delete`,this.deleteButton.className="icon-btn events-delete",this.deleteButton.innerHTML=L.TRASH,this.deleteButton.addEventListener("click",()=>this.remove()),i&&this.localizeList()}static CSS=`${et.CSS}${Ae.CSS}
208
208
  .events-section[hidden] { display: none; }
209
209
  .events-note { grid-column: 1 / -1; margin: 0; font-size: 13px; color: var(--ink-dim); }
210
210
  .events-row, .events-fields { grid-column: 1 / -1; min-width: 0; }
@@ -229,7 +229,7 @@ ${C.titles("::before","[data-chosen]")} { display: none; }
229
229
  .event-row-step { font-size: 13px; white-space: nowrap; }
230
230
  .event-direction-point { font-size: 13px; color: var(--ink-dim); }
231
231
  .event-direction-look { font-size: 13px; }
232
- `;static ADDABLE={observer:["look","walk","follow"],phenomenon:["stand","blink","turn","roll","vibrate","spiral","vanish"],bodies:["motion","spin","rise","turn","ride","light","blink","vanish"]};static CHOICES={sizeBy:{values:["","altitude"],absent:"",with:["sizeDeg"]},side:{values:["left","right"],with:[]},seenFrom:{values:["","craft"],absent:"",with:["side","byDeg"]}};static AMONG={target:["shape","group","body","decor"],in:["body","decor"],vehicle:["decor"]};words;get messages(){return this.words}note;reset;fields;timeline;timelineHost;empty;addButton;addMenu;deleteButton;picked;localize(e){this.words=e,this.localizeList(),this.render()}localizeList(){const e=this.messages;this.timeline.setMessages({addKeyframeHere:e.add,keyframeHere:e.add,zoomHint:e.zoomHint}),this.addButton.innerHTML=`${M.PLUS} ${e.add}`,this.addMenu.setKinds(xe.ADDABLE[this.actor].map(t=>({value:t,label:e.kinds[t]??t}))),this.empty.textContent=e.none,this.deleteButton.title=e.remove,this.deleteButton.setAttribute("aria-label",e.remove)}choose(e){this.picked=e;const t=this.host.sighting().events?.[e];t&&this.host.seek(t.t),this.render(),this.host.picked?.()}syncTimeline(e){const t=this.messages,i=l=>t.kinds[l.eventType]??l.eventType,s=e.map(({event:l,index:h})=>({id:String(h),t:l.t,until:Math.max(l.t,l.until??l.t),label:i(l)})),n=s.flatMap(l=>[l.t,l.until]),r=this.host.duration?.()??Math.max(1,...n),o=Math.min(...n),a=Math.max(...n),d=Math.max(500,(a-o)/10);this.timeline.show([{id:this.actor,label:this.titleText(),color:xe.COLOR,times:[],spans:s,selected:this.picked===void 0?void 0:String(this.picked),select:l=>this.choose(Number(l)),open:()=>{},add:()=>this.addButton.click()}],r,this.host.now(),{from:o-d,to:a+d})}setTime(e){this.timeline.setTime(e)}static COLOR="#4f8fd6";shownTheirs;sync(){this.theirs()!==this.shownTheirs&&this.render()}theirs(){const e=this.host.sighting();return this.actor==="observer"?ue.observerTrackIsExpanded(e):this.actor==="phenomenon"?ue.timelineIsExpanded(e):ue.bodiesAreExpanded(e)}who(){const e=this.host.sighting();if(this.actor==="observer")return q.observerId(e);if(this.actor==="bodies")return this.host.currentBody?.();const t=this.host.currentShapes?.();if(t!==void 0)return t;const i=(e.events??[]).find(n=>n.eventType==="stand"&&q.isPhenomenon(e,n));if(i?.who!==void 0)return i.who;const s=q.shapeIds(e);return s.length>0?e.timeline.topOf(s[0]):void 0}events(){const e=this.host.sighting(),t=this.actor==="bodies"?this.host.currentBody?.():void 0,i=s=>this.actor==="observer"?q.isObserver(e,s):this.actor==="phenomenon"?q.isPhenomenon(e,s):t!==void 0&&(s.who===t||q.partOf(s.who)?.element===t);return(e.events??[]).map((s,n)=>({event:s,index:n})).filter(({event:s})=>i(s))}get pickedIndex(){return this.picked}pick(e){this.picked=e,this.render(),this.root.scrollIntoView?.({block:"start"})}titleText(){return this.actor==="observer"?this.messages.title:this.actor==="phenomenon"?this.messages.phenomenonTitle:this.messages.bodyTitle.replace("{body}",this.host.bodyLabel?.(this.who()??"")??this.who()??"")}render(){if(!this.words)return;this.shownTheirs=this.theirs(),this.root.querySelector(".events-title").textContent=this.titleText(),this.root.hidden=this.actor==="bodies"&&this.who()===void 0;const e=this.events();e.some(({index:n})=>n===this.picked)||(this.picked=e[0]?.index);const t=this.shownTheirs;this.note.hidden=e.length===0,this.note.textContent=this.actor==="observer"?t?this.messages.derivedNote:this.messages.overriddenNote:this.actor==="phenomenon"?t?this.messages.derivedShapesNote:this.messages.overriddenShapesNote:t?this.messages.derivedBodiesNote:this.messages.overriddenBodiesNote,this.reset.hidden=e.length===0||t,this.reset.textContent=this.messages.resetToEvents,this.empty.hidden=e.length>0,this.timelineHost.hidden=e.length===0,this.syncTimeline(e);const i=this.picked===void 0?void 0:this.host.sighting().events?.[this.picked],s=i?this.details(i,this.picked):[];s[0]?.append(this.deleteButton),this.fields.replaceChildren(...s)}add(e){const t=this.host.sighting(),i=this.who();if(i===void 0)return;const s=Math.round(this.host.now()),n=t.observerTrack.getInterpolatedPoseAt(s)??t.observerTrack.getLatestPoseAt(s),r=n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:t.event.place?.[0]&&{lat:t.event.place[0].lat,lng:t.event.place[0].lng},o=t.interpretation?.bodies.find(h=>h.id!==i)?.id??"",a={look:{params:{headingDeg:Math.round(n?.headingDeg??0),pitchDeg:Math.round(n?.pitchDeg??0)}},walk:{until:s+1e4,params:{from:{...r},to:{...r}}},follow:{until:s+5e3,params:{target:o}},stand:{params:{place:{...r},metres:[{t:s,widthM:1,heightM:1}]}},blink:{until:s+5e3,params:{onS:.5,offS:.5,off:{transparency:1}}},vanish:{},motion:{until:s+2e3,params:{motion:"",to:1}},spin:{until:s+5e3,params:{motion:"",turnsPerS:.5}},rise:{until:s+3e3,params:{distanceM:1,angleDeg:0,headingDeg:0,stops:!0}},ride:{params:{in:o,aboveM:0}},turn:{until:s+1e3,params:{headingDeg:0}}};this.actor==="phenomenon"&&Object.assign(a,{turn:{until:s+1e3,params:{byDeg:15,side:"left"}},roll:{until:s+500,params:{toDeg:20}},vibrate:{until:s+1e3,params:{hz:10,amplitudeShare:.1,riseS:.3}},spiral:{until:s+1e3,params:{turns:1,radiusDeg:2,shrink:.5,clockwise:!0,rollDeg:360}}}),this.actor==="bodies"&&Object.assign(a,{blink:{until:s+5e3,params:{onS:.5,offS:.5,cdM2:500}},light:{params:{cdM2:500}}});const d=a[e]??{},l={type:"event",eventType:e,who:i,t:s,...d.until===void 0?{}:{until:d.until},...d.params?{params:d.params}:{}};this.host.editing(),t.events=[...t.events??[],l],this.picked=t.events.length-1,ue.refresh(t),this.host.changed()}remove(){const e=this.host.sighting(),t=this.picked;if(t===void 0||!e.events?.[t])return;this.host.editing();const i=e.provenance,s=[];for(const n of i.paths()){const r=/^events\.(\d+)(\..*)?$/.exec(n);if(!r)continue;const o=Number(r[1]);o>t&&s.push([`events.${o-1}${r[2]??""}`,i.at(n)]),o>=t&&i.clear(n)}for(const[n,r]of s)i.set(n,r);e.events=e.events.filter((n,r)=>r!==t),this.picked=void 0,ue.refresh(e),this.host.changed()}details(e,t){const i=document.createElement("div");i.className="event-head",i.append(this.messages.from,this.seconds(e.t,r=>{e.t=r},`events.${t}.t`)),e.until!==void 0&&i.append(this.messages.to,this.seconds(e.until,r=>{e.until=r},`events.${t}.until`));const s=document.createElement("div");if(s.className="event-params",this.actor==="phenomenon"){const r=document.createElement("span");r.textContent=this.messages.who,s.append(r,this.subject(e))}if(this.actor==="bodies"){const r=document.createElement("span");r.textContent=this.messages.part,s.append(r,this.part(e))}const n=Object.entries(e.params??{});for(const[r,o]of Object.entries(xe.CHOICES))o.absent!==void 0&&o.with.every(a=>e.params?.[a]!==void 0)&&e.params?.[r]===void 0&&n.push([r,o.absent]);for(const[r,o]of n){const a=document.createElement("span");a.className="event-param-label";const d=document.createElement("span");d.className="event-param-name",d.textContent=this.messages.params[r]??r;const l=this.messages.paramHints[r];l&&d.append(Ae.of(l)),a.append(d,this.basis(`events.${t}.params.${r}`));const h=document.createElement("span");h.className="event-param",h.append(this.value(e,r,o,`events.${t}.params.${r}`)),s.append(a,h)}return[i,s]}subject(e){const t=this.host.sighting(),i=document.createElement("select");i.className="event-who";const s=[...t.timeline.allGroups.map(n=>n.id),...q.shapeIds(t)];e.who!==void 0&&!s.includes(e.who)&&s.unshift(e.who);for(const n of s){const r=document.createElement("option");r.value=n,r.textContent=this.host.shapesLabel?.(n)??n,i.append(r)}return i.value=e.who??"",i.addEventListener("change",()=>{this.host.editing(),e.who=i.value,ue.refresh(t),this.host.changed()}),i}part(e){const t=this.host.sighting(),i=q.partOf(e.who),s=i?.element??e.who??"",n=document.createElement("input");return n.type="text",n.className="event-part",n.value=i?.part??"",n.placeholder=this.messages.wholeBody,n.title=this.messages.partHint,n.addEventListener("change",()=>{const r=n.value.trim().replaceAll("/","");this.host.editing(),e.who=r?`${s}/${r}`:s,ue.refresh(t),this.host.changed()}),n}value(e,t,i,s){const n=e.params,r=xe.CHOICES[t];if(r&&typeof i=="string")return this.choice(t,i,r,a=>{a===r.absent?delete n[t]:n[t]=a},s);const o=xe.AMONG[t];if(o&&typeof i=="string")return this.actorChoice(i,o,a=>{n[t]=a},s);if(typeof i=="string")return this.text(i,a=>{n[t]=a},s);if(typeof i=="boolean")return this.check(i,a=>{n[t]=a},s);if(typeof i=="number"){if(t==="glancesUntil")return this.seconds(i,l=>{n[t]=l},s);const a=t.endsWith("S")&&!t.endsWith("PerS"),d=t.endsWith("Deg")?"°":a?"s":t.endsWith("M")?"m":t==="cdM2"?"cd/m²":t==="hz"?"Hz":"";return this.number(i,l=>{n[t]=l},s,d,t==="pitchShare"||a||t.endsWith("PerS")?.05:t.endsWith("M")?.01:1)}if(Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="object"&&a!==null&&typeof a.t=="number"))return this.rows(i,s);if(Array.isArray(i)&&i.every(a=>typeof a=="object"&&a!==null&&typeof a.sourceId=="string"))return document.createTextNode(this.messages.parts.replace("{n}",String(i.length)));if(Array.isArray(i)&&i.every(a=>typeof a=="string"))return document.createTextNode(i.join(", "));if(Array.isArray(i))return document.createTextNode(this.messages.points.replace("{n}",String(i.length)));if(typeof i=="object"&&i!==null){const a=i;if(typeof a.lat=="number"&&typeof a.lng=="number"){const d=document.createElement("span");return typeof a.t=="number"&&d.append(this.seconds(a.t,l=>{a.t=l},s,`${this.messages.at} `)," "),d.append(this.position(i,s)),d}return typeof a.x=="number"?document.createTextNode(`${a.x}, ${a.y}, ${a.z} m`):typeof a.azimuthDeg=="number"&&typeof a.altitudeDeg=="number"?this.direction(a,s):document.createTextNode(Object.entries(a).map(([d,l])=>`${d} ${l??"∅"}`).join(", "))}return document.createTextNode(String(i))}choice(e,t,i,s,n){const r=document.createElement("select");for(const o of i.values){const a=document.createElement("option");a.value=o,a.textContent=this.messages.choices[`${e}.${o}`]??o,r.append(a)}return i.values.includes(t)||r.prepend(new Option(t,t)),r.value=t,r.addEventListener("change",()=>this.edited(()=>s(r.value),n)),r}actorChoice(e,t,i,s){const n=document.createElement("select"),r=[...q.ids(this.host.sighting())].filter(([,o])=>o.some(a=>t.includes(a))).map(([o])=>o);r.includes(e)||r.unshift(e);for(const o of r){const a=q.kindOf(this.host.sighting(),o),d=a==="body"?this.host.bodyLabel?.(o):a==="shape"||a==="group"?this.host.shapesLabel?.(o):void 0;n.append(new Option(d??o,o))}return n.value=e,n.addEventListener("change",()=>this.edited(()=>i(n.value),s)),n}direction(e,t){const i=document.createElement("span");i.className="event-direction",i.append(`${this.messages.params.azimuthDeg??"azimuthDeg"} `,this.number(e.azimuthDeg,n=>{e.azimuthDeg=(n%360+360)%360},t,"°",.1));const s=this.host.compassPoint?.(e.azimuthDeg);if(s){const n=document.createElement("span");n.className="event-direction-point",n.textContent=s,i.append(" ",n)}if(i.append(` ${this.messages.params.altitudeDeg??"altitudeDeg"} `,this.number(e.altitudeDeg,n=>{e.altitudeDeg=Math.max(-90,Math.min(90,n))},t,"°",.1)),e.altitudeDeg===90&&i.append(` (${this.messages.zenith})`),this.host.lookedAt){const n=document.createElement("button");n.type="button",n.className="event-direction-look",n.textContent=this.messages.lookedAt,n.title=this.messages.lookedAtHint,n.addEventListener("click",()=>{const r=this.host.lookedAt?.();r&&this.edited(()=>{e.azimuthDeg=Math.round((r.azimuthDeg%360+360)%360*10)/10,e.altitudeDeg=Math.round(r.altitudeDeg*10)/10},t)}),i.append(" ",n)}return i}rows(e,t){const i=Object.keys(e[0]).filter(a=>a!=="t"&&typeof e[0][a]=="number"),s={kmh:"km/h",degPerS:"°/s",widthM:"m",heightM:"m",altitudeM:"m"},n=document.createElement("span");n.className="event-rows",n.style.setProperty("--columns",String(3+i.length)),e.forEach((a,d)=>{n.append(this.seconds(a.t,h=>{a.t=h,e.sort((c,u)=>c.t-u.t)},t,`${this.messages.at} `));for(const h of i)n.append(this.number(a[h],c=>{a[h]=c},t,s[h]??"",h==="divisor"?.05:1));if(d===0)n.append(document.createElement("span"));else{const h=document.createElement("label");h.className="event-row-step",h.title=this.messages.atOnceHint;const c=this.check(a.step===!0,u=>{u?a.step=!0:delete a.step},t);c.title=this.messages.atOnceHint,h.append(c,` ${this.messages.atOnce}`),n.append(h)}const l=document.createElement("button");l.type="button",l.className="icon-btn event-row-remove",l.innerHTML=M.TRASH,l.title=l.ariaLabel=this.messages.removeRow,l.disabled=e.length<2,l.addEventListener("click",()=>this.edited(()=>{e.splice(d,1)},t)),n.append(l)});const r=document.createElement("button");r.type="button",r.className="icon-btn event-row-add",r.innerHTML=M.PLUS,r.title=r.ariaLabel=this.messages.addRow,r.addEventListener("click",()=>this.edited(()=>{const a=e[e.length-1],d={...a,t:a.t+1e3};delete d.step,e.push(d)},t));const o=document.createElement("span");return o.className="event-table",o.append(n,r),o}position(e,t){const i=this.host.positionFrame?.(),s=this.host.positionMessages?.();if(!i||!s){const o=document.createElement("span");return o.append(this.number(e.lat,a=>{e.lat=a},t,"°",1e-6)," ",this.number(e.lng,a=>{e.lng=a},t,"°",1e-6)),o}xs();const n=document.createElement("rr0-input-position");n.setAttribute("native","geo"),n.setAttribute("name",t.replace(/\./g,"-")),n.build(),n.messages=s,n.basisShown=!1,n.frame=i,n.value={lat:e.lat,lng:e.lng},n.said=e.said;let r;return n.addEventListener("positionchange",o=>{r=o.detail}),n.addEventListener("focusout",o=>{if(!r||n.contains(o.relatedTarget))return;const{value:a,said:d}=r;r=void 0,"lat"in a&&this.edited(()=>{e.lat=Math.round(a.lat*1e7)/1e7,e.lng=Math.round(a.lng*1e7)/1e7,d?e.said=d:delete e.said},t)}),n}text(e,t,i){const s=document.createElement("input");return s.type="text",s.value=e,s.addEventListener("change",()=>this.edited(()=>t(s.value.trim()),i)),s}check(e,t,i){const s=document.createElement("input");return s.type="checkbox",s.checked=e,s.addEventListener("change",()=>this.edited(()=>t(s.checked),i)),s}edited(e,t){this.host.editing(),e(),this.host.sighting().provenance.clear(t),ue.refresh(this.host.sighting()),this.host.changed()}seconds(e,t,i,s=""){const n=this.number(e/1e3,o=>t(Math.round(o*1e3)),i,"s",.1);if(!s)return n;const r=document.createElement("span");return r.append(s,n),r}number(e,t,i,s,n){const r=document.createElement("label"),o=document.createElement("input");return o.type="number",o.step=String(n),o.value=String(n<.001?e:Math.round(e*1e3)/1e3),o.addEventListener("change",()=>{const a=Number(o.value);o.value===""||!Number.isFinite(a)||this.edited(()=>t(a),i)}),r.append(o),s&&r.append(` ${s}`),r}basis(e){wi();const t=document.createElement(et.TAG);t.anchorKey=e,t.messages={title:this.messages.basisTitle,basis:this.messages.basis,basisField:this.messages.basisField,howField:this.messages.howField,rationaleField:this.messages.rationaleField};const i=this.host.valueSources?.();return t.sourceMessages=i?.messages,t.choices=i?.choices??{},t.entry=this.host.sighting().provenance.at(e),t.addEventListener("basischange",s=>{const n=s.detail.entry;this.host.editing(),n?this.host.sighting().provenance.set(e,n):this.host.sighting().provenance.clear(e),this.host.changed()}),t}}const sr=je.catalog({en:()=>L(()=>import("./DecorParameterTexts_en-idbdHsFG.js"),[],import.meta.url).then(E=>E.decorParameterTexts_en),fr:()=>L(()=>import("./DecorParameterTexts_fr-D9GeuW_Y.js"),[],import.meta.url).then(E=>E.decorParameterTexts_fr),es:()=>L(()=>import("./DecorParameterTexts_es-CIkkLQc2.js"),[],import.meta.url).then(E=>E.decorParameterTexts_es),it:()=>L(()=>import("./DecorParameterTexts_it-v7TBrnsr.js"),[],import.meta.url).then(E=>E.decorParameterTexts_it)});class P{static MAX_STOPS=12;static METRES_PER_DEGREE=111320;static SAME_TREE_M=1.5;static SAME_BUILDING_M=2.5;static SAME_STRUCTURE_M=5;static stops(e,t){if(e.length===0)return[];const i=e[0],s=Math.cos(i.lat*Math.PI/180),n=e.slice(1).map((p,m)=>Math.hypot((p.lat-e[m].lat)*P.METRES_PER_DEGREE,(p.lng-e[m].lng)*P.METRES_PER_DEGREE*s)),r=n.reduce((p,m)=>p+m,0),o=Math.max(t,r/(P.MAX_STOPS-1)),a=[i];let d=0,l=o;e.slice(1).forEach((p,m)=>{d+=n[m],d>=l&&(a.push(p),l=d+o)});const h=e[e.length-1],c=a[a.length-1];return Math.hypot((h.lat-c.lat)*P.METRES_PER_DEGREE,(h.lng-c.lng)*P.METRES_PER_DEGREE*s)>t/2&&a.length<P.MAX_STOPS&&a.push(h),a}static async fetch(e,t,i,s={}){if(t.length===0)throw new mi("no-coverage","No place to ask about");const n=t[0],r=Math.cos(n.lat*Math.PI/180),o=new Array(t.length).fill(void 0),a=[],d=Math.max(1,s.concurrency??3);let l=0;const h=async()=>{for(;l<t.length;){const m=l++;try{o[m]=await e.getSurroundings(t[m],i)}catch(f){a.push(f)}}};await Promise.all(Array.from({length:Math.min(d,t.length)},h));const c={trees:[],buildings:[],bridges:[],lines:[]};let u=!1;const p={};if(o.forEach((m,f)=>{if(!m)return;u=!0;const g=(t[f].lng-n.lng)*P.METRES_PER_DEGREE*r,b=(t[f].lat-n.lat)*P.METRES_PER_DEGREE,v=x=>x.map(y=>({...y,eastM:Math.round((y.eastM+g)*10)/10,northM:Math.round((y.northM+b)*10)/10})),I=v(m.trees).sort((x,y)=>Math.hypot(x.eastM-g,x.northM-b)-Math.hypot(y.eastM-g,y.northM-b)).slice(0,s.treesPerStop??m.trees.length);P.add(c.trees,I,(x,y)=>Math.hypot(x.eastM-y.eastM,x.northM-y.northM)<P.SAME_TREE_M),P.add(c.buildings,v(m.buildings),(x,y)=>Math.hypot(x.eastM-y.eastM,x.northM-y.northM)<P.SAME_BUILDING_M&&Math.abs(x.widthM-y.widthM)<1.5&&Math.abs(x.lengthM-y.lengthM)<1.5),P.add(c.bridges,v(m.bridges),(x,y)=>Math.hypot(x.eastM-y.eastM,x.northM-y.northM)<P.SAME_STRUCTURE_M),P.add(c.lines,v(m.lines),(x,y)=>Math.hypot(x.eastM-y.eastM,x.northM-y.northM)<P.SAME_STRUCTURE_M&&Math.abs(x.lengthM-y.lengthM)<5),P.addFurniture(c,m,v),m.incomplete&&(c.incomplete=!0);for(const x of["laser","photo","map","lamps"]){const y=m.dates?.[x];y&&(!p[x]||y>p[x])&&(p[x]=y)}}),!u)throw a.find(m=>!(m instanceof mi&&m.reason==="no-coverage"))??a[0];return Object.keys(p).length>0&&(c.dates=p),c}static later(e,t,i){if(!e.later||t.length===0)return;const s=t[0],n=Math.cos(s.lat*Math.PI/180),r=t.map(o=>e.later(o,i)??Promise.reject(new Error("Nothing comes late")));return Promise.allSettled(r).then(o=>{if(!o.some(d=>d.status==="fulfilled"))throw o[0].reason;const a={};return o.forEach((d,l)=>{if(d.status!=="fulfilled")return;const h=(t[l].lng-s.lng)*P.METRES_PER_DEGREE*n,c=(t[l].lat-s.lat)*P.METRES_PER_DEGREE,u=m=>m.map(f=>({...f,eastM:Math.round((f.eastM+h)*10)/10,northM:Math.round((f.northM+c)*10)/10}));P.addFurniture(a,d.value,u);const p=d.value.dates?.lamps;p&&(!a.dates?.lamps||p>a.dates.lamps)&&(a.dates={lamps:p})}),a})}static addFurniture(e,t,i){t.lamps&&P.add(e.lamps??=[],i(t.lamps),(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1);const s=(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1&&Math.abs((n.headingDeg-r.headingDeg+540)%360-180)<10;t.signals&&P.add(e.signals??=[],i(t.signals),s),t.crossings&&P.add(e.crossings??=[],i(t.crossings),s),t.signs&&P.add(e.signs??=[],i(t.signs),s),t.credits&&P.add(e.credits??=[],t.credits,(n,r)=>n.url===r.url)}static add(e,t,i){for(const s of t)e.some(n=>i(n,s))||e.push(s)}}class tt{static FLOOR_HEIGHT_M=3;static CROSSING_LENGTH_M=2.5;static of(e,t,i){const{kept:s}=i,n=g=>s.some(b=>b.kind===g),r={tree:n("tree"),building:n("building"),bridge:n("bridge"),wire:n("wire"),streetlight:n("streetlight"),trafficlight:n("trafficlight"),crossing:n("crossing"),roadsign:n("roadsign")},o=[...s,...i.others??[]],a=new Set(o.map(g=>g.id));let d=0;const l=()=>{let g;do g=`${e}-${++d}`;while(a.has(g));return a.add(g),g},h={tree:o.filter(g=>g.kind==="tree").length,building:o.filter(g=>g.kind==="building").length,bridge:o.filter(g=>g.kind==="bridge").length,wire:o.filter(g=>g.kind==="wire").length,streetlight:o.filter(g=>g.kind==="streetlight").length,trafficlight:o.filter(g=>g.kind==="trafficlight").length,crossing:o.filter(g=>g.kind==="crossing").length,roadsign:o.filter(g=>g.kind==="roadsign").length},c=new Set(o.map(g=>typeof g.title=="string"?g.title:"")),u=(g,b)=>{const v=b??`${i.kindName(g)} ${++h[g]}`;let I=v;for(let x=2;c.has(I);x++)I=`${v} (${x})`;return c.add(I),I},p=t.dates??{},m=(...g)=>{const b=g.filter(v=>v!==void 0).sort().at(-1);return b?{surveyedOn:b}:{}},f=[];if(!r.tree)for(const g of t.trees)f.push({id:l(),kind:"tree",title:u("tree",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.widthM,heightM:g.heightM},origin:e,...m(p.laser)});if(!r.building)for(const g of t.buildings)f.push({id:l(),kind:"building",title:u("building",g.name),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.lengthM,heightM:g.heightM},...g.style==="church"||g.style==="monument"?{}:{floors:g.floors??Math.max(1,Math.round((g.heightM-(g.roof?.riseM??0))/(g.facade?.storeyM??tt.FLOOR_HEIGHT_M)))},...g.roof?{roof:g.roof}:{},...g.facade?{facade:g.facade}:{},origin:e,...m(p.map,p.laser,g.roof?.color?p.photo:void 0)});if(!r.bridge)for(const g of t.bridges)f.push({id:l(),kind:"bridge",title:u("bridge",g.name?`${i.kindName("bridge")} (${g.name})`:void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,widthM:g.widthM,heightM:g.heightM},origin:e,...m(p.map,p.laser)});if(!r.wire)for(const g of t.lines)f.push({id:l(),kind:"wire",title:u("wire",`${i.kindName("wire")} (${g.voltage})`),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,heightM:g.heightM},wire:{strands:g.acrossM.map(b=>({heightM:g.heightM,acrossM:b})),poles:"both",poleHeightM:g.poleHeightM},origin:e,...m(p.map,p.laser)});if(!r.streetlight)for(const g of t.lamps??[]){const b={...g.colorTemperatureK?{colorTemperatureK:g.colorTemperatureK}:{},...g.lumens?{lumens:g.lumens}:{},...g.mount==="wall"?{mount:"wall"}:{},...g.supposed?{supposed:!0}:{}};f.push({id:l(),kind:"streetlight",title:u("streetlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,...g.heightM?{sizeM:{heightM:g.heightM}}:{},...Object.keys(b).length>0?{lamp:b}:{},origin:e,...m(p.lamps)})}if(!r.trafficlight)for(const g of t.signals??[])f.push({id:l(),kind:"trafficlight",title:u("trafficlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lights:g.for==="pedestrians"?Di.pedestrianLights(g.phase):Di.vehicleLights(g.phase),origin:e,...m(p.lamps)});if(!r.crossing)for(const g of t.crossings??[])f.push({id:l(),kind:"crossing",title:u("crossing",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sizeM:{widthM:g.widthM,lengthM:tt.CROSSING_LENGTH_M},origin:e,...m(p.lamps)});if(!r.roadsign)for(const g of t.signs??[])f.push({id:l(),kind:"roadsign",title:u("roadsign",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sign:{face:g.face,...g.code?{code:g.code}:{},...g.value?{value:g.value}:{}},origin:e,...m(p.lamps)});return{planted:f,handPlaced:Object.values(r).some(Boolean)}}}class ie{constructor(e,t,i,s,n={}){this.status=e,this.host=t,this.loadProvider=s,this.messages=i,this.debounceMs=n.debounceMs??ie.DEFAULT_DEBOUNCE_MS,this.radiusM=n.radiusM??ie.DEFAULT_RADIUS_M}static SAME_PLACE_M=25;static METRES_PER_DEGREE=111320;static DEFAULT_RADIUS_M=100;static DEFAULT_DEBOUNCE_MS=800;static TREES_PER_STOP=80;static WALK_LEAD_S=4;static WALK_LEAD_SHARE=.6;static SAME_BUILDING_M=3;static SAME_OBJECT_M=1.5;messages;debounceMs;radiusM;enabled=!0;surveyedFor;timer;token=0;surveyed="";furnitureSaid="";furnitureCredits=[];asked=[];lastStep;walkSpeedMps=0;setMessages(e){this.messages=e}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.cancel())}withdraw(){this.cancel(),this.withdrawPlanted(),this.say("")}placeLoaded(e,t){this.cancel(),this.surveyedFor=e!==void 0&&t!==void 0?{lat:e,lng:t}:void 0,this.say("")}radiusChanged(e,t,i){e!==this.radiusM&&(this.radiusM=e,!(!this.enabled||t===void 0||i===void 0)&&(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(t,i),this.debounceMs)))}placeChanged(e,t){!this.enabled||e===void 0||t===void 0||this.surveyedFor&&this.isSamePlace(this.surveyedFor,e,t)||(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(e,t),this.debounceMs))}walked(e,t,i,s=Date.now()){if(clearTimeout(this.timer),this.timer=void 0,this.surveyedFor={lat:e,lng:t},this.lastStep){const a=(s-this.lastStep.atMs)/1e3,d=this.metresBetween(this.lastStep,e,t);this.walkSpeedMps=a>0&&a<2?.5*this.walkSpeedMps+.5*d/a:0}if(this.lastStep={lat:e,lng:t,atMs:s},!this.enabled)return;const n=Math.min(this.radiusM,Math.max(this.radiusM*ie.WALK_LEAD_SHARE,this.walkSpeedMps*ie.WALK_LEAD_S)),r=i*Math.PI/180,o={lat:e+Math.cos(r)*n/ie.METRES_PER_DEGREE,lng:t+Math.sin(r)*n/(ie.METRES_PER_DEGREE*Math.cos(e*Math.PI/180))};this.asked.some(a=>this.metresBetween(a,o.lat,o.lng)<this.radiusM/2)||(this.asked.push(o),this.plantAhead(o))}async plantAhead(e){const t=this.token;try{const i=await this.loadProvider(e.lat,e.lng);if(!i||t!==this.token)return;const s=await i.getSurroundings(e,this.radiusM);if(t!==this.token)return;this.addAhead(i,this.fromCentre(s,e)),(s.incomplete?i.later?.(e,this.radiusM):void 0)?.then(r=>{t===this.token&&this.addAhead(i,this.fromCentre({trees:[],buildings:[],bridges:[],lines:[],...r},e))},()=>{})}catch{this.asked=this.asked.filter(i=>i!==e)}}addAhead(e,t){const i=this.host.decor(),s=i.filter(a=>a.origin===void 0),n=i.filter(a=>a.origin!==void 0),{planted:r}=tt.of(e.id,t,{kept:s,others:n,kindName:a=>this.host.kindName(a)}),o=r.filter(a=>!n.some(d=>ie.same(d,a)));o.length>0&&this.host.setDecor([...i,...o])}static same(e,t){if(e.kind!==t.kind)return!1;const i=Math.hypot(e.eastM-t.eastM,e.northM-t.northM);if(e.kind!=="building")return i<ie.SAME_OBJECT_M;const s=n=>[n.sizeM?.widthM??0,n.sizeM?.lengthM??0];return i<ie.SAME_BUILDING_M&&s(e).every((n,r)=>Math.abs(n-s(t)[r])<1.5)}fromCentre(e,t){const i=this.host.centre?.();if(!i)return e;const s=(t.lng-i.lng)*ie.METRES_PER_DEGREE*Math.cos(i.lat*Math.PI/180),n=(t.lat-i.lat)*ie.METRES_PER_DEGREE;if(Math.hypot(s,n)<.01)return e;const r=o=>o?.map(a=>({...a,eastM:Math.round((a.eastM+s)*100)/100,northM:Math.round((a.northM+n)*100)/100}));return{...e,...e.trees?{trees:r(e.trees)}:{},...e.buildings?{buildings:r(e.buildings)}:{},...e.bridges?{bridges:r(e.bridges)}:{},...e.lines?{lines:r(e.lines)}:{},...e.lamps?{lamps:r(e.lamps)}:{},...e.signals?{signals:r(e.signals)}:{},...e.crossings?{crossings:r(e.crossings)}:{},...e.signs?{signs:r(e.signs)}:{}}}metresBetween(e,t,i){const s=(e.lat-t)*ie.METRES_PER_DEGREE,n=(e.lng-i)*ie.METRES_PER_DEGREE*Math.cos(t*Math.PI/180);return Math.hypot(s,n)}async survey(e,t){const i=++this.token;this.surveyedFor={lat:e,lng:t},this.asked=[{lat:e,lng:t}],this.lastStep=void 0,this.host.busy(!0,this.messages.surveyBusy);try{const s=await this.loadProvider(e,t);if(i!==this.token)return;if(s===void 0){this.withdrawPlanted(),this.say("");return}this.say(this.messages.surveyBusy);const n=P.stops([{lat:e,lng:t},...this.host.track?.()??[]],this.radiusM),r=n.length>1?await P.fetch(s,n,this.radiusM,{treesPerStop:ie.TREES_PER_STOP}):await s.getSurroundings({lat:e,lng:t},this.radiusM);if(i!==this.token)return;this.plant(s,this.fromCentre(r,{lat:e,lng:t})),r.incomplete&&this.awaitLate(s,n,i)}catch(s){if(i!==this.token)return;s instanceof mi&&s.reason==="no-coverage"?(this.withdrawPlanted(),this.say("")):this.say(this.messages.surveyUnreachable)}finally{i===this.token&&this.host.busy(!1,"")}}cancel(){clearTimeout(this.timer),this.timer=void 0,this.token++,this.host.busy(!1,"")}withoutPlanted(){return this.host.decor().filter(e=>e.origin===void 0)}withdrawPlanted(){this.host.decor().some(e=>e.origin!==void 0)&&this.host.setDecor(this.withoutPlanted())}plant(e,t){const i=this.withoutPlanted(),{planted:s,handPlaced:n}=tt.of(e.id,t,{kept:i,kindName:d=>this.host.kindName(d)}),r=d=>s.filter(l=>l.kind===d).length;if((s.length>0||this.host.decor().length!==i.length)&&this.host.setDecor([...i,...s]),s.length===0){this.furnitureSaid="",this.surveyed=n?this.messages.surveyKept:this.messages.surveyNone.replace("{radius}",String(this.radiusM)),this.say(this.surveyed,t.incomplete?this.messages.surveyFurniturePending:"");return}this.host.cite({title:`${e.name}, survey of the surroundings`,url:e.creditUrl,publication:{publisher:e.name}});const o=this.messages.surveyDone.replace("{trees}",String(r("tree"))).replace("{buildings}",String(r("building"))).replace("{bridges}",String(r("bridge"))).replace("{lines}",String(r("wire"))).replace("{source}",e.name),a=this.datesText(t.dates);this.surveyed=[o,a,n?this.messages.surveyKept:""].filter(d=>d!=="").join(" "),this.citeCredits(t),this.furnitureCredits=t.credits??[],this.furnitureSaid=this.furnitureText(s,t),this.say(this.surveyed,[this.furnitureSaid,t.incomplete?this.messages.surveyFurniturePending:""].filter(d=>d!=="").join(" "))}citeCredits(e){for(const t of e.credits??[])this.host.cite({title:t.licence?`${t.name} (${t.licence})`:t.name,url:t.url,publication:{publisher:t.name}})}awaitLate(e,t,i){const s=t.length>1?P.later(e,t,this.radiusM):e.later?.(t[0],this.radiusM);if(!s){this.say(this.surveyed,"");return}this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurniturePending].filter(n=>n!=="").join(" ")),s.then(n=>{i===this.token&&this.plantLate(e,this.fromCentre(n,t[0]))},()=>{i===this.token&&this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurnitureUnavailable].filter(n=>n!=="").join(" "),{label:this.messages.surveyFurnitureRetry,run:()=>this.awaitLate(e,t,i)})})}plantLate(e,t){const i=this.host.decor(),{planted:s}=tt.of(e.id,{trees:[],buildings:[],bridges:[],lines:[],...t},{kept:i,kindName:r=>this.host.kindName(r)});s.length>0&&this.host.setDecor([...i,...s]),this.citeCredits(t);const n=i.filter(r=>r.origin===e.id).concat(s);this.furnitureSaid=this.furnitureText(n,{credits:[...this.furnitureCredits,...t.credits??[]]}),this.say(this.surveyed,this.furnitureSaid)}furnitureText(e,t){const i=o=>e.filter(a=>a.kind===o).length;if(!e.some(o=>o.kind==="streetlight"||o.kind==="trafficlight"||o.kind==="crossing"||o.kind==="roadsign"))return"";const s=o=>o.of==="lamps"?i("streetlight")>0:o.of==="signals"?i("trafficlight")>0:!0,r=[...new Set((t.credits??[]).filter(s).map(o=>o.name))].join(" + ")||"OpenStreetMap";return this.messages.surveyFurnitureDone.replace("{source}",r).replace("{lamps}",String(i("streetlight"))).replace("{signals}",String(i("trafficlight"))).replace("{crossings}",String(i("crossing"))).replace("{signs}",String(i("roadsign")))}datesText(e){if(!e)return"";const t=[["laser",this.messages.surveyLaserLabel],["photo",this.messages.surveyPhotoLabel],["map",this.messages.surveyMapLabel],["lamps",this.messages.surveyLampsLabel]].filter(([i])=>e[i]!==void 0).map(([i,s])=>`${s} ${e[i]}`);return t.length>0?this.messages.surveyDated.replace("{dates}",t.join(", ")):""}isSamePlace(e,t,i){return this.metresBetween(e,t,i)<ie.SAME_PLACE_M}say(e,t="",i){if(this.status.textContent=[e,t].filter(n=>n!=="").join(" "),!i)return;const s=this.status.ownerDocument.createElement("button");s.type="button",s.className="scenery-retry",s.textContent=i.label,s.addEventListener("click",i.run),this.status.append(" ",s)}}class zt{static newestSurvey(e){return e.filter(t=>t.origin!==void 0).map(t=>t.surveyedOn).filter(t=>t!==void 0).sort().at(-1)}static latestObservationDay(e){if(!e?.year)return;const t=e.month??12,i=e.day??new Date(Date.UTC(e.year,t,0)).getUTCDate();return`${String(e.year).padStart(4,"0")}-${String(t).padStart(2,"0")}-${String(i).padStart(2,"0")}`}static anachronism(e,t){const i=zt.newestSurvey(e),s=zt.latestObservationDay(t);return i&&s&&i>s?{survey:i,observation:s}:void 0}}class me{static number(e,t,i,s,n,r,o={}){return{type:"number",key:e,label:t,min:i,max:s,step:n,unit:r,required:!0,...o}}static natural(e){return(t,i)=>i?.natural?.[e]}static BASE={kind:"decor-base",title:"object",parameters:[{type:"said",key:"title",required:!0,label:"name"},{type:"position",key:"eastM",secondKey:"northM",saidKey:"saidPosition",native:"local",step:.5,label:"position"},me.number("altitudeM","altitude",-1e3,3e4,1,"m"),me.number("headingDeg","heading",0,360,1,"°"),{type:"colour",key:"color",label:"colour",fallback:"#808080",visibleWhen:(e,t)=>t?.traits.color===!0},me.number("sizeM.widthM","width",.1,1e3,.1,"m",{required:!1,effective:me.natural("widthM")}),me.number("sizeM.lengthM","length",.1,1e3,.1,"m",{required:!1,effective:me.natural("lengthM")}),me.number("sizeM.heightM","height",.1,1e3,.1,"m",{required:!1,effective:me.natural("heightM")}),{type:"choice",key:"model.id",label:"n3DModel",choices:[],empty:"noModelBuiltInShape",optionsOf:(e,t)=>[...t?.models??[]],effective:(e,t)=>t?.defaultModelId}]};static HEADLIGHT_LABELS={off:"off",position:"positionLights",dipped:"dippedBeam",main:"mainBeam",fog:"fogLamps"};static STATE={kind:"decor-state",title:"state",parameters:[{type:"boolean",key:"lit",required:!0,label:"lit",visibleWhen:(e,t)=>t?.traits.lit===!0&&t?.traits.headlights!==!0},{type:"choice",key:"headlights",required:!0,label:"headlights",choices:Hn.MODES.map(e=>({value:e,label:me.HEADLIGHT_LABELS[e]})),visibleWhen:(e,t)=>t?.traits.headlights===!0},{type:"choice",key:"lightRig",label:"lights",choices:[],empty:"noLights",optionsOf:(e,t)=>(t?.lightRigs??[]).map(i=>({value:i.value,label:i.label})),visibleWhen:(e,t)=>t?.traits.lights===!0},{type:"choice",key:"observerSide",label:"witnessLocation",choices:[],empty:"notPresent",optionsOf:(e,t)=>[...t?.seats??[]],visibleWhen:(e,t)=>t?.traits.observerSide===!0}]};static seatsFor(e){return $n(e).map(t=>({value:t,label:Ss.sideLabel(t)}))}}class ce extends Error{constructor(e,t,i){const s=e==="rejected"&&typeof t=="string"?t:void 0,n=e==="rejected"?i:t;super(s??e,n===void 0?void 0:{cause:n}),this.kind=e,this.name="NarrativeError",this.detail=s}detail}class Ut{static KNOWN_TAGS=["landing","trace","aerial observation","project sign","paralysis","contact","occupants","close encounter","photograph","radar","electromagnetic effect"];static RULES=[{draft:`Sizes are ANGULAR, in degrees, and never metric — the format stores no physical size, because an
232
+ `;static ADDABLE={observer:["look","walk","follow"],phenomenon:["stand","blink","turn","roll","vibrate","spiral","vanish"],bodies:["motion","spin","rise","turn","ride","light","blink","vanish"]};static CHOICES={sizeBy:{values:["","altitude"],absent:"",with:["sizeDeg"]},side:{values:["left","right"],with:[]},seenFrom:{values:["","craft"],absent:"",with:["side","byDeg"]}};static AMONG={target:["shape","group","body","decor"],in:["body","decor"],vehicle:["decor"]};words;get messages(){return this.words}note;reset;fields;timeline;timelineHost;empty;addButton;addMenu;deleteButton;picked;localize(e){this.words=e,this.localizeList(),this.render()}localizeList(){const e=this.messages;this.timeline.setMessages({addKeyframeHere:e.add,keyframeHere:e.add,zoomHint:e.zoomHint}),this.addButton.innerHTML=`${L.PLUS} ${e.add}`,this.addMenu.setKinds(xe.ADDABLE[this.actor].map(t=>({value:t,label:e.kinds[t]??t}))),this.empty.textContent=e.none,this.deleteButton.title=e.remove,this.deleteButton.setAttribute("aria-label",e.remove)}choose(e){this.picked=e;const t=this.host.sighting().events?.[e];t&&this.host.seek(t.t),this.render(),this.host.picked?.()}syncTimeline(e){const t=this.messages,i=l=>t.kinds[l.eventType]??l.eventType,s=e.map(({event:l,index:h})=>({id:String(h),t:l.t,until:Math.max(l.t,l.until??l.t),label:i(l)})),n=s.flatMap(l=>[l.t,l.until]),r=this.host.duration?.()??Math.max(1,...n),o=Math.min(...n),a=Math.max(...n),d=Math.max(500,(a-o)/10);this.timeline.show([{id:this.actor,label:this.titleText(),color:xe.COLOR,times:[],spans:s,selected:this.picked===void 0?void 0:String(this.picked),select:l=>this.choose(Number(l)),open:()=>{},add:()=>this.addButton.click()}],r,this.host.now(),{from:o-d,to:a+d})}setTime(e){this.timeline.setTime(e)}static COLOR="#4f8fd6";shownTheirs;sync(){this.theirs()!==this.shownTheirs&&this.render()}theirs(){const e=this.host.sighting();return this.actor==="observer"?ue.observerTrackIsExpanded(e):this.actor==="phenomenon"?ue.timelineIsExpanded(e):ue.bodiesAreExpanded(e)}who(){const e=this.host.sighting();if(this.actor==="observer")return q.observerId(e);if(this.actor==="bodies")return this.host.currentBody?.();const t=this.host.currentShapes?.();if(t!==void 0)return t;const i=(e.events??[]).find(n=>n.eventType==="stand"&&q.isPhenomenon(e,n));if(i?.who!==void 0)return i.who;const s=q.shapeIds(e);return s.length>0?e.timeline.topOf(s[0]):void 0}events(){const e=this.host.sighting(),t=this.actor==="bodies"?this.host.currentBody?.():void 0,i=s=>this.actor==="observer"?q.isObserver(e,s):this.actor==="phenomenon"?q.isPhenomenon(e,s):t!==void 0&&(s.who===t||q.partOf(s.who)?.element===t);return(e.events??[]).map((s,n)=>({event:s,index:n})).filter(({event:s})=>i(s))}get pickedIndex(){return this.picked}pick(e){this.picked=e,this.render(),this.root.scrollIntoView?.({block:"start"})}titleText(){return this.actor==="observer"?this.messages.title:this.actor==="phenomenon"?this.messages.phenomenonTitle:this.messages.bodyTitle.replace("{body}",this.host.bodyLabel?.(this.who()??"")??this.who()??"")}render(){if(!this.words)return;this.shownTheirs=this.theirs(),this.root.querySelector(".events-title").textContent=this.titleText(),this.root.hidden=this.actor==="bodies"&&this.who()===void 0;const e=this.events();e.some(({index:n})=>n===this.picked)||(this.picked=e[0]?.index);const t=this.shownTheirs;this.note.hidden=e.length===0,this.note.textContent=this.actor==="observer"?t?this.messages.derivedNote:this.messages.overriddenNote:this.actor==="phenomenon"?t?this.messages.derivedShapesNote:this.messages.overriddenShapesNote:t?this.messages.derivedBodiesNote:this.messages.overriddenBodiesNote,this.reset.hidden=e.length===0||t,this.reset.textContent=this.messages.resetToEvents,this.empty.hidden=e.length>0,this.timelineHost.hidden=e.length===0,this.syncTimeline(e);const i=this.picked===void 0?void 0:this.host.sighting().events?.[this.picked],s=i?this.details(i,this.picked):[];s[0]?.append(this.deleteButton),this.fields.replaceChildren(...s)}add(e){const t=this.host.sighting(),i=this.who();if(i===void 0)return;const s=Math.round(this.host.now()),n=t.observerTrack.getInterpolatedPoseAt(s)??t.observerTrack.getLatestPoseAt(s),r=n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:t.event.place?.[0]&&{lat:t.event.place[0].lat,lng:t.event.place[0].lng},o=t.interpretation?.bodies.find(h=>h.id!==i)?.id??"",a={look:{params:{headingDeg:Math.round(n?.headingDeg??0),pitchDeg:Math.round(n?.pitchDeg??0)}},walk:{until:s+1e4,params:{from:{...r},to:{...r}}},follow:{until:s+5e3,params:{target:o}},stand:{params:{place:{...r},metres:[{t:s,widthM:1,heightM:1}]}},blink:{until:s+5e3,params:{onS:.5,offS:.5,off:{transparency:1}}},vanish:{},motion:{until:s+2e3,params:{motion:"",to:1}},spin:{until:s+5e3,params:{motion:"",turnsPerS:.5}},rise:{until:s+3e3,params:{distanceM:1,angleDeg:0,headingDeg:0,stops:!0}},ride:{params:{in:o,aboveM:0}},turn:{until:s+1e3,params:{headingDeg:0}}};this.actor==="phenomenon"&&Object.assign(a,{turn:{until:s+1e3,params:{byDeg:15,side:"left"}},roll:{until:s+500,params:{toDeg:20}},vibrate:{until:s+1e3,params:{hz:10,amplitudeShare:.1,riseS:.3}},spiral:{until:s+1e3,params:{turns:1,radiusDeg:2,shrink:.5,clockwise:!0,rollDeg:360}}}),this.actor==="bodies"&&Object.assign(a,{blink:{until:s+5e3,params:{onS:.5,offS:.5,cdM2:500}},light:{params:{cdM2:500}}});const d=a[e]??{},l={type:"event",eventType:e,who:i,t:s,...d.until===void 0?{}:{until:d.until},...d.params?{params:d.params}:{}};this.host.editing(),t.events=[...t.events??[],l],this.picked=t.events.length-1,ue.refresh(t),this.host.changed()}remove(){const e=this.host.sighting(),t=this.picked;if(t===void 0||!e.events?.[t])return;this.host.editing();const i=e.provenance,s=[];for(const n of i.paths()){const r=/^events\.(\d+)(\..*)?$/.exec(n);if(!r)continue;const o=Number(r[1]);o>t&&s.push([`events.${o-1}${r[2]??""}`,i.at(n)]),o>=t&&i.clear(n)}for(const[n,r]of s)i.set(n,r);e.events=e.events.filter((n,r)=>r!==t),this.picked=void 0,ue.refresh(e),this.host.changed()}details(e,t){const i=document.createElement("div");i.className="event-head",i.append(this.messages.from,this.seconds(e.t,r=>{e.t=r},`events.${t}.t`)),e.until!==void 0&&i.append(this.messages.to,this.seconds(e.until,r=>{e.until=r},`events.${t}.until`));const s=document.createElement("div");if(s.className="event-params",this.actor==="phenomenon"){const r=document.createElement("span");r.textContent=this.messages.who,s.append(r,this.subject(e))}if(this.actor==="bodies"){const r=document.createElement("span");r.textContent=this.messages.part,s.append(r,this.part(e))}const n=Object.entries(e.params??{});for(const[r,o]of Object.entries(xe.CHOICES))o.absent!==void 0&&o.with.every(a=>e.params?.[a]!==void 0)&&e.params?.[r]===void 0&&n.push([r,o.absent]);for(const[r,o]of n){const a=document.createElement("span");a.className="event-param-label";const d=document.createElement("span");d.className="event-param-name",d.textContent=this.messages.params[r]??r;const l=this.messages.paramHints[r];l&&d.append(Ae.of(l)),a.append(d,this.basis(`events.${t}.params.${r}`));const h=document.createElement("span");h.className="event-param",h.append(this.value(e,r,o,`events.${t}.params.${r}`)),s.append(a,h)}return[i,s]}subject(e){const t=this.host.sighting(),i=document.createElement("select");i.className="event-who";const s=[...t.timeline.allGroups.map(n=>n.id),...q.shapeIds(t)];e.who!==void 0&&!s.includes(e.who)&&s.unshift(e.who);for(const n of s){const r=document.createElement("option");r.value=n,r.textContent=this.host.shapesLabel?.(n)??n,i.append(r)}return i.value=e.who??"",i.addEventListener("change",()=>{this.host.editing(),e.who=i.value,ue.refresh(t),this.host.changed()}),i}part(e){const t=this.host.sighting(),i=q.partOf(e.who),s=i?.element??e.who??"",n=document.createElement("input");return n.type="text",n.className="event-part",n.value=i?.part??"",n.placeholder=this.messages.wholeBody,n.title=this.messages.partHint,n.addEventListener("change",()=>{const r=n.value.trim().replaceAll("/","");this.host.editing(),e.who=r?`${s}/${r}`:s,ue.refresh(t),this.host.changed()}),n}value(e,t,i,s){const n=e.params,r=xe.CHOICES[t];if(r&&typeof i=="string")return this.choice(t,i,r,a=>{a===r.absent?delete n[t]:n[t]=a},s);const o=xe.AMONG[t];if(o&&typeof i=="string")return this.actorChoice(i,o,a=>{n[t]=a},s);if(typeof i=="string")return this.text(i,a=>{n[t]=a},s);if(typeof i=="boolean")return this.check(i,a=>{n[t]=a},s);if(typeof i=="number"){if(t==="glancesUntil")return this.seconds(i,l=>{n[t]=l},s);const a=t.endsWith("S")&&!t.endsWith("PerS"),d=t.endsWith("Deg")?"°":a?"s":t.endsWith("M")?"m":t==="cdM2"?"cd/m²":t==="hz"?"Hz":"";return this.number(i,l=>{n[t]=l},s,d,t==="pitchShare"||a||t.endsWith("PerS")?.05:t.endsWith("M")?.01:1)}if(Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="object"&&a!==null&&typeof a.t=="number"))return this.rows(i,s);if(Array.isArray(i)&&i.every(a=>typeof a=="object"&&a!==null&&typeof a.sourceId=="string"))return document.createTextNode(this.messages.parts.replace("{n}",String(i.length)));if(Array.isArray(i)&&i.every(a=>typeof a=="string"))return document.createTextNode(i.join(", "));if(Array.isArray(i))return document.createTextNode(this.messages.points.replace("{n}",String(i.length)));if(typeof i=="object"&&i!==null){const a=i;if(typeof a.lat=="number"&&typeof a.lng=="number"){const d=document.createElement("span");return typeof a.t=="number"&&d.append(this.seconds(a.t,l=>{a.t=l},s,`${this.messages.at} `)," "),d.append(this.position(i,s)),d}return typeof a.x=="number"?document.createTextNode(`${a.x}, ${a.y}, ${a.z} m`):typeof a.azimuthDeg=="number"&&typeof a.altitudeDeg=="number"?this.direction(a,s):document.createTextNode(Object.entries(a).map(([d,l])=>`${d} ${l??"∅"}`).join(", "))}return document.createTextNode(String(i))}choice(e,t,i,s,n){const r=document.createElement("select");for(const o of i.values){const a=document.createElement("option");a.value=o,a.textContent=this.messages.choices[`${e}.${o}`]??o,r.append(a)}return i.values.includes(t)||r.prepend(new Option(t,t)),r.value=t,r.addEventListener("change",()=>this.edited(()=>s(r.value),n)),r}actorChoice(e,t,i,s){const n=document.createElement("select"),r=[...q.ids(this.host.sighting())].filter(([,o])=>o.some(a=>t.includes(a))).map(([o])=>o);r.includes(e)||r.unshift(e);for(const o of r){const a=q.kindOf(this.host.sighting(),o),d=a==="body"?this.host.bodyLabel?.(o):a==="shape"||a==="group"?this.host.shapesLabel?.(o):void 0;n.append(new Option(d??o,o))}return n.value=e,n.addEventListener("change",()=>this.edited(()=>i(n.value),s)),n}direction(e,t){const i=document.createElement("span");i.className="event-direction",i.append(`${this.messages.params.azimuthDeg??"azimuthDeg"} `,this.number(e.azimuthDeg,n=>{e.azimuthDeg=(n%360+360)%360},t,"°",.1));const s=this.host.compassPoint?.(e.azimuthDeg);if(s){const n=document.createElement("span");n.className="event-direction-point",n.textContent=s,i.append(" ",n)}if(i.append(` ${this.messages.params.altitudeDeg??"altitudeDeg"} `,this.number(e.altitudeDeg,n=>{e.altitudeDeg=Math.max(-90,Math.min(90,n))},t,"°",.1)),e.altitudeDeg===90&&i.append(` (${this.messages.zenith})`),this.host.lookedAt){const n=document.createElement("button");n.type="button",n.className="event-direction-look",n.textContent=this.messages.lookedAt,n.title=this.messages.lookedAtHint,n.addEventListener("click",()=>{const r=this.host.lookedAt?.();r&&this.edited(()=>{e.azimuthDeg=Math.round((r.azimuthDeg%360+360)%360*10)/10,e.altitudeDeg=Math.round(r.altitudeDeg*10)/10},t)}),i.append(" ",n)}return i}rows(e,t){const i=Object.keys(e[0]).filter(a=>a!=="t"&&typeof e[0][a]=="number"),s={kmh:"km/h",degPerS:"°/s",widthM:"m",heightM:"m",altitudeM:"m"},n=document.createElement("span");n.className="event-rows",n.style.setProperty("--columns",String(3+i.length)),e.forEach((a,d)=>{n.append(this.seconds(a.t,h=>{a.t=h,e.sort((c,u)=>c.t-u.t)},t,`${this.messages.at} `));for(const h of i)n.append(this.number(a[h],c=>{a[h]=c},t,s[h]??"",h==="divisor"?.05:1));if(d===0)n.append(document.createElement("span"));else{const h=document.createElement("label");h.className="event-row-step",h.title=this.messages.atOnceHint;const c=this.check(a.step===!0,u=>{u?a.step=!0:delete a.step},t);c.title=this.messages.atOnceHint,h.append(c,` ${this.messages.atOnce}`),n.append(h)}const l=document.createElement("button");l.type="button",l.className="icon-btn event-row-remove",l.innerHTML=L.TRASH,l.title=l.ariaLabel=this.messages.removeRow,l.disabled=e.length<2,l.addEventListener("click",()=>this.edited(()=>{e.splice(d,1)},t)),n.append(l)});const r=document.createElement("button");r.type="button",r.className="icon-btn event-row-add",r.innerHTML=L.PLUS,r.title=r.ariaLabel=this.messages.addRow,r.addEventListener("click",()=>this.edited(()=>{const a=e[e.length-1],d={...a,t:a.t+1e3};delete d.step,e.push(d)},t));const o=document.createElement("span");return o.className="event-table",o.append(n,r),o}position(e,t){const i=this.host.positionFrame?.(),s=this.host.positionMessages?.();if(!i||!s){const o=document.createElement("span");return o.append(this.number(e.lat,a=>{e.lat=a},t,"°",1e-6)," ",this.number(e.lng,a=>{e.lng=a},t,"°",1e-6)),o}xs();const n=document.createElement("rr0-input-position");n.setAttribute("native","geo"),n.setAttribute("name",t.replace(/\./g,"-")),n.build(),n.messages=s,n.basisShown=!1,n.frame=i,n.value={lat:e.lat,lng:e.lng},n.said=e.said;let r;return n.addEventListener("positionchange",o=>{r=o.detail}),n.addEventListener("focusout",o=>{if(!r||n.contains(o.relatedTarget))return;const{value:a,said:d}=r;r=void 0,"lat"in a&&this.edited(()=>{e.lat=Math.round(a.lat*1e7)/1e7,e.lng=Math.round(a.lng*1e7)/1e7,d?e.said=d:delete e.said},t)}),n}text(e,t,i){const s=document.createElement("input");return s.type="text",s.value=e,s.addEventListener("change",()=>this.edited(()=>t(s.value.trim()),i)),s}check(e,t,i){const s=document.createElement("input");return s.type="checkbox",s.checked=e,s.addEventListener("change",()=>this.edited(()=>t(s.checked),i)),s}edited(e,t){this.host.editing(),e(),this.host.sighting().provenance.clear(t),ue.refresh(this.host.sighting()),this.host.changed()}seconds(e,t,i,s=""){const n=this.number(e/1e3,o=>t(Math.round(o*1e3)),i,"s",.1);if(!s)return n;const r=document.createElement("span");return r.append(s,n),r}number(e,t,i,s,n){const r=document.createElement("label"),o=document.createElement("input");return o.type="number",o.step=String(n),o.value=String(n<.001?e:Math.round(e*1e3)/1e3),o.addEventListener("change",()=>{const a=Number(o.value);o.value===""||!Number.isFinite(a)||this.edited(()=>t(a),i)}),r.append(o),s&&r.append(` ${s}`),r}basis(e){wi();const t=document.createElement(et.TAG);t.anchorKey=e,t.messages={title:this.messages.basisTitle,basis:this.messages.basis,basisField:this.messages.basisField,howField:this.messages.howField,rationaleField:this.messages.rationaleField};const i=this.host.valueSources?.();return t.sourceMessages=i?.messages,t.choices=i?.choices??{},t.entry=this.host.sighting().provenance.at(e),t.addEventListener("basischange",s=>{const n=s.detail.entry;this.host.editing(),n?this.host.sighting().provenance.set(e,n):this.host.sighting().provenance.clear(e),this.host.changed()}),t}}const sr=Ge.catalog({en:()=>D(()=>import("./DecorParameterTexts_en-idbdHsFG.js"),[],import.meta.url).then(k=>k.decorParameterTexts_en),fr:()=>D(()=>import("./DecorParameterTexts_fr-D9GeuW_Y.js"),[],import.meta.url).then(k=>k.decorParameterTexts_fr),es:()=>D(()=>import("./DecorParameterTexts_es-CIkkLQc2.js"),[],import.meta.url).then(k=>k.decorParameterTexts_es),it:()=>D(()=>import("./DecorParameterTexts_it-v7TBrnsr.js"),[],import.meta.url).then(k=>k.decorParameterTexts_it)});class B{static MAX_STOPS=12;static METRES_PER_DEGREE=111320;static SAME_TREE_M=1.5;static SAME_BUILDING_M=2.5;static SAME_STRUCTURE_M=5;static stops(e,t){if(e.length===0)return[];const i=e[0],s=Math.cos(i.lat*Math.PI/180),n=e.slice(1).map((p,m)=>Math.hypot((p.lat-e[m].lat)*B.METRES_PER_DEGREE,(p.lng-e[m].lng)*B.METRES_PER_DEGREE*s)),r=n.reduce((p,m)=>p+m,0),o=Math.max(t,r/(B.MAX_STOPS-1)),a=[i];let d=0,l=o;e.slice(1).forEach((p,m)=>{d+=n[m],d>=l&&(a.push(p),l=d+o)});const h=e[e.length-1],c=a[a.length-1];return Math.hypot((h.lat-c.lat)*B.METRES_PER_DEGREE,(h.lng-c.lng)*B.METRES_PER_DEGREE*s)>t/2&&a.length<B.MAX_STOPS&&a.push(h),a}static async fetch(e,t,i,s={}){if(t.length===0)throw new mi("no-coverage","No place to ask about");const n=t[0],r=Math.cos(n.lat*Math.PI/180),o=new Array(t.length).fill(void 0),a=[],d=Math.max(1,s.concurrency??3);let l=0;const h=async()=>{for(;l<t.length;){const m=l++;try{o[m]=await e.getSurroundings(t[m],i)}catch(f){a.push(f)}}};await Promise.all(Array.from({length:Math.min(d,t.length)},h));const c={trees:[],buildings:[],bridges:[],lines:[]};let u=!1;const p={};if(o.forEach((m,f)=>{if(!m)return;u=!0;const g=(t[f].lng-n.lng)*B.METRES_PER_DEGREE*r,b=(t[f].lat-n.lat)*B.METRES_PER_DEGREE,v=x=>x.map(S=>({...S,eastM:Math.round((S.eastM+g)*10)/10,northM:Math.round((S.northM+b)*10)/10})),E=v(m.trees).sort((x,S)=>Math.hypot(x.eastM-g,x.northM-b)-Math.hypot(S.eastM-g,S.northM-b)).slice(0,s.treesPerStop??m.trees.length);B.add(c.trees,E,(x,S)=>Math.hypot(x.eastM-S.eastM,x.northM-S.northM)<B.SAME_TREE_M),B.add(c.buildings,v(m.buildings),(x,S)=>Math.hypot(x.eastM-S.eastM,x.northM-S.northM)<B.SAME_BUILDING_M&&Math.abs(x.widthM-S.widthM)<1.5&&Math.abs(x.lengthM-S.lengthM)<1.5),B.add(c.bridges,v(m.bridges),(x,S)=>Math.hypot(x.eastM-S.eastM,x.northM-S.northM)<B.SAME_STRUCTURE_M),B.add(c.lines,v(m.lines),(x,S)=>Math.hypot(x.eastM-S.eastM,x.northM-S.northM)<B.SAME_STRUCTURE_M&&Math.abs(x.lengthM-S.lengthM)<5),B.addFurniture(c,m,v),m.incomplete&&(c.incomplete=!0);for(const x of["laser","photo","map","lamps"]){const S=m.dates?.[x];S&&(!p[x]||S>p[x])&&(p[x]=S)}}),!u)throw a.find(m=>!(m instanceof mi&&m.reason==="no-coverage"))??a[0];return Object.keys(p).length>0&&(c.dates=p),c}static later(e,t,i){if(!e.later||t.length===0)return;const s=t[0],n=Math.cos(s.lat*Math.PI/180),r=t.map(o=>e.later(o,i)??Promise.reject(new Error("Nothing comes late")));return Promise.allSettled(r).then(o=>{if(!o.some(d=>d.status==="fulfilled"))throw o[0].reason;const a={};return o.forEach((d,l)=>{if(d.status!=="fulfilled")return;const h=(t[l].lng-s.lng)*B.METRES_PER_DEGREE*n,c=(t[l].lat-s.lat)*B.METRES_PER_DEGREE,u=m=>m.map(f=>({...f,eastM:Math.round((f.eastM+h)*10)/10,northM:Math.round((f.northM+c)*10)/10}));B.addFurniture(a,d.value,u);const p=d.value.dates?.lamps;p&&(!a.dates?.lamps||p>a.dates.lamps)&&(a.dates={lamps:p})}),a})}static addFurniture(e,t,i){t.lamps&&B.add(e.lamps??=[],i(t.lamps),(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1);const s=(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1&&Math.abs((n.headingDeg-r.headingDeg+540)%360-180)<10;t.signals&&B.add(e.signals??=[],i(t.signals),s),t.crossings&&B.add(e.crossings??=[],i(t.crossings),s),t.signs&&B.add(e.signs??=[],i(t.signs),s),t.credits&&B.add(e.credits??=[],t.credits,(n,r)=>n.url===r.url)}static add(e,t,i){for(const s of t)e.some(n=>i(n,s))||e.push(s)}}class tt{static FLOOR_HEIGHT_M=3;static CROSSING_LENGTH_M=2.5;static of(e,t,i){const{kept:s}=i,n=g=>s.some(b=>b.kind===g),r={tree:n("tree"),building:n("building"),bridge:n("bridge"),wire:n("wire"),streetlight:n("streetlight"),trafficlight:n("trafficlight"),crossing:n("crossing"),roadsign:n("roadsign")},o=[...s,...i.others??[]],a=new Set(o.map(g=>g.id));let d=0;const l=()=>{let g;do g=`${e}-${++d}`;while(a.has(g));return a.add(g),g},h={tree:o.filter(g=>g.kind==="tree").length,building:o.filter(g=>g.kind==="building").length,bridge:o.filter(g=>g.kind==="bridge").length,wire:o.filter(g=>g.kind==="wire").length,streetlight:o.filter(g=>g.kind==="streetlight").length,trafficlight:o.filter(g=>g.kind==="trafficlight").length,crossing:o.filter(g=>g.kind==="crossing").length,roadsign:o.filter(g=>g.kind==="roadsign").length},c=new Set(o.map(g=>typeof g.title=="string"?g.title:"")),u=(g,b)=>{const v=b??`${i.kindName(g)} ${++h[g]}`;let E=v;for(let x=2;c.has(E);x++)E=`${v} (${x})`;return c.add(E),E},p=t.dates??{},m=(...g)=>{const b=g.filter(v=>v!==void 0).sort().at(-1);return b?{surveyedOn:b}:{}},f=[];if(!r.tree)for(const g of t.trees)f.push({id:l(),kind:"tree",title:u("tree",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.widthM,heightM:g.heightM},origin:e,...m(p.laser)});if(!r.building)for(const g of t.buildings)f.push({id:l(),kind:"building",title:u("building",g.name),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.lengthM,heightM:g.heightM},...g.style==="church"||g.style==="monument"?{}:{floors:g.floors??Math.max(1,Math.round((g.heightM-(g.roof?.riseM??0))/(g.facade?.storeyM??tt.FLOOR_HEIGHT_M)))},...g.roof?{roof:g.roof}:{},...g.facade?{facade:g.facade}:{},origin:e,...m(p.map,p.laser,g.roof?.color?p.photo:void 0)});if(!r.bridge)for(const g of t.bridges)f.push({id:l(),kind:"bridge",title:u("bridge",g.name?`${i.kindName("bridge")} (${g.name})`:void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,widthM:g.widthM,heightM:g.heightM},origin:e,...m(p.map,p.laser)});if(!r.wire)for(const g of t.lines)f.push({id:l(),kind:"wire",title:u("wire",`${i.kindName("wire")} (${g.voltage})`),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,heightM:g.heightM},wire:{strands:g.acrossM.map(b=>({heightM:g.heightM,acrossM:b})),poles:"both",poleHeightM:g.poleHeightM},origin:e,...m(p.map,p.laser)});if(!r.streetlight)for(const g of t.lamps??[]){const b={...g.colorTemperatureK?{colorTemperatureK:g.colorTemperatureK}:{},...g.lumens?{lumens:g.lumens}:{},...g.mount==="wall"?{mount:"wall"}:{},...g.supposed?{supposed:!0}:{}};f.push({id:l(),kind:"streetlight",title:u("streetlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,...g.heightM?{sizeM:{heightM:g.heightM}}:{},...Object.keys(b).length>0?{lamp:b}:{},origin:e,...m(p.lamps)})}if(!r.trafficlight)for(const g of t.signals??[])f.push({id:l(),kind:"trafficlight",title:u("trafficlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lights:g.for==="pedestrians"?Di.pedestrianLights(g.phase):Di.vehicleLights(g.phase),origin:e,...m(p.lamps)});if(!r.crossing)for(const g of t.crossings??[])f.push({id:l(),kind:"crossing",title:u("crossing",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sizeM:{widthM:g.widthM,lengthM:tt.CROSSING_LENGTH_M},origin:e,...m(p.lamps)});if(!r.roadsign)for(const g of t.signs??[])f.push({id:l(),kind:"roadsign",title:u("roadsign",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sign:{face:g.face,...g.code?{code:g.code}:{},...g.value?{value:g.value}:{}},origin:e,...m(p.lamps)});return{planted:f,handPlaced:Object.values(r).some(Boolean)}}}class ie{constructor(e,t,i,s,n={}){this.status=e,this.host=t,this.loadProvider=s,this.messages=i,this.debounceMs=n.debounceMs??ie.DEFAULT_DEBOUNCE_MS,this.radiusM=n.radiusM??ie.DEFAULT_RADIUS_M}static SAME_PLACE_M=25;static METRES_PER_DEGREE=111320;static DEFAULT_RADIUS_M=100;static DEFAULT_DEBOUNCE_MS=800;static TREES_PER_STOP=80;static WALK_LEAD_S=4;static WALK_LEAD_SHARE=.6;static SAME_BUILDING_M=3;static SAME_OBJECT_M=1.5;messages;debounceMs;radiusM;enabled=!0;surveyedFor;timer;token=0;surveyed="";furnitureSaid="";furnitureCredits=[];asked=[];lastStep;walkSpeedMps=0;setMessages(e){this.messages=e}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.cancel())}withdraw(){this.cancel(),this.withdrawPlanted(),this.say("")}placeLoaded(e,t){this.cancel(),this.surveyedFor=e!==void 0&&t!==void 0?{lat:e,lng:t}:void 0,this.say("")}radiusChanged(e,t,i){e!==this.radiusM&&(this.radiusM=e,!(!this.enabled||t===void 0||i===void 0)&&(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(t,i),this.debounceMs)))}placeChanged(e,t){!this.enabled||e===void 0||t===void 0||this.surveyedFor&&this.isSamePlace(this.surveyedFor,e,t)||(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(e,t),this.debounceMs))}walked(e,t,i,s=Date.now()){if(clearTimeout(this.timer),this.timer=void 0,this.surveyedFor={lat:e,lng:t},this.lastStep){const a=(s-this.lastStep.atMs)/1e3,d=this.metresBetween(this.lastStep,e,t);this.walkSpeedMps=a>0&&a<2?.5*this.walkSpeedMps+.5*d/a:0}if(this.lastStep={lat:e,lng:t,atMs:s},!this.enabled)return;const n=Math.min(this.radiusM,Math.max(this.radiusM*ie.WALK_LEAD_SHARE,this.walkSpeedMps*ie.WALK_LEAD_S)),r=i*Math.PI/180,o={lat:e+Math.cos(r)*n/ie.METRES_PER_DEGREE,lng:t+Math.sin(r)*n/(ie.METRES_PER_DEGREE*Math.cos(e*Math.PI/180))};this.asked.some(a=>this.metresBetween(a,o.lat,o.lng)<this.radiusM/2)||(this.asked.push(o),this.plantAhead(o))}async plantAhead(e){const t=this.token;try{const i=await this.loadProvider(e.lat,e.lng);if(!i||t!==this.token)return;const s=await i.getSurroundings(e,this.radiusM);if(t!==this.token)return;this.addAhead(i,this.fromCentre(s,e)),(s.incomplete?i.later?.(e,this.radiusM):void 0)?.then(r=>{t===this.token&&this.addAhead(i,this.fromCentre({trees:[],buildings:[],bridges:[],lines:[],...r},e))},()=>{})}catch{this.asked=this.asked.filter(i=>i!==e)}}addAhead(e,t){const i=this.host.decor(),s=i.filter(a=>a.origin===void 0),n=i.filter(a=>a.origin!==void 0),{planted:r}=tt.of(e.id,t,{kept:s,others:n,kindName:a=>this.host.kindName(a)}),o=r.filter(a=>!n.some(d=>ie.same(d,a)));o.length>0&&this.host.setDecor([...i,...o])}static same(e,t){if(e.kind!==t.kind)return!1;const i=Math.hypot(e.eastM-t.eastM,e.northM-t.northM);if(e.kind!=="building")return i<ie.SAME_OBJECT_M;const s=n=>[n.sizeM?.widthM??0,n.sizeM?.lengthM??0];return i<ie.SAME_BUILDING_M&&s(e).every((n,r)=>Math.abs(n-s(t)[r])<1.5)}fromCentre(e,t){const i=this.host.centre?.();if(!i)return e;const s=(t.lng-i.lng)*ie.METRES_PER_DEGREE*Math.cos(i.lat*Math.PI/180),n=(t.lat-i.lat)*ie.METRES_PER_DEGREE;if(Math.hypot(s,n)<.01)return e;const r=o=>o?.map(a=>({...a,eastM:Math.round((a.eastM+s)*100)/100,northM:Math.round((a.northM+n)*100)/100}));return{...e,...e.trees?{trees:r(e.trees)}:{},...e.buildings?{buildings:r(e.buildings)}:{},...e.bridges?{bridges:r(e.bridges)}:{},...e.lines?{lines:r(e.lines)}:{},...e.lamps?{lamps:r(e.lamps)}:{},...e.signals?{signals:r(e.signals)}:{},...e.crossings?{crossings:r(e.crossings)}:{},...e.signs?{signs:r(e.signs)}:{}}}metresBetween(e,t,i){const s=(e.lat-t)*ie.METRES_PER_DEGREE,n=(e.lng-i)*ie.METRES_PER_DEGREE*Math.cos(t*Math.PI/180);return Math.hypot(s,n)}async survey(e,t){const i=++this.token;this.surveyedFor={lat:e,lng:t},this.asked=[{lat:e,lng:t}],this.lastStep=void 0,this.host.busy(!0,this.messages.surveyBusy);try{const s=await this.loadProvider(e,t);if(i!==this.token)return;if(s===void 0){this.withdrawPlanted(),this.say("");return}this.say(this.messages.surveyBusy);const n=B.stops([{lat:e,lng:t},...this.host.track?.()??[]],this.radiusM),r=n.length>1?await B.fetch(s,n,this.radiusM,{treesPerStop:ie.TREES_PER_STOP}):await s.getSurroundings({lat:e,lng:t},this.radiusM);if(i!==this.token)return;this.plant(s,this.fromCentre(r,{lat:e,lng:t})),r.incomplete&&this.awaitLate(s,n,i)}catch(s){if(i!==this.token)return;s instanceof mi&&s.reason==="no-coverage"?(this.withdrawPlanted(),this.say("")):this.say(this.messages.surveyUnreachable)}finally{i===this.token&&this.host.busy(!1,"")}}cancel(){clearTimeout(this.timer),this.timer=void 0,this.token++,this.host.busy(!1,"")}withoutPlanted(){return this.host.decor().filter(e=>e.origin===void 0)}withdrawPlanted(){this.host.decor().some(e=>e.origin!==void 0)&&this.host.setDecor(this.withoutPlanted())}plant(e,t){const i=this.withoutPlanted(),{planted:s,handPlaced:n}=tt.of(e.id,t,{kept:i,kindName:d=>this.host.kindName(d)}),r=d=>s.filter(l=>l.kind===d).length;if((s.length>0||this.host.decor().length!==i.length)&&this.host.setDecor([...i,...s]),s.length===0){this.furnitureSaid="",this.surveyed=n?this.messages.surveyKept:this.messages.surveyNone.replace("{radius}",String(this.radiusM)),this.say(this.surveyed,t.incomplete?this.messages.surveyFurniturePending:"");return}this.host.cite({title:`${e.name}, survey of the surroundings`,url:e.creditUrl,publication:{publisher:e.name}});const o=this.messages.surveyDone.replace("{trees}",String(r("tree"))).replace("{buildings}",String(r("building"))).replace("{bridges}",String(r("bridge"))).replace("{lines}",String(r("wire"))).replace("{source}",e.name),a=this.datesText(t.dates);this.surveyed=[o,a,n?this.messages.surveyKept:""].filter(d=>d!=="").join(" "),this.citeCredits(t),this.furnitureCredits=t.credits??[],this.furnitureSaid=this.furnitureText(s,t),this.say(this.surveyed,[this.furnitureSaid,t.incomplete?this.messages.surveyFurniturePending:""].filter(d=>d!=="").join(" "))}citeCredits(e){for(const t of e.credits??[])this.host.cite({title:t.licence?`${t.name} (${t.licence})`:t.name,url:t.url,publication:{publisher:t.name}})}awaitLate(e,t,i){const s=t.length>1?B.later(e,t,this.radiusM):e.later?.(t[0],this.radiusM);if(!s){this.say(this.surveyed,"");return}this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurniturePending].filter(n=>n!=="").join(" ")),s.then(n=>{i===this.token&&this.plantLate(e,this.fromCentre(n,t[0]))},()=>{i===this.token&&this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurnitureUnavailable].filter(n=>n!=="").join(" "),{label:this.messages.surveyFurnitureRetry,run:()=>this.awaitLate(e,t,i)})})}plantLate(e,t){const i=this.host.decor(),{planted:s}=tt.of(e.id,{trees:[],buildings:[],bridges:[],lines:[],...t},{kept:i,kindName:r=>this.host.kindName(r)});s.length>0&&this.host.setDecor([...i,...s]),this.citeCredits(t);const n=i.filter(r=>r.origin===e.id).concat(s);this.furnitureSaid=this.furnitureText(n,{credits:[...this.furnitureCredits,...t.credits??[]]}),this.say(this.surveyed,this.furnitureSaid)}furnitureText(e,t){const i=o=>e.filter(a=>a.kind===o).length;if(!e.some(o=>o.kind==="streetlight"||o.kind==="trafficlight"||o.kind==="crossing"||o.kind==="roadsign"))return"";const s=o=>o.of==="lamps"?i("streetlight")>0:o.of==="signals"?i("trafficlight")>0:!0,r=[...new Set((t.credits??[]).filter(s).map(o=>o.name))].join(" + ")||"OpenStreetMap";return this.messages.surveyFurnitureDone.replace("{source}",r).replace("{lamps}",String(i("streetlight"))).replace("{signals}",String(i("trafficlight"))).replace("{crossings}",String(i("crossing"))).replace("{signs}",String(i("roadsign")))}datesText(e){if(!e)return"";const t=[["laser",this.messages.surveyLaserLabel],["photo",this.messages.surveyPhotoLabel],["map",this.messages.surveyMapLabel],["lamps",this.messages.surveyLampsLabel]].filter(([i])=>e[i]!==void 0).map(([i,s])=>`${s} ${e[i]}`);return t.length>0?this.messages.surveyDated.replace("{dates}",t.join(", ")):""}isSamePlace(e,t,i){return this.metresBetween(e,t,i)<ie.SAME_PLACE_M}say(e,t="",i){if(this.status.textContent=[e,t].filter(n=>n!=="").join(" "),!i)return;const s=this.status.ownerDocument.createElement("button");s.type="button",s.className="scenery-retry",s.textContent=i.label,s.addEventListener("click",i.run),this.status.append(" ",s)}}class zt{static newestSurvey(e){return e.filter(t=>t.origin!==void 0).map(t=>t.surveyedOn).filter(t=>t!==void 0).sort().at(-1)}static latestObservationDay(e){if(!e?.year)return;const t=e.month??12,i=e.day??new Date(Date.UTC(e.year,t,0)).getUTCDate();return`${String(e.year).padStart(4,"0")}-${String(t).padStart(2,"0")}-${String(i).padStart(2,"0")}`}static anachronism(e,t){const i=zt.newestSurvey(e),s=zt.latestObservationDay(t);return i&&s&&i>s?{survey:i,observation:s}:void 0}}class me{static number(e,t,i,s,n,r,o={}){return{type:"number",key:e,label:t,min:i,max:s,step:n,unit:r,required:!0,...o}}static natural(e){return(t,i)=>i?.natural?.[e]}static BASE={kind:"decor-base",title:"object",parameters:[{type:"said",key:"title",required:!0,label:"name"},{type:"position",key:"eastM",secondKey:"northM",saidKey:"saidPosition",native:"local",step:.5,label:"position"},me.number("altitudeM","altitude",-1e3,3e4,1,"m"),me.number("headingDeg","heading",0,360,1,"°"),{type:"colour",key:"color",label:"colour",fallback:"#808080",visibleWhen:(e,t)=>t?.traits.color===!0},me.number("sizeM.widthM","width",.1,1e3,.1,"m",{required:!1,effective:me.natural("widthM")}),me.number("sizeM.lengthM","length",.1,1e3,.1,"m",{required:!1,effective:me.natural("lengthM")}),me.number("sizeM.heightM","height",.1,1e3,.1,"m",{required:!1,effective:me.natural("heightM")}),{type:"choice",key:"model.id",label:"n3DModel",choices:[],empty:"noModelBuiltInShape",optionsOf:(e,t)=>[...t?.models??[]],effective:(e,t)=>t?.defaultModelId}]};static HEADLIGHT_LABELS={off:"off",position:"positionLights",dipped:"dippedBeam",main:"mainBeam",fog:"fogLamps"};static STATE={kind:"decor-state",title:"state",parameters:[{type:"boolean",key:"lit",required:!0,label:"lit",visibleWhen:(e,t)=>t?.traits.lit===!0&&t?.traits.headlights!==!0},{type:"choice",key:"headlights",required:!0,label:"headlights",choices:$n.MODES.map(e=>({value:e,label:me.HEADLIGHT_LABELS[e]})),visibleWhen:(e,t)=>t?.traits.headlights===!0},{type:"choice",key:"lightRig",label:"lights",choices:[],empty:"noLights",optionsOf:(e,t)=>(t?.lightRigs??[]).map(i=>({value:i.value,label:i.label})),visibleWhen:(e,t)=>t?.traits.lights===!0},{type:"choice",key:"observerSide",label:"witnessLocation",choices:[],empty:"notPresent",optionsOf:(e,t)=>[...t?.seats??[]],visibleWhen:(e,t)=>t?.traits.observerSide===!0}]};static seatsFor(e){return Hn(e).map(t=>({value:t,label:Ss.sideLabel(t)}))}}class ce extends Error{constructor(e,t,i){const s=e==="rejected"&&typeof t=="string"?t:void 0,n=e==="rejected"?i:t;super(s??e,n===void 0?void 0:{cause:n}),this.kind=e,this.name="NarrativeError",this.detail=s}detail}class Ut{static KNOWN_TAGS=["landing","trace","aerial observation","project sign","paralysis","contact","occupants","close encounter","photograph","radar","electromagnetic effect"];static RULES=[{draft:`Sizes are ANGULAR, in degrees, and never metric — the format stores no physical size, because an
233
233
  observer perceives an angle and a size only follows from a distance nobody measured. Convert the
234
234
  comparisons an account gives: the full Moon and the Sun are both about 0.5 degrees across, a
235
235
  thumbnail at arm's length about 1.5, a fist about 10. Where the account gives no comparison, work
@@ -330,7 +330,7 @@ ${C.titles("::before","[data-chosen]")} { display: none; }
330
330
  camera inside a wall than a data fault. Then list, in your report, the questions whose answers would
331
331
  replace each "assumed" value (height at the start, timed duration, which way the head turned, standing
332
332
  point, what was behind), because that list is what an investigator can act on.`}];static text(e){return Ut.RULES.map(t=>t[e]).filter(t=>t!==void 0).map((t,i)=>`${i+1}. ${t.replace("{tags}",Ut.KNOWN_TAGS.join(", "))}`).join(`
333
- `)}}class _t{static of(e){const{recording:t}=hi.strip(e),{timeline:i,...s}=t,n=(i?.keyframes??[]).map(o=>_t.keyframe(o)),r=Object.entries(s).filter(([o,a])=>o!=="version"&&a!==void 0);if(!(r.length===0&&n.every(o=>o.shapes.length===0)))return{...Object.fromEntries(r),...n.length>0?{timeline:{keyframes:n}}:{}}}static keyframe(e){return{t:e.t,shapes:e.shapes.map(t=>_t.shape(t.sourceId,t.shape))}}static shape(e,t){const i=t??{},s=i.angular,n=i.aim;return{sourceId:e,kind:i.kind??"oval",...i.title===void 0?{}:{title:i.title},...s?.widthDeg===void 0||s.heightDeg===void 0?{}:{angular:{widthDeg:s.widthDeg,heightDeg:s.heightDeg}},...n?.azimuthDeg===void 0||n.altitudeDeg===void 0?{}:{aim:{azimuthDeg:n.azimuthDeg,altitudeDeg:n.altitudeDeg}}}}}const nr=je.catalog({en:()=>L(()=>import("./ClaudeNarrativeTexts_en-CBLJZ7b6.js"),[],import.meta.url).then(E=>E.claudeNarrativeTexts_en),fr:()=>L(()=>import("./ClaudeNarrativeTexts_fr-DiKzTF9T.js"),[],import.meta.url).then(E=>E.claudeNarrativeTexts_fr),es:()=>L(()=>import("./ClaudeNarrativeTexts_es-BDV0GimU.js"),[],import.meta.url).then(E=>E.claudeNarrativeTexts_es),it:()=>L(()=>import("./ClaudeNarrativeTexts_it-DwxjRDVG.js"),[],import.meta.url).then(E=>E.claudeNarrativeTexts_it)}),os={name:"draft_recording",description:"Record what the account states, what justifies each value, and what it leaves out.",input_schema:{type:"object",properties:{recording:{type:"object",description:"The recording, in the format given above. Partial: only the fields the account actually states."},claims:{type:"array",description:"One entry per value in `recording`. EVERY value needs one: a value with no claim is a value nobody can check.",items:{type:"object",properties:{path:{type:"string",description:'Where the value sits in `recording`, dot-joined, array indices as steps: "time", "place.locations.0.lat", "timeline.keyframes.1.shapes.0.shape.angular.widthDeg".'},basis:{type:"string",enum:["stated","derived","assumed"],description:'"stated": the observer said it. "derived": worked out from what they said plus something checkable. "assumed": chosen so the reconstruction has a value at all, on nothing they said.'},rationale:{type:"string",description:`For "stated", the account's own words, copied verbatim, never a paraphrase. For "derived", the working, with the numbers in it. For "assumed", what the guess was chosen for and how wrong it could be.`}},required:["path","basis","rationale"]}},gaps:{type:"array",description:"What nothing could settle, not even a guess worth making — one short sentence each, in the reader's language. Usually empty.",items:{type:"string"}}},required:["recording","claims","gaps"]}},rr=`You are reading an observer's account of an aerial sighting and reconstructing it in the
333
+ `)}}class _t{static of(e){const{recording:t}=hi.strip(e),{timeline:i,...s}=t,n=(i?.keyframes??[]).map(o=>_t.keyframe(o)),r=Object.entries(s).filter(([o,a])=>o!=="version"&&a!==void 0);if(!(r.length===0&&n.every(o=>o.shapes.length===0)))return{...Object.fromEntries(r),...n.length>0?{timeline:{keyframes:n}}:{}}}static keyframe(e){return{t:e.t,shapes:e.shapes.map(t=>_t.shape(t.sourceId,t.shape))}}static shape(e,t){const i=t??{},s=i.angular,n=i.aim;return{sourceId:e,kind:i.kind??"oval",...i.title===void 0?{}:{title:i.title},...s?.widthDeg===void 0||s.heightDeg===void 0?{}:{angular:{widthDeg:s.widthDeg,heightDeg:s.heightDeg}},...n?.azimuthDeg===void 0||n.altitudeDeg===void 0?{}:{aim:{azimuthDeg:n.azimuthDeg,altitudeDeg:n.altitudeDeg}}}}}const nr=Ge.catalog({en:()=>D(()=>import("./ClaudeNarrativeTexts_en-CBLJZ7b6.js"),[],import.meta.url).then(k=>k.claudeNarrativeTexts_en),fr:()=>D(()=>import("./ClaudeNarrativeTexts_fr-DiKzTF9T.js"),[],import.meta.url).then(k=>k.claudeNarrativeTexts_fr),es:()=>D(()=>import("./ClaudeNarrativeTexts_es-BDV0GimU.js"),[],import.meta.url).then(k=>k.claudeNarrativeTexts_es),it:()=>D(()=>import("./ClaudeNarrativeTexts_it-DwxjRDVG.js"),[],import.meta.url).then(k=>k.claudeNarrativeTexts_it)}),os={name:"draft_recording",description:"Record what the account states, what justifies each value, and what it leaves out.",input_schema:{type:"object",properties:{recording:{type:"object",description:"The recording, in the format given above. Partial: only the fields the account actually states."},claims:{type:"array",description:"One entry per value in `recording`. EVERY value needs one: a value with no claim is a value nobody can check.",items:{type:"object",properties:{path:{type:"string",description:'Where the value sits in `recording`, dot-joined, array indices as steps: "time", "place.locations.0.lat", "timeline.keyframes.1.shapes.0.shape.angular.widthDeg".'},basis:{type:"string",enum:["stated","derived","assumed"],description:'"stated": the observer said it. "derived": worked out from what they said plus something checkable. "assumed": chosen so the reconstruction has a value at all, on nothing they said.'},rationale:{type:"string",description:`For "stated", the account's own words, copied verbatim, never a paraphrase. For "derived", the working, with the numbers in it. For "assumed", what the guess was chosen for and how wrong it could be.`}},required:["path","basis","rationale"]}},gaps:{type:"array",description:"What nothing could settle, not even a guess worth making — one short sentence each, in the reader's language. Usually empty.",items:{type:"string"}}},required:["recording","claims","gaps"]}},rr=`You are reading an observer's account of an aerial sighting and reconstructing it in the
334
334
  recording format of UFO@home, a tool that replays what an observer reported seeing, from where they
335
335
  stood, under the real sky of that moment.
336
336
 
@@ -357,7 +357,7 @@ padding it with plumbing is how it stops being read.
357
357
 
358
358
  Then:
359
359
 
360
- ${Ut.text("draft")}`;class Ne{static DEFAULT_MODEL="claude-opus-5-5";get settings(){return this.localizedSettings}localizedSettings=[];async localize(e){this.localizedSettings=Ne.settingsIn(await nr.load(e))}static settingsIn(e){return[{id:"key",kind:"secret",label:e.keyLabel,required:!0,remembered:"credential",suspect:t=>t.startsWith("sk-ant-")?void 0:e.keySuspect},{id:"workspace",kind:"text",label:e.workspaceLabel,placeholder:e.workspacePlaceholder,hint:e.workspaceHint,remembered:"credential"},{id:"model",kind:"choice",label:e.modelLabel,choices:[{value:Ne.DEFAULT_MODEL,label:"Claude Opus 5.5"},{value:"claude-fable-5-1",label:e.fableChoice},{value:"claude-sonnet-5-5",label:e.sonnetChoice},{value:"claude-haiku-4-5",label:e.haikuChoice}],remembered:"preference"}]}client;clientFor_;format;async draft(e,t){const i=await this.clientFor(e.settings.key,e.settings.workspace),s=this.format??=JSON.stringify((await L(async()=>{const{default:o}=await import("./sightingSchema-CgwoRMl-.js");return{default:o}},[],import.meta.url)).default),n=i.messages.stream({model:e.settings.model||Ne.DEFAULT_MODEL,max_tokens:16e3,system:[{type:"text",text:rr},{type:"text",text:`The recording format, every key with what its own declaration says about it:
360
+ ${Ut.text("draft")}`;class Ne{static DEFAULT_MODEL="claude-opus-5-5";get settings(){return this.localizedSettings}localizedSettings=[];async localize(e){this.localizedSettings=Ne.settingsIn(await nr.load(e))}static settingsIn(e){return[{id:"key",kind:"secret",label:e.keyLabel,required:!0,remembered:"credential",suspect:t=>t.startsWith("sk-ant-")?void 0:e.keySuspect},{id:"workspace",kind:"text",label:e.workspaceLabel,placeholder:e.workspacePlaceholder,hint:e.workspaceHint,remembered:"credential"},{id:"model",kind:"choice",label:e.modelLabel,choices:[{value:Ne.DEFAULT_MODEL,label:"Claude Opus 5.5"},{value:"claude-fable-5-1",label:e.fableChoice},{value:"claude-sonnet-5-5",label:e.sonnetChoice},{value:"claude-haiku-4-5",label:e.haikuChoice}],remembered:"preference"}]}client;clientFor_;format;async draft(e,t){const i=await this.clientFor(e.settings.key,e.settings.workspace),s=this.format??=JSON.stringify((await D(async()=>{const{default:o}=await import("./sightingSchema-CgwoRMl-.js");return{default:o}},[],import.meta.url)).default),n=i.messages.stream({model:e.settings.model||Ne.DEFAULT_MODEL,max_tokens:16e3,system:[{type:"text",text:rr},{type:"text",text:`The recording format, every key with what its own declaration says about it:
361
361
 
362
362
  ${s}`,cache_control:{type:"ephemeral"}}],messages:this.messages(e),tools:[os],tool_choice:{type:"auto",disable_parallel_tool_use:!0}}),r=()=>n.controller.abort();t?.aborted&&r(),t?.addEventListener("abort",r,{once:!0});try{return Ne.read(await n.finalMessage())}catch(o){throw await Ne.diagnose(o,t)}finally{t?.removeEventListener("abort",r)}}messages(e){return[{role:"user",content:[...(e.images??[]).map(t=>Ne.imageBlock(t)),{type:"text",text:this.ask(e)}]}]}ask(e){const t=[];e.language&&t.push(`Write the gaps in ${e.language}.`);const i=e.current?_t.of(e.current):void 0;return i&&t.push(`What the editor already holds, shapes reduced to their stated angle and direction. Do not restate a value here that the account does not itself state:
363
363
 
@@ -365,7 +365,7 @@ ${JSON.stringify(i)}`),t.push(`The account:
365
365
 
366
366
  ${e.ask}`,"Answer by calling draft_recording."),t.join(`
367
367
 
368
- `)}static imageBlock(e){return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}}}async clientFor(e,t){if(!e)throw new ce("credential");const i=`${e}\0${t??""}`;if(this.client&&this.clientFor_===i)return this.client;const{default:s}=await L(async()=>{const{default:n}=await import("./index-DqGmxMZD.js").then(r=>r.i);return{default:n}},__vite__mapDeps([0,1]),import.meta.url);return this.client=new s({apiKey:e,...t?{defaultHeaders:{"anthropic-workspace-id":t}}:{},dangerouslyAllowBrowser:!0,maxRetries:1}),this.clientFor_=i,this.client}static read(e){if(e.stop_reason==="refusal")throw new ce("refused");const t=e.content.find(s=>s.type==="tool_use"&&s.name===os.name);if(!t||t.type!=="tool_use")throw new ce("malformed");const i=t.input;if(typeof i?.recording!="object"||i.recording===null||Array.isArray(i.recording))throw new ce("malformed");return{recording:i.recording,claims:Array.isArray(i.claims)?i.claims.flatMap(s=>{const{path:n,basis:r,rationale:o}=s??{};return typeof n!="string"||typeof o!="string"?[]:[{path:n,basis:r==="derived"||r==="assumed"?r:"stated",rationale:o}]}):[],gaps:Array.isArray(i.gaps)?i.gaps.filter(s=>typeof s=="string"):[]}}static async diagnose(e,t){if(e instanceof ce)return e;if(t?.aborted)return new ce("cancelled",e);const{default:i}=await L(async()=>{const{default:s}=await import("./index-DqGmxMZD.js").then(n=>n.i);return{default:s}},__vite__mapDeps([0,1]),import.meta.url);return e instanceof i.AuthenticationError||e instanceof i.PermissionDeniedError?new ce("credential",e):e instanceof i.RateLimitError?new ce("rate-limited",e):e instanceof i.BadRequestError||e instanceof i.NotFoundError?new ce("rejected",e.message,e):e instanceof i.APIConnectionError?new ce("unreachable",e):new ce("malformed",e)}}const yt=he.point("narrative").provide(he.BUILT_IN,[{id:"claude",name:"Claude",credit:"Anthropic",creditUrl:"https://www.anthropic.com/legal/consumer-terms",create:()=>new Ne}]);class Ee{static stated(e){return Ee.statedIn(e,[])}static apply(e,t,i){const s=structuredClone(e);for(const n of i){const r=n.split("."),o=Ee.read(t,r);o!==void 0&&Ee.write(s,r,structuredClone(o))}return s}static statedIn(e,t){const i=[];for(const[s,n]of Object.entries(e)){if(n===void 0)continue;const r=[...t,s];Ee.isPlainObject(n)?i.push(...Ee.statedIn(n,r)):i.push(r.join("."))}return i}static isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static read(e,t){let i=e;for(const s of t){if(!Ee.isPlainObject(i))return;i=i[s]}return i}static write(e,t,i){let s=e;for(const n of t.slice(0,-1)){const r=s[n];Ee.isPlainObject(r)||(s[n]={}),s=s[n]}s[t[t.length-1]]=i}}const or={x:ge.CANVAS_WIDTH_PX/2,y:ge.CANVAS_HEIGHT_PX/2,width:1,height:1};class Ht{static loadable(e){const t=e.decor?{decor:e.decor.map((s,n)=>Ht.decor(s,n))}:{},i=e.timeline?.keyframes;return i?{...e,...t,timeline:{...e.timeline,keyframes:i.map(s=>({t:s.t??0,shapes:(s.shapes??[]).map(n=>({sourceId:n.sourceId,shape:Ht.shape(n.shape)}))}))}}:{...e,...t}}static decor(e,t){const i=e.kind??"vehicle";return{...Wn(i)?{windows:Os(i)}:{},...i==="building"?{floors:Cs}:{},...e,id:e.id??`decor-${t+1}`,kind:i,eastM:e.eastM??0,northM:e.northM??0}}static shape(e){const t=e?.kind==="polygon"?"polygon":"oval";return{...t==="polygon"?{points:[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}]}:{},...e,kind:t,bounds:{...or},color:typeof e?.color=="string"?e.color:"#e8e6df",angle:0,transparency:0,haloScale:0,selected:!1}}}class De{static FREE='input:not([type]), input[type="text"], input[type="url"], input[type="search"], input[type="email"], input[type="tel"], input[type="password"], textarea';static FAMILY="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";static PICKER="select:not([multiple]):not([size]), .rr0-select";static CSS=`
368
+ `)}static imageBlock(e){return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}}}async clientFor(e,t){if(!e)throw new ce("credential");const i=`${e}\0${t??""}`;if(this.client&&this.clientFor_===i)return this.client;const{default:s}=await D(async()=>{const{default:n}=await import("./index-DqGmxMZD.js").then(r=>r.i);return{default:n}},__vite__mapDeps([0,1]),import.meta.url);return this.client=new s({apiKey:e,...t?{defaultHeaders:{"anthropic-workspace-id":t}}:{},dangerouslyAllowBrowser:!0,maxRetries:1}),this.clientFor_=i,this.client}static read(e){if(e.stop_reason==="refusal")throw new ce("refused");const t=e.content.find(s=>s.type==="tool_use"&&s.name===os.name);if(!t||t.type!=="tool_use")throw new ce("malformed");const i=t.input;if(typeof i?.recording!="object"||i.recording===null||Array.isArray(i.recording))throw new ce("malformed");return{recording:i.recording,claims:Array.isArray(i.claims)?i.claims.flatMap(s=>{const{path:n,basis:r,rationale:o}=s??{};return typeof n!="string"||typeof o!="string"?[]:[{path:n,basis:r==="derived"||r==="assumed"?r:"stated",rationale:o}]}):[],gaps:Array.isArray(i.gaps)?i.gaps.filter(s=>typeof s=="string"):[]}}static async diagnose(e,t){if(e instanceof ce)return e;if(t?.aborted)return new ce("cancelled",e);const{default:i}=await D(async()=>{const{default:s}=await import("./index-DqGmxMZD.js").then(n=>n.i);return{default:s}},__vite__mapDeps([0,1]),import.meta.url);return e instanceof i.AuthenticationError||e instanceof i.PermissionDeniedError?new ce("credential",e):e instanceof i.RateLimitError?new ce("rate-limited",e):e instanceof i.BadRequestError||e instanceof i.NotFoundError?new ce("rejected",e.message,e):e instanceof i.APIConnectionError?new ce("unreachable",e):new ce("malformed",e)}}const yt=he.point("narrative").provide(he.BUILT_IN,[{id:"claude",name:"Claude",credit:"Anthropic",creditUrl:"https://www.anthropic.com/legal/consumer-terms",create:()=>new Ne}]);class Ee{static stated(e){return Ee.statedIn(e,[])}static apply(e,t,i){const s=structuredClone(e);for(const n of i){const r=n.split("."),o=Ee.read(t,r);o!==void 0&&Ee.write(s,r,structuredClone(o))}return s}static statedIn(e,t){const i=[];for(const[s,n]of Object.entries(e)){if(n===void 0)continue;const r=[...t,s];Ee.isPlainObject(n)?i.push(...Ee.statedIn(n,r)):i.push(r.join("."))}return i}static isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static read(e,t){let i=e;for(const s of t){if(!Ee.isPlainObject(i))return;i=i[s]}return i}static write(e,t,i){let s=e;for(const n of t.slice(0,-1)){const r=s[n];Ee.isPlainObject(r)||(s[n]={}),s=s[n]}s[t[t.length-1]]=i}}const or={x:ge.CANVAS_WIDTH_PX/2,y:ge.CANVAS_HEIGHT_PX/2,width:1,height:1};class $t{static loadable(e){const t=e.decor?{decor:e.decor.map((s,n)=>$t.decor(s,n))}:{},i=e.timeline?.keyframes;return i?{...e,...t,timeline:{...e.timeline,keyframes:i.map(s=>({t:s.t??0,shapes:(s.shapes??[]).map(n=>({sourceId:n.sourceId,shape:$t.shape(n.shape)}))}))}}:{...e,...t}}static decor(e,t){const i=e.kind??"vehicle";return{...Wn(i)?{windows:Os(i)}:{},...i==="building"?{floors:Cs}:{},...e,id:e.id??`decor-${t+1}`,kind:i,eastM:e.eastM??0,northM:e.northM??0}}static shape(e){const t=e?.kind==="polygon"?"polygon":"oval";return{...t==="polygon"?{points:[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}]}:{},...e,kind:t,bounds:{...or},color:typeof e?.color=="string"?e.color:"#e8e6df",angle:0,transparency:0,haloScale:0,selected:!1}}}class De{static FREE='input:not([type]), input[type="text"], input[type="url"], input[type="search"], input[type="email"], input[type="tel"], input[type="password"], textarea';static FAMILY="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";static PICKER="select:not([multiple]):not([size]), .rr0-select";static CSS=`
369
369
  /* Every field the same size; what is typed freely in a monospaced font (see InputFont). */
370
370
  input, textarea, select, .rr0-select { font-size: var(--rr0-input-font-size, 13px); }
371
371
  :is(${De.FREE}) { font-family: ${De.FAMILY}; }
@@ -428,20 +428,20 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
428
428
  <!-- What Alt does while the view is turned by a drag (see SightingEditorElement.showViewDragHint). -->
429
429
  <p id="view-drag-hint" class="view-drag-hint" role="status" hidden></p>
430
430
  <div class="toolbar playback-row">
431
- <button id="play-pause" type="button" class="icon-btn" data-icon="▶">${M.PLAY}</button>
431
+ <button id="play-pause" type="button" class="icon-btn" data-icon="▶">${L.PLAY}</button>
432
432
  <!-- The sound: the player's own button is hidden here with its controls (see SightingEditorElement.syncSoundControls), and stands where the player has it: between play and the time. -->
433
433
  <div class="editor-volume">
434
434
  <button id="editor-mute" type="button" class="icon-btn" aria-pressed="false"></button>
435
435
  <input id="editor-volume" type="range" min="0" max="1" step="0.05" value="1"/>
436
436
  </div>
437
437
  <span id="time-start" class="time-label">0:00</span>
438
- <button id="previous-mark" type="button" class="icon-btn">${M.PREVIOUS_MARK}</button>
438
+ <button id="previous-mark" type="button" class="icon-btn">${L.PREVIOUS_MARK}</button>
439
439
  <!-- The keyframes of what the open group edits, and the named moments — see TimelineMarks. -->
440
440
  <div class="seek-track">
441
441
  <input id="seek" type="range" min="0" max="0" value="0" step="1"/>
442
442
  <div id="timeline-marks" class="timeline-marks"></div>
443
443
  </div>
444
- <button id="next-mark" type="button" class="icon-btn">${M.NEXT_MARK}</button>
444
+ <button id="next-mark" type="button" class="icon-btn">${L.NEXT_MARK}</button>
445
445
  <span id="time-end" class="time-label">0:00</span>
446
446
  <!-- Lays the tracks out after the sections' chips (see TimelineTracks): the timeline then leaves the picture and stays in view. -->
447
447
  <button id="toggle-tracks" type="button" class="icon-btn" aria-expanded="false" aria-controls="timeline-tracks"><svg class="icon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/></svg></button>
@@ -450,16 +450,16 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
450
450
  <!-- Drags the scene taller or shorter, which gives the form under it the height it leaves (see SightingEditorElement.resizeScene). -->
451
451
  <div id="scene-resize" class="scene-resize" role="separator" aria-orientation="horizontal" tabindex="0"></div>
452
452
  <nav id="group-tabs" class="section-chips">
453
- <button class="group-tab" type="button" aria-controls="group-observation" aria-expanded="false">${M.SUMMARY}<span id="label-observation-group"></span></button>
454
- <button class="group-tab" type="button" aria-controls="group-observer" aria-expanded="false">${M.WITNESS}<span id="label-observer-group"></span></button>
455
- <button class="group-tab" type="button" aria-controls="group-location" aria-expanded="false">${M.LOCATION}<span id="label-location-group"></span></button>
456
- <button class="group-tab" type="button" aria-controls="group-temporal" aria-expanded="false">${M.DATE}<span id="label-temporal-group"></span></button>
457
- <button class="group-tab" type="button" aria-controls="group-decor" aria-expanded="false">${M.ENVIRONMENT}<span id="label-decor-group"></span></button>
458
- <button class="group-tab" type="button" aria-controls="group-weather" aria-expanded="false">${M.SKY}<span id="label-weather-group"></span></button>
459
- <button class="group-tab" type="button" aria-controls="group-shape" aria-expanded="false">${M.PHENOMENON}<span id="label-shape-group"></span></button>
460
- <button class="group-tab" type="button" aria-controls="group-sound" aria-expanded="false">${M.SOUND}<span id="label-sound-group"></span></button>
461
- <button class="group-tab" type="button" aria-controls="group-reference" aria-expanded="false">${M.PICTURES}<span id="label-reference-group"></span></button>
462
- <button class="group-tab" type="button" aria-controls="group-file" aria-expanded="false">${M.FILES}<span id="label-file-group"></span></button>
453
+ <button class="group-tab" type="button" aria-controls="group-observation" aria-expanded="false">${L.SUMMARY}<span id="label-observation-group"></span></button>
454
+ <button class="group-tab" type="button" aria-controls="group-observer" aria-expanded="false">${L.WITNESS}<span id="label-observer-group"></span></button>
455
+ <button class="group-tab" type="button" aria-controls="group-location" aria-expanded="false">${L.LOCATION}<span id="label-location-group"></span></button>
456
+ <button class="group-tab" type="button" aria-controls="group-temporal" aria-expanded="false">${L.DATE}<span id="label-temporal-group"></span></button>
457
+ <button class="group-tab" type="button" aria-controls="group-decor" aria-expanded="false">${L.ENVIRONMENT}<span id="label-decor-group"></span></button>
458
+ <button class="group-tab" type="button" aria-controls="group-weather" aria-expanded="false">${L.SKY}<span id="label-weather-group"></span></button>
459
+ <button class="group-tab" type="button" aria-controls="group-shape" aria-expanded="false">${L.PHENOMENON}<span id="label-shape-group"></span></button>
460
+ <button class="group-tab" type="button" aria-controls="group-sound" aria-expanded="false">${L.SOUND}<span id="label-sound-group"></span></button>
461
+ <button class="group-tab" type="button" aria-controls="group-reference" aria-expanded="false">${L.PICTURES}<span id="label-reference-group"></span></button>
462
+ <button class="group-tab" type="button" aria-controls="group-file" aria-expanded="false">${L.FILES}<span id="label-file-group"></span></button>
463
463
  <!-- What an element that holds this editor puts after the last tab (see CaseEditorElement): a mark of its own, which takes its room whether it shows or not. -->
464
464
  <slot name="tab-status"></slot>
465
465
  </nav>
@@ -762,10 +762,10 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
762
762
  <label class="element-list-picker"><select id="milestone" aria-labelledby="label-milestones"></select></label>
763
763
  <!-- A select says nothing when the moment already shown is picked again, which is the one to go
764
764
  back to after playing on past it: this goes there whatever the list shows. -->
765
- <button id="go-to-milestone" type="button" class="icon-btn">${M.TARGET}</button>
766
- <button id="delete-milestone" type="button" class="icon-btn">${M.TRASH}</button>
765
+ <button id="go-to-milestone" type="button" class="icon-btn">${L.TARGET}</button>
766
+ <button id="delete-milestone" type="button" class="icon-btn">${L.TRASH}</button>
767
767
  <span id="milestone-empty" class="element-list-empty"></span>
768
- <button id="add-milestone" type="button" class="icon-btn element-list-add">${M.PLUS}</button>
768
+ <button id="add-milestone" type="button" class="icon-btn element-list-add">${L.PLUS}</button>
769
769
  </div>
770
770
  <div class="element-list-body" id="milestone-item">
771
771
  <label><span id="label-milestone-label"></span> <input id="milestoneLabel" type="text" size="4"/></label>
@@ -887,11 +887,11 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
887
887
  <output id="sky-candidates" class="weather-source" for="lat lng obs-time"></output>
888
888
  <!-- A shooting star for the meteor and a comet for the comet. The meteor button used to carry
889
889
  the comet glyph, which was only ever unambiguous while there was nothing else up there. -->
890
- <button id="show-meteor" type="button" class="icon-btn" disabled>${M.METEOR}</button>
891
- <button id="show-comet" type="button" class="icon-btn" disabled>${M.COMET}</button>
892
- <button id="show-nova" type="button" class="icon-btn" disabled>${M.STAR}</button>
893
- <button id="show-satellite" type="button" class="icon-btn" disabled>${M.SATELLITE}</button>
894
- <button id="show-fireball" type="button" class="icon-btn" disabled>${M.FIREBALL}</button>
890
+ <button id="show-meteor" type="button" class="icon-btn" disabled>${L.METEOR}</button>
891
+ <button id="show-comet" type="button" class="icon-btn" disabled>${L.COMET}</button>
892
+ <button id="show-nova" type="button" class="icon-btn" disabled>${L.STAR}</button>
893
+ <button id="show-satellite" type="button" class="icon-btn" disabled>${L.SATELLITE}</button>
894
+ <button id="show-fireball" type="button" class="icon-btn" disabled>${L.FIREBALL}</button>
895
895
  </div>
896
896
  <!-- The weather in three parts — what falls (first, and open on arrival: the user's own order), the
897
897
  clouds, and what blows — as a strip of handles
@@ -996,9 +996,9 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
996
996
  under it, the frame of the picked picture. -->
997
997
  <div class="element-list-row" id="reference-row">
998
998
  <label class="element-list-picker"><select id="reference"></select></label>
999
- <button id="delete-reference" type="button" class="icon-btn">${M.TRASH}</button>
999
+ <button id="delete-reference" type="button" class="icon-btn">${L.TRASH}</button>
1000
1000
  <span id="reference-empty" class="element-list-empty"></span>
1001
- <button id="add-reference" type="button" class="icon-btn element-list-add">${M.PLUS}</button>
1001
+ <button id="add-reference" type="button" class="icon-btn element-list-add">${L.PLUS}</button>
1002
1002
  </div>
1003
1003
  <!-- Street-level pictures somebody took near the observer's spot — see PanoramaxPictures. Each
1004
1004
  comes with where it was taken from and which way it looked, a registration already made. -->
@@ -1050,9 +1050,9 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
1050
1050
  <h3 class="section-title"><span id="label-reference-landmarks"></span></h3>
1051
1051
  <div class="element-list-row" id="reference-landmark-row">
1052
1052
  <label class="element-list-picker"><select id="reference-landmarks" aria-labelledby="label-reference-landmarks"></select></label>
1053
- <button id="delete-reference-landmark" type="button" class="icon-btn">${M.TRASH}</button>
1053
+ <button id="delete-reference-landmark" type="button" class="icon-btn">${L.TRASH}</button>
1054
1054
  <span id="reference-landmark-empty" class="element-list-empty"></span>
1055
- <button id="add-reference-landmark" type="button" class="icon-btn element-list-add">${M.PLUS}</button>
1055
+ <button id="add-reference-landmark" type="button" class="icon-btn element-list-add">${L.PLUS}</button>
1056
1056
  </div>
1057
1057
  <div class="element-list-body" id="reference-landmark-item">
1058
1058
  <label><span id="label-reference-landmark-label"></span> <input id="referenceLandmarkLabel" type="text"/></label>
@@ -1074,9 +1074,9 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
1074
1074
  <h3 class="section-title"><span id="label-trace-import"></span></h3>
1075
1075
  <div class="element-list-row" id="trace-row">
1076
1076
  <label class="element-list-picker"><select id="trace" aria-labelledby="label-trace-import"></select></label>
1077
- <button id="delete-trace" type="button" class="icon-btn">${M.TRASH}</button>
1077
+ <button id="delete-trace" type="button" class="icon-btn">${L.TRASH}</button>
1078
1078
  <span id="trace-empty" class="element-list-empty"></span>
1079
- <button id="add-trace" type="button" class="icon-btn element-list-add">${M.PLUS}</button>
1079
+ <button id="add-trace" type="button" class="icon-btn element-list-add">${L.PLUS}</button>
1080
1080
  </div>
1081
1081
  <!-- Where the lines added by "+" are read from: a file of the author's, or an address. -->
1082
1082
  <span id="trace-import-row" class="input-file-row" hidden><rr0-input-file id="trace-import" name="trace-import" accept=".kml,.kmz,.geojson,.json,application/vnd.google-earth.kml+xml,application/vnd.google-earth.kmz,application/geo+json,application/json" placeholder="https://…/lines.kmz"></rr0-input-file></span>
@@ -1110,9 +1110,9 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
1110
1110
  picked shape, gone while there is none. -->
1111
1111
  <div class="element-list-row" id="shape-row">
1112
1112
  <label class="element-list-picker"><select id="source"></select></label>
1113
- <button id="delete-shape" type="button" class="icon-btn">${M.TRASH}</button>
1113
+ <button id="delete-shape" type="button" class="icon-btn">${L.TRASH}</button>
1114
1114
  <span id="shape-empty" class="element-list-empty"></span>
1115
- <button id="add-shape" type="button" class="icon-btn element-list-add">${M.PLUS}</button>
1115
+ <button id="add-shape" type="button" class="icon-btn element-list-add">${L.PLUS}</button>
1116
1116
  </div>
1117
1117
  <div class="element-list-body" id="shape-item">
1118
1118
  <div class="form-section">
@@ -1215,7 +1215,7 @@ fieldset { border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); bo
1215
1215
  <div id="context-masks-submenu" class="submenu" role="menu"></div>
1216
1216
  </div>
1217
1217
  </div>
1218
- `,lr=`${De.CSS}${fe.CSS}${M.CSS}${Fe.CSS}${C.CSS}${C.INDEX_CSS}${$e.CSS}${yi.CSS}${xe.CSS}${Ns.CSS}${Bs.CSS}${ne.CSS}
1218
+ `,lr=`${De.CSS}${fe.CSS}${L.CSS}${Fe.CSS}${O.CSS}${O.INDEX_CSS}${We.CSS}${yi.CSS}${xe.CSS}${Ns.CSS}${Bs.CSS}${ne.CSS}
1219
1219
  :host {
1220
1220
  color-scheme: light dark;
1221
1221
  display: block;
@@ -2364,7 +2364,7 @@ ${F.rules(["#scenery-status",".apparent-size",".place-status",".ground-elevation
2364
2364
  The site's own tokens (site/style.css), each a light-dark() pair: they follow the colour scheme this
2365
2365
  widget is used in exactly as Canvas and CanvasText do. The scene keeps its own colours in both. */
2366
2366
  :host {
2367
- ${Qe.TOKENS}
2367
+ ${He.TOKENS}
2368
2368
  --rr0-field-radius: 8px;
2369
2369
  --rr0-input-font-size: 15px;
2370
2370
  /* What the layout adapts to: the width this editor is given, never the window's. */
@@ -2402,7 +2402,7 @@ ${Qe.TOKENS}
2402
2402
  .app .toolbar > label:has(> input[type="checkbox"]) { display: inline-flex; align-items: center; gap: 8px; min-height: 38px; }
2403
2403
  /* Held by another editor (see embedded): no card of its own inside that one's. */
2404
2404
  .app.embedded { border: 0; border-radius: 0; max-width: none; }
2405
- ${Qe.HEAD}
2405
+ ${He.HEAD}
2406
2406
  .scene-card { background: #0b1020; }
2407
2407
  .scene-card > .render-line { padding: 6px 12px; background: var(--ground-raised); }
2408
2408
  .scene-card > .render-line:not(:has(:not(:empty))) { display: none; }
@@ -2504,7 +2504,7 @@ ${Qe.HEAD}
2504
2504
  .group-panel .toolbar > label:not(:has(> input[type="checkbox"], > input[type="radio"])) > :first-child { grid-column: 1 / -1; }
2505
2505
  .group-panel .toolbar > label > :is(input, select, textarea) { font-weight: 400; }
2506
2506
  .group-panel .toolbar > label.wide { display: flex; }
2507
- ${Qe.fields(".app")}
2507
+ ${He.fields(".app")}
2508
2508
  /* A group's parts: tabs underlined as the groups' are, each with its pictogram (dicté 2026-11-21 : « le même principe d'onglets avec
2509
2509
  icônes, et arrête les boutons de groupes »), the part open underlined; a line under them all. */
2510
2510
  .subtabs-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin: 0 0 16px; }
@@ -2677,7 +2677,7 @@ ${Qe.fields(".app")}
2677
2677
  .app > .group-panel { grid-area: panel; border-left: 1px solid var(--line); }
2678
2678
  .app > .section-index { grid-area: index; display: block; padding: 10px 0; overflow-y: auto; overflow-x: hidden; background: var(--ground-raised); }
2679
2679
  .app > .column-resize { display: block; grid-column: 1; grid-row: 4 / span 3; margin-right: -6px; }
2680
- ${C.INDEXED_CSS}
2680
+ ${O.INDEXED_CSS}
2681
2681
  }
2682
2682
  @container (max-width: 640px) {
2683
2683
  .editor-head { flex-wrap: wrap; }
@@ -2702,7 +2702,7 @@ rr0-popover-picker .pp-choice:hover, rr0-popover-picker .pp-choice:focus-visible
2702
2702
  rr0-popover-picker .pp-choice[aria-selected="true"] { font-weight: 600; }
2703
2703
  rr0-popover-picker .pp-choice[aria-selected="true"]::before { content: "✓ "; }
2704
2704
  rr0-popover-picker .pp-choice[aria-disabled="true"] { opacity: .45; cursor: not-allowed; background: none; }
2705
- `;class $t extends HTMLElement{tree=[];current="";trigger;panel;stale=!0;build(){if(this.trigger)return;const e=this.ownerDocument,t=e.createElement("style");t.textContent=mr;const i=e.createElement("button");i.type="button",i.className="pp-trigger rr0-select";const s=e.createElement("div");s.className="pp-panel",s.setAttribute("popover",""),s.setAttribute("role","listbox");const n=`${this.id||"rr0-popover-picker"}-panel`;s.id=n,i.setAttribute("popovertarget",n),i.setAttribute("aria-haspopup","listbox"),this.trigger=i,this.panel=s,s.addEventListener("beforetoggle",r=>{r.newState==="open"&&this.drawMenu()}),this.append(t,i,s),this.render()}connectedCallback(){this.build()}set choices(e){this.tree=e,this.build(),this.render()}get choices(){return this.tree}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(e){this.setAttribute("placeholder",e),this.render()}get value(){return this.current}set value(e){this.current=e,this.build(),this.render()}get selectedLabel(){return $t.find(this.tree,this.current)?.label}static find(e,t){for(const i of e)if(i.children){const s=$t.find(i.children,t);if(s)return s}else if(i.id===t)return i}pick(e){e.disabledReason!==void 0||e.id===void 0||(this.panel?.hidePopover?.(),e.id!==this.current&&(this.current=e.id,this.render(),this.dispatchEvent(new Event("change",{bubbles:!0}))))}render(){if(!this.trigger||!this.panel)return;this.trigger.textContent=this.selectedLabel??(this.current||this.placeholder),this.stale=!0;let e=!1;try{e=this.panel.matches(":popover-open")}catch{}e&&this.drawMenu()}drawMenu(){if(!this.panel||!this.stale)return;this.stale=!1;const e=this.ownerDocument,t=(i,s)=>i.flatMap(n=>{if(n.children){const a=e.createElement("div");return a.className="pp-heading",a.setAttribute("role","presentation"),a.style.setProperty("--pp-depth",String(s)),a.textContent=n.label,[a,...t(n.children,s+1)]}const r=e.createElement("button");r.type="button",r.className="pp-choice",r.dataset.id=n.id,r.setAttribute("role","option"),r.setAttribute("aria-selected",String(n.id===this.current)),r.style.setProperty("--pp-depth",String(s)),r.textContent=n.label;const o=n.disabledReason??n.hint;return o&&(r.title=o),n.disabledReason!==void 0&&r.setAttribute("aria-disabled","true"),r.addEventListener("click",()=>this.pick(n)),[r]});this.panel.replaceChildren(...t(this.tree,0))}}function gr(){customElements.get(ls)||customElements.define(ls,$t)}const Wt="rr0-duration-input",fr=`
2705
+ `;class Ht extends HTMLElement{tree=[];current="";trigger;panel;stale=!0;build(){if(this.trigger)return;const e=this.ownerDocument,t=e.createElement("style");t.textContent=mr;const i=e.createElement("button");i.type="button",i.className="pp-trigger rr0-select";const s=e.createElement("div");s.className="pp-panel",s.setAttribute("popover",""),s.setAttribute("role","listbox");const n=`${this.id||"rr0-popover-picker"}-panel`;s.id=n,i.setAttribute("popovertarget",n),i.setAttribute("aria-haspopup","listbox"),this.trigger=i,this.panel=s,s.addEventListener("beforetoggle",r=>{r.newState==="open"&&this.drawMenu()}),this.append(t,i,s),this.render()}connectedCallback(){this.build()}set choices(e){this.tree=e,this.build(),this.render()}get choices(){return this.tree}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(e){this.setAttribute("placeholder",e),this.render()}get value(){return this.current}set value(e){this.current=e,this.build(),this.render()}get selectedLabel(){return Ht.find(this.tree,this.current)?.label}static find(e,t){for(const i of e)if(i.children){const s=Ht.find(i.children,t);if(s)return s}else if(i.id===t)return i}pick(e){e.disabledReason!==void 0||e.id===void 0||(this.panel?.hidePopover?.(),e.id!==this.current&&(this.current=e.id,this.render(),this.dispatchEvent(new Event("change",{bubbles:!0}))))}render(){if(!this.trigger||!this.panel)return;this.trigger.textContent=this.selectedLabel??(this.current||this.placeholder),this.stale=!0;let e=!1;try{e=this.panel.matches(":popover-open")}catch{}e&&this.drawMenu()}drawMenu(){if(!this.panel||!this.stale)return;this.stale=!1;const e=this.ownerDocument,t=(i,s)=>i.flatMap(n=>{if(n.children){const a=e.createElement("div");return a.className="pp-heading",a.setAttribute("role","presentation"),a.style.setProperty("--pp-depth",String(s)),a.textContent=n.label,[a,...t(n.children,s+1)]}const r=e.createElement("button");r.type="button",r.className="pp-choice",r.dataset.id=n.id,r.setAttribute("role","option"),r.setAttribute("aria-selected",String(n.id===this.current)),r.style.setProperty("--pp-depth",String(s)),r.textContent=n.label;const o=n.disabledReason??n.hint;return o&&(r.title=o),n.disabledReason!==void 0&&r.setAttribute("aria-disabled","true"),r.addEventListener("click",()=>this.pick(n)),[r]});this.panel.replaceChildren(...t(this.tree,0))}}function gr(){customElements.get(ls)||customElements.define(ls,Ht)}const Wt="rr0-duration-input",fr=`
2706
2706
  rr0-duration-input { position: relative; display: inline-flex; align-items: center; gap: .3em; }
2707
2707
  rr0-duration-input .duration-field { position: relative; display: inline-flex; align-items: center; gap: .25em; }
2708
2708
  rr0-duration-input .duration-field input[type="text"] { padding-right: 2.1em; }
@@ -2718,7 +2718,7 @@ rr0-duration-input .duration-mode:focus-visible { outline: 2px solid #4af; outli
2718
2718
  rr0-duration-input [hidden] { display: none !important; }
2719
2719
  ${Se.css("rr0-duration-input .duration-helppop")}
2720
2720
  `;class br extends HTMLElement{wording;built=!1;precise=!0;numberInput;textInput;modeButton;helpButton;popup;chosen;build(){if(this.built)return;this.built=!0;const e=this.getAttribute("name"),t=this.ownerDocument,i=t.createElement("style");i.textContent=fr;const s=t.createElement("span");s.className="duration-field",this.numberInput=t.createElement("input"),this.numberInput.type="number",this.numberInput.min="0",this.numberInput.max="86400",this.numberInput.step="0.1",this.numberInput.setAttribute("aria-required","true");const n=t.createElement("span");n.className="duration-unit",n.textContent="s",this.textInput=t.createElement("input"),this.textInput.type="text",this.textInput.hidden=!0,this.helpButton=t.createElement("button"),this.helpButton.type="button",this.helpButton.className="duration-help",this.helpButton.textContent="?",this.helpButton.hidden=!0,this.popup=t.createElement("div"),this.popup.className="duration-helppop",Se.attach(this.helpButton,this.popup),this.chosen=t.createElement("span"),this.chosen.className="duration-chosen",this.chosen.hidden=!0,this.modeButton=t.createElement("button"),this.modeButton.type="button",this.modeButton.className="duration-mode",e&&(this.numberInput.id=e,this.textInput.id=`${e}-text`),s.append(this.numberInput,n,this.textInput,this.helpButton,this.popup),this.append(i,s,this.modeButton,this.chosen),this.numberInput.addEventListener("input",()=>{const r=this.numberInput.value;this.tell(r===""?void 0:Number(r),void 0)}),this.textInput.addEventListener("input",()=>this.readText()),this.textInput.addEventListener("focus",()=>this.showDeduction()),this.modeButton.addEventListener("click",()=>this.setPrecise(!this.precise)),this.helpButton.addEventListener("click",()=>Se.show(this.popup,this.popup.hidden)),this.applyWording()}connectedCallback(){this.build(),document.addEventListener("pointerdown",this.closeHelpOutside,!0),document.addEventListener("keydown",this.closeHelpOnEscape,!0)}disconnectedCallback(){document.removeEventListener("pointerdown",this.closeHelpOutside,!0),document.removeEventListener("keydown",this.closeHelpOnEscape,!0)}closeHelpOutside=e=>{this.popup&&!this.popup.hidden&&!e.composedPath().includes(this)&&Se.show(this.popup,!1)};closeHelpOnEscape=e=>{e.key==="Escape"&&this.popup&&Se.show(this.popup,!1)};get input(){return this.build(),this.numberInput}get textField(){return this.build(),this.textInput}get isPrecise(){return this.build(),this.precise}set messages(e){this.wording=e,this.built&&this.applyWording()}applyWording(){const e=this.wording;if(!e)return;this.modeButton.title=e.durationModeTitle,this.modeButton.setAttribute("aria-label",e.durationModeTitle);const t=this.ownerDocument.createElement("p");t.textContent=e.durationHelpTitle;const i=this.ownerDocument.createElement("ul");for(const s of e.durationHelpLines.split(`
2721
- `)){const n=this.ownerDocument.createElement("li");n.textContent=s,i.append(n)}this.popup.replaceChildren(t,i),this.setPrecise(this.precise)}setPrecise(e){this.build();const t=this.precise;this.precise=e,this.numberInput.hidden=!e,this.querySelector(".duration-unit").hidden=!e,this.textInput.hidden=e,this.helpButton.hidden=e,this.modeButton.textContent=(e?this.wording?.durationPrecise:this.wording?.durationIso)??"",this.modeButton.setAttribute("aria-pressed",String(!e)),!e&&t&&this.textInput.value===""&&this.numberInput.value!==""&&(this.textInput.value=we.format(Number(this.numberInput.value))),this.showDeduction(),this.showChosen()}set(e,t){this.build(),this.numberInput.value=e===void 0?"":String(e),this.textInput.value=t??"",this.setPrecise(t===void 0)}readText(){const e=this.textInput.value.trim();if(this.showDeduction(),e===""){this.numberInput.value="",this.showChosen(),this.tell(void 0,void 0);return}const t=we.parse(e);t&&(this.numberInput.value=String(t.chosenSeconds),this.showChosen(),this.tell(t.chosenSeconds,we.isExact(e)?void 0:e))}tell(e,t){this.dispatchEvent(new CustomEvent("durationchange",{detail:{seconds:e,text:t},bubbles:!0,composed:!0}))}describe(e){const t=this.wording,i=e.minSeconds===e.maxSeconds?we.say(e.minSeconds):`${we.say(e.minSeconds)} – ${we.say(e.maxSeconds)}`,s=t?e.doubt==="~"?t.timeQualifierApproximate:e.doubt==="?"?t.timeQualifierUncertain:e.doubt==="%"?t.timeQualifierBoth:"":"";return s?`${i} — ${s.toLowerCase()}`:i}showDeduction(){const e=this.textInput.value.trim();if(this.precise||e===""){this.textInput.title="";return}const t=we.parse(e);this.textInput.title=t?`→ ${this.describe(t)}`:this.wording?.durationInvalid??""}showChosen(){const e=this.precise?void 0:we.parse(this.textInput.value),t=e!==void 0&&!we.isExact(this.textInput.value);this.chosen.hidden=!t,this.chosen.textContent=t&&this.wording?this.wording.durationChosen.replace("{value}",we.say(e.chosenSeconds)):""}}function vr(){customElements.get(Wt)||customElements.define(Wt,br)}class kt{static at(e,t){if(e.year===void 0||t.year===void 0)return;let i=t.year-e.year;const s=(n,r)=>n!==void 0&&r!==void 0;return s(e.month,t.month)&&(t.month<e.month||t.month===e.month&&s(e.day,t.day)&&t.day<e.day)&&i--,i>=0?i:void 0}static birthFor(e,t){if(t.year===void 0)return;const i=t.year-e;return{year:i,raw:`${String(i).padStart(4,"0")}~`}}static isFirm(e){return!/[?~%]/.test(e.raw??"")}}class jt{static easter(e){const t=e%19,i=Math.floor(e/100),s=e%100,n=Math.floor(i/4),r=i%4,o=Math.floor((i+8)/25),a=Math.floor((i-o+1)/3),d=(19*t+i-n-a+15)%30,l=Math.floor(s/4),h=s%4,c=(32+2*r+2*l-d-h)%7,u=Math.floor((t+11*d+22*c)/451),p=Math.floor((d+c-7*u+114)/31),m=(d+c-7*u+114)%31+1;return new Date(Date.UTC(e,p-1,m,12))}static lunation(e){if(e<1583)return;const t=jt.easter(e),i=qt(0,t,40);if(!i)return;const s=qt(180,i.date,20),n=qt(0,new Date(i.date.getTime()+864e5),40);if(!(!s||!n))return{begin:i.date,full:s.date,end:n.date}}static isIn(e){const t=jt.lunation(e.getUTCFullYear());return t!==void 0&&e>=t.begin&&e<t.end}}const wr=[{id:"echo",name:"the Echo balloons",from:"1960-08-12",to:"1969-06-07",peakMagnitude:-1,note:"Echo 1 and 2 were 30- and 40-metre reflective balloons, as bright as the brightest stars and moving slowly enough to be watched — deliberately visible, widely announced in newspapers, and the first objects most people ever saw crossing the night sky. They fall squarely inside the sighting waves this project reconstructs."},{id:"iridium-flares",name:"the Iridium flares",from:"1997-05-05",to:"2019-12-27",peakMagnitude:-8,note:"The original Iridium satellites carried flat, mirror-finish antennas that threw a sunbeam a few kilometres wide across the ground: a still point of sky flaring to magnitude -8 over five seconds and vanishing again. Nothing else in the sky does that."},{id:"iss",name:"the International Space Station",from:"1998-11-20",peakMagnitude:-5.9,note:"Since its first module, and much brighter as it grew: at its best it outshines everything in the sky but the Sun and the Moon, crossing in a straight silent line in about four minutes."},{id:"starlink-trains",name:"the Starlink trains",from:"2019-05-24",peakMagnitude:1,note:"In the days after a launch, satellites still bunched in their deployment string cross as an evenly spaced line of lights — the most reported 'formation of UFOs' of the era. They spread out within weeks, so a train is a fact about the days after a launch rather than about the year."}],yr=23493,ds=[2,3,2,1,2,5,4,6,5,6,6,6,6,6,6,6,9,9,9,9,9,9,14,14,15,16,16,16,16,16,18,22,25,24,29,28,29,33,34,35,40,40,42,42,43,46,48,48,49,53,53,54,58,61,70,70,74,78,79,83,92,92,99,97,101,102,109,115,126,125,123,125,127,130,139,153,157,156,161,156,165,174,193,193,201,203,212,215,224,244,255,263,262,281,293,307,312,327,339,336,343,353,359,369,386,396,405,410,421,419,424,434,443,450,460,480,492,504,509,516,519,524,527,530,527,535,543,549,564,571,573,576,582,584,600,600,608,618,625,632,637,642,648,654,661,667,669,667,671,671,697,692,703,697,710,714,724,731,747,755,764,770,782,802,801,815,819,837,846,856,878,881,877,900,906,907,917,932,932,936,954,973,989,986,991,990,1002,1009,1021,1024,1040,1038,1058,1078,1098,1092,1094,1099,1122,1132,1140,1151,1154,1161,1176,1185,1202,1206,1227,1228,1243,1265,1281,1288,1296,1325,1328,1336,1354,1373,1375,1393,1398,1411,1432,1457,1462,1476,1487,1485,1506,1509,1521,1524,1537,1543,1563,1586,1598,1614,1621,1620,1640,1658,1660,1673,1670,1686,1708,1715,1726,1726,1745,1749,1767,1774,1790,1798,1803,1805,1815,1818,1819,1820,1833,1822,1821,1819,1838,1835,1845,1841,1851,1869,1865,1868,1871,1870,1879,1882,1886,1900,1899,1908,1921,1928,1954,1966,1976,1986,1999,2007,2015,2030,2036,2057,2067,2072,2077,2088,2101,2106,2112,2119,2127,2142,2171,2176,2203,2226,2242,2241,2244,2254,2263,2284,2300,2320,2327,2345,2364,2367,2402,2423,2425,2434,2443,2461,2476,2495,2505,2520,2531,2535,2556,2567,2599,2608,2625,2639,2660,2663,2668,2681,2695,2702,2709,2719,2720,2738,2746,2763,2778,2788,2796,2807,2822,2831,2831,2853,2863,2866,2883,2892,2895,2921,2919,2937,2941,2947,2964,2987,2992,2987,2995,3002,3021,3025,3026,3036,3052,3049,3059,3077,3075,3083,3086,3107,3123,3124,3146,3155,3168,3179,3204,3205,3211,3233,3252,3253,3276,3287,3294,3293,3297,3314,3326,3335,3338,3355,3362,3358,3365,3364,3376,3375,3382,3418,3429,3432,3455,3463,3483,3490,3502,3509,3521,3532,3542,3544,3553,3571,3580,3588,3596,3603,3633,3639,3649,3655,3660,3670,3699,3699,3707,3723,3747,3752,3754,3766,3772,3778,3781,3798,3815,3814,3824,3832,3853,3859,3879,3885,3899,3912,3910,3924,3937,3951,3951,3961,3963,3961,3976,3977,3988,4004,4018,4025,4047,4074,4086,4108,4133,4136,4159,4168,4182,4192,4200,4215,4230,4239,4257,4678,4698,4694,4713,4719,4739,4750,4756,4764,4771,4788,4792,4790,4809,4821,4829,4834,4836,4843,4853,4863,4872,4881,4890,4898,4901,4897,4895,4884,4886,4886,4894,4897,4905,4905,4909,4907,4925,4918,4920,4929,4925,4928,4936,4943,4944,4951,4955,4952,4974,4976,4975,4981,4994,4997,5022,5023,5032,5043,5048,5051,5066,5062,5068,5075,5082,5082,5098,5102,5110,5113,5119,5123,5138,5138,5145,5149,5157,5165,5166,5169,5178,5183,5190,5192,5203,5204,5207,5214,5228,5234,5245,5249,5256,5262,5275,5278,5305,5303,5315,5321,5348,5358,5369,5369,5372,5385,5402,5409,5427,5429,5429,5439,5456,5464,5481,5485,5494,5509,5520,5526,5543,5555,5568,5575,5585,5596,5602,5620,5627,5644,5647,5660,5678,5680,5684,5692,5700,5711,5727,5733,5736,5756,5776,5797,5805,5804,5807,5800,5808,5814,5822,5839,5856,5869,5889,5902,5919,5921,5936,5937,5936,5957,5961,5975,5981,6002,6015,6027,6035,6042,6059,6062,6080,6081,6092,6097,6106,6127,6129,6198,6227,6231,6243,6249,6262,6255,6279,6304,6315,6326,6330,6334,6361,6358,6359,6379,6381,6389,6388,6404,6404,6443,6465,6473,6497,6500,6513,6524,6532,6538,6578,6572,6576,6584,6582,6608,6639,6656,6761,6764,6768,6772,6836,6905,6916,6925,6951,6984,7009,7072,7092,7110,7122,7140,7148,7170,7168,7180,7194,7247,7374,7391,7393,7382,7425,7485,7530,7568,7587,7602,7602,7715,7771,7900,8004,8103,8153,8162,8296,8319,8437,8566,8746,8860,8913,9128,9275,9585,9739,10014,10123,10167,10203,10288,10323,10398,10544,10721,10883,11044,11157,11442,11515,11787,12070,12269,12468,12484,12619,12883,13008,13264,13317,13549,13859,14049,14175,14360,14498,14687,14843,14984,15093,15279,15431,15623,15741,15788,15966,16025,16132,16419,16568,16791,16892,17060,17269,17598,17959,18194,18482,18804,19136,19564,19990,20249,20509,20943,21248,21539,21845,22196,22412];class ve{static FIRST_ORBIT="1957-10-04";static EARTH_RADIUS_KM=6371;static LOW_ORBIT_KM=500;static shadowHeightKm(e){if(e>=0)return 0;const t=-e*Math.PI/180;return ve.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>ve.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return wr.filter(i=>{const s=Date.parse(`${i.from}T00:00:00Z`),n=i.to===void 0?1/0:Date.parse(`${i.to}T23:59:59Z`);return t>=s&&t<=n})}static trackedInOrbitAt(e){const t=e.getUTCFullYear()*12+e.getUTCMonth()-yr;if(!(t<0))return ds[Math.min(t,ds.length-1)]}static visibilityAt(e,t){const i=V("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:i,shadowHeightKm:ve.shadowHeightKm(i),lowOrbitLit:ve.isLitOverhead(ve.LOW_ORBIT_KM,i),classes:ve.classesAt(e),trackedObjects:ve.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${ve.FIRST_ORBIT}T00:00:00Z`)}}}const kr="https://ufoathome.org/light-pollution/index.json";class He{year=2015;citation="World Atlas of the artificial night sky brightness (Falchi et al. 2016, doi:10.1126/sciadv.1600377; data doi:10.5880/GFZ.1.4.2016.001, CC BY-NC 4.0)";static NATURAL_MCD=.171168;fetchImpl;indexUrls;index;tiles=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??He.defaultIndexUrls()}static defaultIndexUrls(){const e=typeof location>"u"?void 0:new URL("/light-pollution/index.json",location.href).href;return[...new Set([e,kr].filter(t=>t!==void 0))]}static magPerArcsec2Of(e){return-2.5*Math.log10((e+He.NATURAL_MCD)/108e6)}static mcdOf(e,t){return e===0?0:t.floorMcd*10**((e-1)/t.subdivisions)}async lookUp(e,t){const i=await this.loadIndex();if(!i)return{status:"failed"};const{index:s,base:n,present:r}=i;if(!(e<s.north&&e>=s.south))return{status:"outside"};const o=((t+180)%360+360)%360-180,a=Math.floor((s.north-e)/s.tileDeg),d=Math.floor((o+180)/s.tileDeg),l=a*(360/s.tileDeg)+d;if(!(r[l>>3]&1<<(l&7)))return{status:"natural"};const h=s.north-a*s.tileDeg,c=-180+d*s.tileDeg,u=He.nameOf(h-s.tileDeg,c),p=await this.tile(`${n}${u}.bin`);if(!p)return{status:"failed"};const m=s.tileDeg/s.cells,f=Math.min(s.cells-1,Math.floor((h-e)/m)),g=Math.min(s.cells-1,Math.floor((o-c)/m)),b=He.mcdOf(p[f*s.cells+g],s);return b===0?{status:"natural"}:{status:"found",lightPollution:Math.round(He.magPerArcsec2Of(b)*100)/100,artificialMcdPerM2:b,lat:h-(f+.5)*m,lng:c+(g+.5)*m}}static nameOf(e,t){const i=`${e<0?"S":"N"}${String(Math.abs(e)).padStart(2,"0")}`,s=`${t<0?"W":"E"}${String(Math.abs(t)).padStart(3,"0")}`;return i+s}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json(),s=Uint8Array.from(atob(i.present),n=>n.charCodeAt(0));return{index:i,base:new URL(".",e).href,present:s}}catch{}})(),this.index.then(e=>{e||(this.index=void 0)}),this.index}tile(e){let t=this.tiles.get(e);return t||(t=(async()=>{try{const i=await this.fetchImpl(e);if(!i.ok||!i.body)return;const s=i.body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(s).arrayBuffer())}catch{return}})(),this.tiles.set(e,t),t.then(i=>{i||this.tiles.delete(e)})),t}}const Et=he.point("lightPollution").provide(he.BUILT_IN,[{id:"falchi-2015",name:"World Atlas 2015",credit:"Falchi et al. 2016, CC BY-NC 4.0",creditUrl:"https://doi.org/10.5880/GFZ.1.4.2016.001",create:()=>new He}]);class R{static COARSE_STEP_DEG=10;static FINE_STEP_DEG=2;static FINE_SPAN_DEG=10;static LOWEST_DEG=5;static THRESHOLD_CONTRAST=.5;static CONE_SEPARATION_DEG=60;galaxy=new rn;dust=new on;assess(e,t,i){const s=V("Sun",e,t),n=V("Moon",e,t),r={altitudeDeg:n.altitudeDeg,phaseAngleDeg:pe.phaseAngleOf(Je(e).illuminatedFraction)},o=Ai.galactic(e,t),a=R.unit(o.centre),d=R.unit(o.rotation),l=R.unit(o.pole),h=R.unit(Ai.eclipticPole(e,t)),c=R.unit(s),u=R.unit(n),p=R.normalize(R.reject(c,h));let m,f,g=0;const b=(v,I)=>{const x=R.unit({altitudeDeg:v,azimuthDeg:I}),y=R.between(x,c),S=pe.magPerArcsec2({altitudeDeg:s.altitudeDeg,separationDeg:y},{...r,separationDeg:R.between(x,u)},v,i);S>g&&(g=S);const O=Ci.fromMagPerArcsec2(S),N=10**(-.4*pe.EXTINCTION_PER_AIR_MASS*(pe.airMass(v)-1)),A=this.galaxy.surfaceBrightnessS10(Math.atan2(R.dot(x,d),R.dot(x,a))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,R.dot(x,l))))*180/Math.PI)*N;m=R.better(m,A,O,S,v,I,y);const te=Math.max(-1,Math.min(1,R.dot(x,h))),Z=R.normalize(R.reject(x,h)),Ce=this.dust.surfaceBrightnessS10(R.between(Z,p),Math.asin(te)*180/Math.PI)*N;f=R.better(f,Ce,O,S,v,I,y)};for(let v=R.LOWEST_DEG;v<=90;v+=R.COARSE_STEP_DEG)for(let I=0;I<360;I+=R.COARSE_STEP_DEG)b(v,I);for(const v of[m,f]){if(!v)continue;const I=R.FINE_SPAN_DEG,x=R.FINE_STEP_DEG;for(let y=v.altitudeDeg-I;y<=v.altitudeDeg+I;y+=x)if(!(y<R.LOWEST_DEG||y>90))for(let S=v.azimuthDeg-I;S<=v.azimuthDeg+I;S+=x)b(y,(S+360)%360)}return{milkyWay:m&&m.contrast>=R.THRESHOLD_CONTRAST?m:void 0,zodiacal:f&&f.contrast>=R.THRESHOLD_CONTRAST?f:void 0,darkestSkyMagPerArcsec2:g}}static better(e,t,i,s,n,r,o){const a=t/i;return e&&e.contrast>=a?e:{contrast:a,altitudeDeg:n,azimuthDeg:r,magPerArcsec2:Ci.toMagPerArcsec2(t),skyMagPerArcsec2:s,sunSeparationDeg:o}}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,s=Math.cos(t);return[s*Math.sin(i),Math.sin(t),-s*Math.cos(i)]}static dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}static between(e,t){return Math.acos(Math.max(-1,Math.min(1,R.dot(e,t))))*180/Math.PI}static reject(e,t){const i=R.dot(e,t);return[e[0]-i*t[0],e[1]-i*t[1],e[2]-i*t[2]]}static normalize(e){const t=Math.hypot(...e)||1;return[e[0]/t,e[1]/t,e[2]/t]}}class _{static MIN_NAME_LENGTH=3;static EMAIL=/[\p{L}\d._%+-]+@[\p{L}\d-]+(?:\.[\p{L}\d-]+)+/u;static PHONE=/(?:\+\d{1,3}[ .-]?|\b0)\d(?:[ .-]?\d{2}){4}\b|\+\d[\d ().-]{8,}\d/;static ADDRESS=new RegExp("\\b\\d{1,4}\\s?(?:bis|ter)?,?\\s+(?:rue|avenue|av\\.|boulevard|bd|chemin|impasse|allée|route|place|street|st\\.|road|rd|lane|drive|via|calle|piazza)\\b","iu");static inspect(e,t){const i=new Set((t?_.all(t):[]).map(s=>`${s.kind}:${s.found}`));return _.all(e).filter(s=>!i.has(`${s.kind}:${s.found}`))}static initialsOf(e){return e.trim().split("-").map(t=>{const i=[...t.trim()][0];return i===void 0?"":`${i.toLocaleUpperCase()}.`}).filter(t=>t!=="").join("-")}static withInitials(e,t,i=!1){let s=e;for(const n of _.usable(t)){const r=_.initialsOf(n);s=s.replace(new RegExp(_.escape(n),"giu"),i?r.replace(/[.-]/g,""):r)}return s}static namesOf(e){const t=e.observer,i=[t?.lastName,...t?.firstNames??[]];return _.usable(i.filter(s=>typeof s=="string"))}static isInitials(e){const t=e.replace(/[^\p{L}]/gu,"");return t.length>0&&t.length<=3&&t===t.toLocaleUpperCase()}static usable(e){return e.map(t=>(t??"").trim()).filter(t=>t.length>=_.MIN_NAME_LENGTH&&!_.isInitials(t))}static all(e){const t=[],i=e.observer,s=_.usable([i?.lastName]),n=_.usable(i?.firstNames??[]);for(const o of s)t.push({kind:"lastName",found:o});for(const o of n)t.push({kind:"firstNames",found:o});const r=[...s,...n];for(const o of[e.id,i?.id])for(const a of r)o&&o.toLocaleLowerCase().includes(a.toLocaleLowerCase())&&t.push({kind:"nameInId",found:`${o}`});for(const o of _.texts(e)){for(const h of r)new RegExp(`(?<![\\p{L}])${_.escape(h)}(?![\\p{L}])`,"iu").test(o)&&t.push({kind:"nameInText",found:h});const a=_.ADDRESS.exec(o)?.[0];a&&t.push({kind:"address",found:a});const d=_.EMAIL.exec(o)?.[0];d&&t.push({kind:"email",found:d});const l=_.PHONE.exec(o)?.[0];l&&t.push({kind:"phone",found:l})}return _.unique(t)}static texts(e){const t=n=>typeof n=="string"?[n]:typeof n=="object"&&n!==null?Object.values(n).filter(r=>typeof r=="string"):[],i=e.place,s=i===void 0?[]:[i.name??i.value?.name];return[...t(e.description),...t(e.summary),...t(e.account?.observerOccupation),...s.flatMap(t)]}static unique(e){const t=new Set;return e.filter(i=>{const s=`${i.kind}:${i.found}`;return t.has(s)?!1:(t.add(s),!0)})}static escape(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}const Er=.5,xt=40,xr=4e5,St=36e5,hs=25;class st{constructor(e){this.provider=e}queryOf(e){const t=this.questionOf(e);return t?{points:this.sampleTimings(e,t.start,Nt(e.event)??0).map(s=>this.pointAt(e,s,t.origin))}:void 0}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{start:i}=t,s=Nt(e.event)??0,n=this.sampleTimings(e,i,s);let r;try{r=await this.provider.getWeather(this.queryOf(e))}catch{return{status:"failed",at:i}}return r?{status:"inferred",at:i,source:r.source,keyframes:r.samples.map((o,a)=>({t:n[a].t,weather:o.weather}))}:{status:"unavailable",at:i}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const i of t.keyframes)e.weatherTrack.addKeyframe(i.t,i.weather);e.weatherSource=t.source}}sampleTimes(e,t){const i=[e],s=e.getTime()+t;let n=Math.floor(e.getTime()/St)*St+St;for(;n<=s&&i.length<hs;)i.push(new Date(n)),n+=St;return t>0&&i[i.length-1].getTime()!==s&&i.length<hs&&i.push(new Date(s)),i}sampleTimings(e,t,i){const s=e.timeline.duration>0?e.timeline.duration:i;return i<=0||s<=0?[{time:t,t:0}]:this.sampleTimes(t,i).map(n=>{const r=(n.getTime()-t.getTime())/i;return{time:n,t:Math.round(s*Math.max(0,Math.min(1,r)))}})}canInfer(e){return this.questionOf(e)!==void 0}missingOf(e){const t=e.event.time;return{date:t?.year===void 0||t.month===void 0||t.day===void 0,place:this.originOf(e)===void 0}}questionOf(e){const t=this.originOf(e);if(!t)return;const i=e.event.time;if(i?.year===void 0||i.month===void 0||i.day===void 0)return;const s=be(i,t.lng,e.event.utcOffsetHours);return s?{origin:t,start:s}:void 0}originOf(e){const t=Q(e,0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return s===void 0||n===void 0?void 0:{lat:s,lng:n}}pointAt(e,t,i){const s=Q(e,t.t);return{lat:s?.lat??i.lat,lng:s?.lng??i.lng,time:t.time}}}const Sr=Date.UTC(1940,0,1),cs=36e5,us=.25,Ir=.7,Tr=.45,Mr=.1,Lr=2,Dr=.3,Ar=.2,Cr=8,si=.125,Or=.05,ps=125,ms=100,gs=2500,ni=3500,ri=8e3,Rr=95,Pr=99,Br=[96,99],Nr=["cloud_cover","cloud_cover_low","cloud_cover_mid","cloud_cover_high","precipitation","snowfall","weather_code","wind_speed_10m","wind_direction_10m","temperature_2m","dew_point_2m"],Fr=5;class Fs{fetchImpl;baseUrl;forecastUrl;now;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive",this.forecastUrl=e.forecastUrl??"https://api.open-meteo.com/v1/forecast",this.now=e.now??(()=>new Date)}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(l=>l.time.getTime()),i=Math.min(...t);if(i<Sr)return;const s=new Map;for(const l of e.points){const h=this.cellKey(l);s.has(h)||s.set(h,{lat:l.lat,lng:l.lng,index:s.size})}const n=i>=this.now().getTime()-Fr*864e5,r=this.requestUrl([...s.values()],new Date(i),new Date(Math.max(...t)),n);let o=this.cache.get(r);if(!o){const l=await this.fetchImpl(r);if(!l.ok)throw new Error(`Open-Meteo HTTP ${l.status}`);const h=await l.json();if(o=Array.isArray(h)?h:[h],o.length<s.size||o.some(c=>c.error||!c.hourly))return;this.cache.set(r,o)}const a=n?{id:"open-meteo-forecast",name:"Open-Meteo (forecast model)",url:r}:{id:"era5",name:"ERA5 (Open-Meteo)",url:r},d=e.points.map(l=>this.sampleAt(o[s.get(this.cellKey(l)).index].hourly,l.time));if(!d.some(l=>l===void 0))return{samples:d,source:a}}cellKey(e){return`${Math.round(e.lat/us)},${Math.round(e.lng/us)}`}requestUrl(e,t,i,s){const n=new URLSearchParams({latitude:e.map(r=>r.lat).join(","),longitude:e.map(r=>r.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(i),hourly:Nr.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${s?this.forecastUrl:this.baseUrl}?${n}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const i=this.recordAt(e,t);return i&&{time:t,weather:this.toWeather(i)}}recordAt(e,t){const i=e.time.map(o=>Date.parse(`${o}Z`)),s=t.getTime();if(i.length===0||s<i[0]-cs||s>i[i.length-1]+cs)return;if(s<=i[0])return this.recordFrom(e,0);if(s>=i[i.length-1])return this.recordFrom(e,i.length-1);let n=0;for(;n+1<i.length&&i[n+1]<=s;)n++;const r=i[n+1]-i[n];return this.blendRecords(this.recordFrom(e,n),this.recordFrom(e,n+1),r>0?(s-i[n])/r:0)}recordFrom(e,t){const i={cloudCover:e.cloud_cover[t]/100,cloudCoverLow:e.cloud_cover_low[t]/100,cloudCoverMid:e.cloud_cover_mid[t]/100,cloudCoverHigh:e.cloud_cover_high[t]/100,precipitationMm:e.precipitation[t],snowfallCm:e.snowfall[t],weatherCode:e.weather_code[t],windSpeedMs:e.wind_speed_10m[t],windFromDeg:e.wind_direction_10m[t],temperatureC:e.temperature_2m[t],dewPointC:e.dew_point_2m[t]};return Object.values(i).some(s=>s===void 0||Number.isNaN(s))?void 0:i}blendRecords(e,t,i){if(!e||!t)return e??t;const s=(r,o)=>r+(o-r)*i,n=((t.windFromDeg-e.windFromDeg)%360+540)%360-180;return{cloudCover:s(e.cloudCover,t.cloudCover),cloudCoverLow:s(e.cloudCoverLow,t.cloudCoverLow),cloudCoverMid:s(e.cloudCoverMid,t.cloudCoverMid),cloudCoverHigh:s(e.cloudCoverHigh,t.cloudCoverHigh),precipitationMm:s(e.precipitationMm,t.precipitationMm),snowfallCm:s(e.snowfallCm,t.snowfallCm),weatherCode:i<.5?e.weatherCode:t.weatherCode,windSpeedMs:s(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+n*i)%360+360)%360,temperatureC:s(e.temperatureC,t.temperatureC),dewPointC:s(e.dewPointC,t.dewPointC)}}cloudLayersFrom(e){return[{id:"record-low",type:"unknown",baseM:Math.round(this.clamp(ps*(e.temperatureC-e.dewPointC),ms,gs)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:ni,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:ri,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=Rr&&e.weatherCode<=Pr,i=this.precipitationTypeFrom(e);return{cloudLayers:this.cloudLayersFrom(e),cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),highCloudCover:e.cloudCoverHigh,lowerCloudCover:Math.max(e.cloudCoverLow,e.cloudCoverMid),relativeHumidity:Math.round(an.relativeHumidity(e.temperatureC,e.dewPointC)*100)/100,precipitationType:i,precipitationIntensity:i==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/Cr),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":Br.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const i=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(i<=0)return 0;const s=(Ir*e.cloudCoverLow+Tr*e.cloudCoverMid+Mr*e.cloudCoverHigh)/i,n=Math.min(1,e.precipitationMm/Lr);return this.clamp(s+Dr*n+(t?Ar:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<Or)return;const t=this.clamp(ps*(e.temperatureC-e.dewPointC),ms,gs);if(e.cloudCoverLow>=si)return Math.round(t);if(e.cloudCoverMid>=si)return ni;if(e.cloudCoverHigh>=si)return ri;const i=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(i<=0))return i===e.cloudCoverLow?Math.round(t):i===e.cloudCoverMid?ni:ri}clamp(e,t,i){return Math.max(t,Math.min(i,e))}}function zr(){return new Fs}const Ur=5;class zs{attribution={text:"© OpenStreetMap",url:"https://osm.org/copyright"};fetchImpl;baseUrl;reverseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://nominatim.openstreetmap.org/search",this.reverseUrl=e.reverseUrl??"https://nominatim.openstreetmap.org/reverse"}async reverse(e,t,i={}){const s=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});i.language&&s.set("accept-language",i.language);const n=`${this.reverseUrl}?${s}`,r=this.cache.get(n);if(r)return r[0];const o=await this.fetchImpl(n,{signal:i.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const a=await o.json(),d=a.error?void 0:this.toMatch(a);return this.cache.set(n,d?[d]:[]),d}async search(e,t={}){const i=e.trim();if(i==="")return[];const s=this.requestUrl(i,t),n=this.cache.get(s);if(n)return n;const r=await this.fetchImpl(s,{signal:t.signal});if(!r.ok)throw new Error(`Nominatim HTTP ${r.status}`);const o=await r.json(),a=(Array.isArray(o)?o:[]).map(d=>this.toMatch(d)).filter(d=>d!==void 0);return this.cache.set(s,a),a}requestUrl(e,t){const i=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??Ur)});return t.language&&i.set("accept-language",t.language),`${this.baseUrl}?${i}`}toMatch(e){const t=e.display_name??e.name,i=this.coordinate(e.lat),s=this.coordinate(e.lon);return t&&i!==void 0&&s!==void 0?{name:t,lat:i,lng:s}:void 0}coordinate(e){if(e===void 0||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}}function _r(){return new zs}const oi=he.point("place").provide(he.BUILT_IN,[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new zs}]),ke=he.point("weather").provide(he.BUILT_IN,[{id:"era5",name:"Open-Meteo",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new Fs}]),It=E=>E.id==="open-meteo-forecast"||ke.some(e=>e.id===E.id);class fs{static of(e,t){if(!t)return e;let i,s;try{i=new URL(e),s=new URL(t)}catch{return e}if(i.origin!==s.origin||!/^https?:$/.test(i.protocol))return e;const n=s.pathname.split("/").slice(0,-1),r=i.pathname.split("/");let o=0;for(;o<n.length&&o<r.length-1&&n[o]===r[o];)o++;const a=n.length-o;return[...Array(a).fill(".."),...r.slice(o)].join("/")+i.search+i.hash}static names(e,t,i){return(e??[]).some(s=>{try{return new URL(s,i??t).href===t}catch{return!1}})}}class ct{constructor(e,t){this.root=e,this.messages=t}static STYLE=`
2721
+ `)){const n=this.ownerDocument.createElement("li");n.textContent=s,i.append(n)}this.popup.replaceChildren(t,i),this.setPrecise(this.precise)}setPrecise(e){this.build();const t=this.precise;this.precise=e,this.numberInput.hidden=!e,this.querySelector(".duration-unit").hidden=!e,this.textInput.hidden=e,this.helpButton.hidden=e,this.modeButton.textContent=(e?this.wording?.durationPrecise:this.wording?.durationIso)??"",this.modeButton.setAttribute("aria-pressed",String(!e)),!e&&t&&this.textInput.value===""&&this.numberInput.value!==""&&(this.textInput.value=we.format(Number(this.numberInput.value))),this.showDeduction(),this.showChosen()}set(e,t){this.build(),this.numberInput.value=e===void 0?"":String(e),this.textInput.value=t??"",this.setPrecise(t===void 0)}readText(){const e=this.textInput.value.trim();if(this.showDeduction(),e===""){this.numberInput.value="",this.showChosen(),this.tell(void 0,void 0);return}const t=we.parse(e);t&&(this.numberInput.value=String(t.chosenSeconds),this.showChosen(),this.tell(t.chosenSeconds,we.isExact(e)?void 0:e))}tell(e,t){this.dispatchEvent(new CustomEvent("durationchange",{detail:{seconds:e,text:t},bubbles:!0,composed:!0}))}describe(e){const t=this.wording,i=e.minSeconds===e.maxSeconds?we.say(e.minSeconds):`${we.say(e.minSeconds)} – ${we.say(e.maxSeconds)}`,s=t?e.doubt==="~"?t.timeQualifierApproximate:e.doubt==="?"?t.timeQualifierUncertain:e.doubt==="%"?t.timeQualifierBoth:"":"";return s?`${i} — ${s.toLowerCase()}`:i}showDeduction(){const e=this.textInput.value.trim();if(this.precise||e===""){this.textInput.title="";return}const t=we.parse(e);this.textInput.title=t?`→ ${this.describe(t)}`:this.wording?.durationInvalid??""}showChosen(){const e=this.precise?void 0:we.parse(this.textInput.value),t=e!==void 0&&!we.isExact(this.textInput.value);this.chosen.hidden=!t,this.chosen.textContent=t&&this.wording?this.wording.durationChosen.replace("{value}",we.say(e.chosenSeconds)):""}}function vr(){customElements.get(Wt)||customElements.define(Wt,br)}class kt{static at(e,t){if(e.year===void 0||t.year===void 0)return;let i=t.year-e.year;const s=(n,r)=>n!==void 0&&r!==void 0;return s(e.month,t.month)&&(t.month<e.month||t.month===e.month&&s(e.day,t.day)&&t.day<e.day)&&i--,i>=0?i:void 0}static birthFor(e,t){if(t.year===void 0)return;const i=t.year-e;return{year:i,raw:`${String(i).padStart(4,"0")}~`}}static isFirm(e){return!/[?~%]/.test(e.raw??"")}}class jt{static easter(e){const t=e%19,i=Math.floor(e/100),s=e%100,n=Math.floor(i/4),r=i%4,o=Math.floor((i+8)/25),a=Math.floor((i-o+1)/3),d=(19*t+i-n-a+15)%30,l=Math.floor(s/4),h=s%4,c=(32+2*r+2*l-d-h)%7,u=Math.floor((t+11*d+22*c)/451),p=Math.floor((d+c-7*u+114)/31),m=(d+c-7*u+114)%31+1;return new Date(Date.UTC(e,p-1,m,12))}static lunation(e){if(e<1583)return;const t=jt.easter(e),i=qt(0,t,40);if(!i)return;const s=qt(180,i.date,20),n=qt(0,new Date(i.date.getTime()+864e5),40);if(!(!s||!n))return{begin:i.date,full:s.date,end:n.date}}static isIn(e){const t=jt.lunation(e.getUTCFullYear());return t!==void 0&&e>=t.begin&&e<t.end}}const wr=[{id:"echo",name:"the Echo balloons",from:"1960-08-12",to:"1969-06-07",peakMagnitude:-1,note:"Echo 1 and 2 were 30- and 40-metre reflective balloons, as bright as the brightest stars and moving slowly enough to be watched — deliberately visible, widely announced in newspapers, and the first objects most people ever saw crossing the night sky. They fall squarely inside the sighting waves this project reconstructs."},{id:"iridium-flares",name:"the Iridium flares",from:"1997-05-05",to:"2019-12-27",peakMagnitude:-8,note:"The original Iridium satellites carried flat, mirror-finish antennas that threw a sunbeam a few kilometres wide across the ground: a still point of sky flaring to magnitude -8 over five seconds and vanishing again. Nothing else in the sky does that."},{id:"iss",name:"the International Space Station",from:"1998-11-20",peakMagnitude:-5.9,note:"Since its first module, and much brighter as it grew: at its best it outshines everything in the sky but the Sun and the Moon, crossing in a straight silent line in about four minutes."},{id:"starlink-trains",name:"the Starlink trains",from:"2019-05-24",peakMagnitude:1,note:"In the days after a launch, satellites still bunched in their deployment string cross as an evenly spaced line of lights — the most reported 'formation of UFOs' of the era. They spread out within weeks, so a train is a fact about the days after a launch rather than about the year."}],yr=23493,ds=[2,3,2,1,2,5,4,6,5,6,6,6,6,6,6,6,9,9,9,9,9,9,14,14,15,16,16,16,16,16,18,22,25,24,29,28,29,33,34,35,40,40,42,42,43,46,48,48,49,53,53,54,58,61,70,70,74,78,79,83,92,92,99,97,101,102,109,115,126,125,123,125,127,130,139,153,157,156,161,156,165,174,193,193,201,203,212,215,224,244,255,263,262,281,293,307,312,327,339,336,343,353,359,369,386,396,405,410,421,419,424,434,443,450,460,480,492,504,509,516,519,524,527,530,527,535,543,549,564,571,573,576,582,584,600,600,608,618,625,632,637,642,648,654,661,667,669,667,671,671,697,692,703,697,710,714,724,731,747,755,764,770,782,802,801,815,819,837,846,856,878,881,877,900,906,907,917,932,932,936,954,973,989,986,991,990,1002,1009,1021,1024,1040,1038,1058,1078,1098,1092,1094,1099,1122,1132,1140,1151,1154,1161,1176,1185,1202,1206,1227,1228,1243,1265,1281,1288,1296,1325,1328,1336,1354,1373,1375,1393,1398,1411,1432,1457,1462,1476,1487,1485,1506,1509,1521,1524,1537,1543,1563,1586,1598,1614,1621,1620,1640,1658,1660,1673,1670,1686,1708,1715,1726,1726,1745,1749,1767,1774,1790,1798,1803,1805,1815,1818,1819,1820,1833,1822,1821,1819,1838,1835,1845,1841,1851,1869,1865,1868,1871,1870,1879,1882,1886,1900,1899,1908,1921,1928,1954,1966,1976,1986,1999,2007,2015,2030,2036,2057,2067,2072,2077,2088,2101,2106,2112,2119,2127,2142,2171,2176,2203,2226,2242,2241,2244,2254,2263,2284,2300,2320,2327,2345,2364,2367,2402,2423,2425,2434,2443,2461,2476,2495,2505,2520,2531,2535,2556,2567,2599,2608,2625,2639,2660,2663,2668,2681,2695,2702,2709,2719,2720,2738,2746,2763,2778,2788,2796,2807,2822,2831,2831,2853,2863,2866,2883,2892,2895,2921,2919,2937,2941,2947,2964,2987,2992,2987,2995,3002,3021,3025,3026,3036,3052,3049,3059,3077,3075,3083,3086,3107,3123,3124,3146,3155,3168,3179,3204,3205,3211,3233,3252,3253,3276,3287,3294,3293,3297,3314,3326,3335,3338,3355,3362,3358,3365,3364,3376,3375,3382,3418,3429,3432,3455,3463,3483,3490,3502,3509,3521,3532,3542,3544,3553,3571,3580,3588,3596,3603,3633,3639,3649,3655,3660,3670,3699,3699,3707,3723,3747,3752,3754,3766,3772,3778,3781,3798,3815,3814,3824,3832,3853,3859,3879,3885,3899,3912,3910,3924,3937,3951,3951,3961,3963,3961,3976,3977,3988,4004,4018,4025,4047,4074,4086,4108,4133,4136,4159,4168,4182,4192,4200,4215,4230,4239,4257,4678,4698,4694,4713,4719,4739,4750,4756,4764,4771,4788,4792,4790,4809,4821,4829,4834,4836,4843,4853,4863,4872,4881,4890,4898,4901,4897,4895,4884,4886,4886,4894,4897,4905,4905,4909,4907,4925,4918,4920,4929,4925,4928,4936,4943,4944,4951,4955,4952,4974,4976,4975,4981,4994,4997,5022,5023,5032,5043,5048,5051,5066,5062,5068,5075,5082,5082,5098,5102,5110,5113,5119,5123,5138,5138,5145,5149,5157,5165,5166,5169,5178,5183,5190,5192,5203,5204,5207,5214,5228,5234,5245,5249,5256,5262,5275,5278,5305,5303,5315,5321,5348,5358,5369,5369,5372,5385,5402,5409,5427,5429,5429,5439,5456,5464,5481,5485,5494,5509,5520,5526,5543,5555,5568,5575,5585,5596,5602,5620,5627,5644,5647,5660,5678,5680,5684,5692,5700,5711,5727,5733,5736,5756,5776,5797,5805,5804,5807,5800,5808,5814,5822,5839,5856,5869,5889,5902,5919,5921,5936,5937,5936,5957,5961,5975,5981,6002,6015,6027,6035,6042,6059,6062,6080,6081,6092,6097,6106,6127,6129,6198,6227,6231,6243,6249,6262,6255,6279,6304,6315,6326,6330,6334,6361,6358,6359,6379,6381,6389,6388,6404,6404,6443,6465,6473,6497,6500,6513,6524,6532,6538,6578,6572,6576,6584,6582,6608,6639,6656,6761,6764,6768,6772,6836,6905,6916,6925,6951,6984,7009,7072,7092,7110,7122,7140,7148,7170,7168,7180,7194,7247,7374,7391,7393,7382,7425,7485,7530,7568,7587,7602,7602,7715,7771,7900,8004,8103,8153,8162,8296,8319,8437,8566,8746,8860,8913,9128,9275,9585,9739,10014,10123,10167,10203,10288,10323,10398,10544,10721,10883,11044,11157,11442,11515,11787,12070,12269,12468,12484,12619,12883,13008,13264,13317,13549,13859,14049,14175,14360,14498,14687,14843,14984,15093,15279,15431,15623,15741,15788,15966,16025,16132,16419,16568,16791,16892,17060,17269,17598,17959,18194,18482,18804,19136,19564,19990,20249,20509,20943,21248,21539,21845,22196,22412];class ve{static FIRST_ORBIT="1957-10-04";static EARTH_RADIUS_KM=6371;static LOW_ORBIT_KM=500;static shadowHeightKm(e){if(e>=0)return 0;const t=-e*Math.PI/180;return ve.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>ve.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return wr.filter(i=>{const s=Date.parse(`${i.from}T00:00:00Z`),n=i.to===void 0?1/0:Date.parse(`${i.to}T23:59:59Z`);return t>=s&&t<=n})}static trackedInOrbitAt(e){const t=e.getUTCFullYear()*12+e.getUTCMonth()-yr;if(!(t<0))return ds[Math.min(t,ds.length-1)]}static visibilityAt(e,t){const i=V("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:i,shadowHeightKm:ve.shadowHeightKm(i),lowOrbitLit:ve.isLitOverhead(ve.LOW_ORBIT_KM,i),classes:ve.classesAt(e),trackedObjects:ve.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${ve.FIRST_ORBIT}T00:00:00Z`)}}}const kr="https://ufoathome.org/light-pollution/index.json";class $e{year=2015;citation="World Atlas of the artificial night sky brightness (Falchi et al. 2016, doi:10.1126/sciadv.1600377; data doi:10.5880/GFZ.1.4.2016.001, CC BY-NC 4.0)";static NATURAL_MCD=.171168;fetchImpl;indexUrls;index;tiles=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??$e.defaultIndexUrls()}static defaultIndexUrls(){const e=typeof location>"u"?void 0:new URL("/light-pollution/index.json",location.href).href;return[...new Set([e,kr].filter(t=>t!==void 0))]}static magPerArcsec2Of(e){return-2.5*Math.log10((e+$e.NATURAL_MCD)/108e6)}static mcdOf(e,t){return e===0?0:t.floorMcd*10**((e-1)/t.subdivisions)}async lookUp(e,t){const i=await this.loadIndex();if(!i)return{status:"failed"};const{index:s,base:n,present:r}=i;if(!(e<s.north&&e>=s.south))return{status:"outside"};const o=((t+180)%360+360)%360-180,a=Math.floor((s.north-e)/s.tileDeg),d=Math.floor((o+180)/s.tileDeg),l=a*(360/s.tileDeg)+d;if(!(r[l>>3]&1<<(l&7)))return{status:"natural"};const h=s.north-a*s.tileDeg,c=-180+d*s.tileDeg,u=$e.nameOf(h-s.tileDeg,c),p=await this.tile(`${n}${u}.bin`);if(!p)return{status:"failed"};const m=s.tileDeg/s.cells,f=Math.min(s.cells-1,Math.floor((h-e)/m)),g=Math.min(s.cells-1,Math.floor((o-c)/m)),b=$e.mcdOf(p[f*s.cells+g],s);return b===0?{status:"natural"}:{status:"found",lightPollution:Math.round($e.magPerArcsec2Of(b)*100)/100,artificialMcdPerM2:b,lat:h-(f+.5)*m,lng:c+(g+.5)*m}}static nameOf(e,t){const i=`${e<0?"S":"N"}${String(Math.abs(e)).padStart(2,"0")}`,s=`${t<0?"W":"E"}${String(Math.abs(t)).padStart(3,"0")}`;return i+s}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json(),s=Uint8Array.from(atob(i.present),n=>n.charCodeAt(0));return{index:i,base:new URL(".",e).href,present:s}}catch{}})(),this.index.then(e=>{e||(this.index=void 0)}),this.index}tile(e){let t=this.tiles.get(e);return t||(t=(async()=>{try{const i=await this.fetchImpl(e);if(!i.ok||!i.body)return;const s=i.body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(s).arrayBuffer())}catch{return}})(),this.tiles.set(e,t),t.then(i=>{i||this.tiles.delete(e)})),t}}const Et=he.point("lightPollution").provide(he.BUILT_IN,[{id:"falchi-2015",name:"World Atlas 2015",credit:"Falchi et al. 2016, CC BY-NC 4.0",creditUrl:"https://doi.org/10.5880/GFZ.1.4.2016.001",create:()=>new $e}]);class P{static COARSE_STEP_DEG=10;static FINE_STEP_DEG=2;static FINE_SPAN_DEG=10;static LOWEST_DEG=5;static THRESHOLD_CONTRAST=.5;static CONE_SEPARATION_DEG=60;galaxy=new rn;dust=new on;assess(e,t,i){const s=V("Sun",e,t),n=V("Moon",e,t),r={altitudeDeg:n.altitudeDeg,phaseAngleDeg:pe.phaseAngleOf(Xe(e).illuminatedFraction)},o=Ai.galactic(e,t),a=P.unit(o.centre),d=P.unit(o.rotation),l=P.unit(o.pole),h=P.unit(Ai.eclipticPole(e,t)),c=P.unit(s),u=P.unit(n),p=P.normalize(P.reject(c,h));let m,f,g=0;const b=(v,E)=>{const x=P.unit({altitudeDeg:v,azimuthDeg:E}),S=P.between(x,c),I=pe.magPerArcsec2({altitudeDeg:s.altitudeDeg,separationDeg:S},{...r,separationDeg:P.between(x,u)},v,i);I>g&&(g=I);const C=Ci.fromMagPerArcsec2(I),R=10**(-.4*pe.EXTINCTION_PER_AIR_MASS*(pe.airMass(v)-1)),T=this.galaxy.surfaceBrightnessS10(Math.atan2(P.dot(x,d),P.dot(x,a))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,P.dot(x,l))))*180/Math.PI)*R;m=P.better(m,T,C,I,v,E,S);const Z=Math.max(-1,Math.min(1,P.dot(x,h))),Y=P.normalize(P.reject(x,h)),Ce=this.dust.surfaceBrightnessS10(P.between(Y,p),Math.asin(Z)*180/Math.PI)*R;f=P.better(f,Ce,C,I,v,E,S)};for(let v=P.LOWEST_DEG;v<=90;v+=P.COARSE_STEP_DEG)for(let E=0;E<360;E+=P.COARSE_STEP_DEG)b(v,E);for(const v of[m,f]){if(!v)continue;const E=P.FINE_SPAN_DEG,x=P.FINE_STEP_DEG;for(let S=v.altitudeDeg-E;S<=v.altitudeDeg+E;S+=x)if(!(S<P.LOWEST_DEG||S>90))for(let I=v.azimuthDeg-E;I<=v.azimuthDeg+E;I+=x)b(S,(I+360)%360)}return{milkyWay:m&&m.contrast>=P.THRESHOLD_CONTRAST?m:void 0,zodiacal:f&&f.contrast>=P.THRESHOLD_CONTRAST?f:void 0,darkestSkyMagPerArcsec2:g}}static better(e,t,i,s,n,r,o){const a=t/i;return e&&e.contrast>=a?e:{contrast:a,altitudeDeg:n,azimuthDeg:r,magPerArcsec2:Ci.toMagPerArcsec2(t),skyMagPerArcsec2:s,sunSeparationDeg:o}}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,s=Math.cos(t);return[s*Math.sin(i),Math.sin(t),-s*Math.cos(i)]}static dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}static between(e,t){return Math.acos(Math.max(-1,Math.min(1,P.dot(e,t))))*180/Math.PI}static reject(e,t){const i=P.dot(e,t);return[e[0]-i*t[0],e[1]-i*t[1],e[2]-i*t[2]]}static normalize(e){const t=Math.hypot(...e)||1;return[e[0]/t,e[1]/t,e[2]/t]}}class _{static MIN_NAME_LENGTH=3;static EMAIL=/[\p{L}\d._%+-]+@[\p{L}\d-]+(?:\.[\p{L}\d-]+)+/u;static PHONE=/(?:\+\d{1,3}[ .-]?|\b0)\d(?:[ .-]?\d{2}){4}\b|\+\d[\d ().-]{8,}\d/;static ADDRESS=new RegExp("\\b\\d{1,4}\\s?(?:bis|ter)?,?\\s+(?:rue|avenue|av\\.|boulevard|bd|chemin|impasse|allée|route|place|street|st\\.|road|rd|lane|drive|via|calle|piazza)\\b","iu");static inspect(e,t){const i=new Set((t?_.all(t):[]).map(s=>`${s.kind}:${s.found}`));return _.all(e).filter(s=>!i.has(`${s.kind}:${s.found}`))}static initialsOf(e){return e.trim().split("-").map(t=>{const i=[...t.trim()][0];return i===void 0?"":`${i.toLocaleUpperCase()}.`}).filter(t=>t!=="").join("-")}static withInitials(e,t,i=!1){let s=e;for(const n of _.usable(t)){const r=_.initialsOf(n);s=s.replace(new RegExp(_.escape(n),"giu"),i?r.replace(/[.-]/g,""):r)}return s}static namesOf(e){const t=e.observer,i=[t?.lastName,...t?.firstNames??[]];return _.usable(i.filter(s=>typeof s=="string"))}static isInitials(e){const t=e.replace(/[^\p{L}]/gu,"");return t.length>0&&t.length<=3&&t===t.toLocaleUpperCase()}static usable(e){return e.map(t=>(t??"").trim()).filter(t=>t.length>=_.MIN_NAME_LENGTH&&!_.isInitials(t))}static all(e){const t=[],i=e.observer,s=_.usable([i?.lastName]),n=_.usable(i?.firstNames??[]);for(const o of s)t.push({kind:"lastName",found:o});for(const o of n)t.push({kind:"firstNames",found:o});const r=[...s,...n];for(const o of[e.id,i?.id])for(const a of r)o&&o.toLocaleLowerCase().includes(a.toLocaleLowerCase())&&t.push({kind:"nameInId",found:`${o}`});for(const o of _.texts(e)){for(const h of r)new RegExp(`(?<![\\p{L}])${_.escape(h)}(?![\\p{L}])`,"iu").test(o)&&t.push({kind:"nameInText",found:h});const a=_.ADDRESS.exec(o)?.[0];a&&t.push({kind:"address",found:a});const d=_.EMAIL.exec(o)?.[0];d&&t.push({kind:"email",found:d});const l=_.PHONE.exec(o)?.[0];l&&t.push({kind:"phone",found:l})}return _.unique(t)}static texts(e){const t=n=>typeof n=="string"?[n]:typeof n=="object"&&n!==null?Object.values(n).filter(r=>typeof r=="string"):[],i=e.place,s=i===void 0?[]:[i.name??i.value?.name];return[...t(e.description),...t(e.summary),...t(e.account?.observerOccupation),...s.flatMap(t)]}static unique(e){const t=new Set;return e.filter(i=>{const s=`${i.kind}:${i.found}`;return t.has(s)?!1:(t.add(s),!0)})}static escape(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}const Er=.5,xt=40,xr=4e5,St=36e5,hs=25;class st{constructor(e){this.provider=e}queryOf(e){const t=this.questionOf(e);return t?{points:this.sampleTimings(e,t.start,Nt(e.event)??0).map(s=>this.pointAt(e,s,t.origin))}:void 0}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{start:i}=t,s=Nt(e.event)??0,n=this.sampleTimings(e,i,s);let r;try{r=await this.provider.getWeather(this.queryOf(e))}catch{return{status:"failed",at:i}}return r?{status:"inferred",at:i,source:r.source,keyframes:r.samples.map((o,a)=>({t:n[a].t,weather:o.weather}))}:{status:"unavailable",at:i}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const i of t.keyframes)e.weatherTrack.addKeyframe(i.t,i.weather);e.weatherSource=t.source}}sampleTimes(e,t){const i=[e],s=e.getTime()+t;let n=Math.floor(e.getTime()/St)*St+St;for(;n<=s&&i.length<hs;)i.push(new Date(n)),n+=St;return t>0&&i[i.length-1].getTime()!==s&&i.length<hs&&i.push(new Date(s)),i}sampleTimings(e,t,i){const s=e.timeline.duration>0?e.timeline.duration:i;return i<=0||s<=0?[{time:t,t:0}]:this.sampleTimes(t,i).map(n=>{const r=(n.getTime()-t.getTime())/i;return{time:n,t:Math.round(s*Math.max(0,Math.min(1,r)))}})}canInfer(e){return this.questionOf(e)!==void 0}missingOf(e){const t=e.event.time;return{date:t?.year===void 0||t.month===void 0||t.day===void 0,place:this.originOf(e)===void 0}}questionOf(e){const t=this.originOf(e);if(!t)return;const i=e.event.time;if(i?.year===void 0||i.month===void 0||i.day===void 0)return;const s=be(i,t.lng,e.event.utcOffsetHours);return s?{origin:t,start:s}:void 0}originOf(e){const t=ee(e,0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return s===void 0||n===void 0?void 0:{lat:s,lng:n}}pointAt(e,t,i){const s=ee(e,t.t);return{lat:s?.lat??i.lat,lng:s?.lng??i.lng,time:t.time}}}const Sr=Date.UTC(1940,0,1),cs=36e5,us=.25,Ir=.7,Tr=.45,Mr=.1,Lr=2,Dr=.3,Ar=.2,Cr=8,si=.125,Or=.05,ps=125,ms=100,gs=2500,ni=3500,ri=8e3,Rr=95,Pr=99,Br=[96,99],Nr=["cloud_cover","cloud_cover_low","cloud_cover_mid","cloud_cover_high","precipitation","snowfall","weather_code","wind_speed_10m","wind_direction_10m","temperature_2m","dew_point_2m"],Fr=5;class Fs{fetchImpl;baseUrl;forecastUrl;now;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive",this.forecastUrl=e.forecastUrl??"https://api.open-meteo.com/v1/forecast",this.now=e.now??(()=>new Date)}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(l=>l.time.getTime()),i=Math.min(...t);if(i<Sr)return;const s=new Map;for(const l of e.points){const h=this.cellKey(l);s.has(h)||s.set(h,{lat:l.lat,lng:l.lng,index:s.size})}const n=i>=this.now().getTime()-Fr*864e5,r=this.requestUrl([...s.values()],new Date(i),new Date(Math.max(...t)),n);let o=this.cache.get(r);if(!o){const l=await this.fetchImpl(r);if(!l.ok)throw new Error(`Open-Meteo HTTP ${l.status}`);const h=await l.json();if(o=Array.isArray(h)?h:[h],o.length<s.size||o.some(c=>c.error||!c.hourly))return;this.cache.set(r,o)}const a=n?{id:"open-meteo-forecast",name:"Open-Meteo (forecast model)",url:r}:{id:"era5",name:"ERA5 (Open-Meteo)",url:r},d=e.points.map(l=>this.sampleAt(o[s.get(this.cellKey(l)).index].hourly,l.time));if(!d.some(l=>l===void 0))return{samples:d,source:a}}cellKey(e){return`${Math.round(e.lat/us)},${Math.round(e.lng/us)}`}requestUrl(e,t,i,s){const n=new URLSearchParams({latitude:e.map(r=>r.lat).join(","),longitude:e.map(r=>r.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(i),hourly:Nr.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${s?this.forecastUrl:this.baseUrl}?${n}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const i=this.recordAt(e,t);return i&&{time:t,weather:this.toWeather(i)}}recordAt(e,t){const i=e.time.map(o=>Date.parse(`${o}Z`)),s=t.getTime();if(i.length===0||s<i[0]-cs||s>i[i.length-1]+cs)return;if(s<=i[0])return this.recordFrom(e,0);if(s>=i[i.length-1])return this.recordFrom(e,i.length-1);let n=0;for(;n+1<i.length&&i[n+1]<=s;)n++;const r=i[n+1]-i[n];return this.blendRecords(this.recordFrom(e,n),this.recordFrom(e,n+1),r>0?(s-i[n])/r:0)}recordFrom(e,t){const i={cloudCover:e.cloud_cover[t]/100,cloudCoverLow:e.cloud_cover_low[t]/100,cloudCoverMid:e.cloud_cover_mid[t]/100,cloudCoverHigh:e.cloud_cover_high[t]/100,precipitationMm:e.precipitation[t],snowfallCm:e.snowfall[t],weatherCode:e.weather_code[t],windSpeedMs:e.wind_speed_10m[t],windFromDeg:e.wind_direction_10m[t],temperatureC:e.temperature_2m[t],dewPointC:e.dew_point_2m[t]};return Object.values(i).some(s=>s===void 0||Number.isNaN(s))?void 0:i}blendRecords(e,t,i){if(!e||!t)return e??t;const s=(r,o)=>r+(o-r)*i,n=((t.windFromDeg-e.windFromDeg)%360+540)%360-180;return{cloudCover:s(e.cloudCover,t.cloudCover),cloudCoverLow:s(e.cloudCoverLow,t.cloudCoverLow),cloudCoverMid:s(e.cloudCoverMid,t.cloudCoverMid),cloudCoverHigh:s(e.cloudCoverHigh,t.cloudCoverHigh),precipitationMm:s(e.precipitationMm,t.precipitationMm),snowfallCm:s(e.snowfallCm,t.snowfallCm),weatherCode:i<.5?e.weatherCode:t.weatherCode,windSpeedMs:s(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+n*i)%360+360)%360,temperatureC:s(e.temperatureC,t.temperatureC),dewPointC:s(e.dewPointC,t.dewPointC)}}cloudLayersFrom(e){return[{id:"record-low",type:"unknown",baseM:Math.round(this.clamp(ps*(e.temperatureC-e.dewPointC),ms,gs)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:ni,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:ri,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=Rr&&e.weatherCode<=Pr,i=this.precipitationTypeFrom(e);return{cloudLayers:this.cloudLayersFrom(e),cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),highCloudCover:e.cloudCoverHigh,lowerCloudCover:Math.max(e.cloudCoverLow,e.cloudCoverMid),relativeHumidity:Math.round(an.relativeHumidity(e.temperatureC,e.dewPointC)*100)/100,precipitationType:i,precipitationIntensity:i==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/Cr),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":Br.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const i=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(i<=0)return 0;const s=(Ir*e.cloudCoverLow+Tr*e.cloudCoverMid+Mr*e.cloudCoverHigh)/i,n=Math.min(1,e.precipitationMm/Lr);return this.clamp(s+Dr*n+(t?Ar:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<Or)return;const t=this.clamp(ps*(e.temperatureC-e.dewPointC),ms,gs);if(e.cloudCoverLow>=si)return Math.round(t);if(e.cloudCoverMid>=si)return ni;if(e.cloudCoverHigh>=si)return ri;const i=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(i<=0))return i===e.cloudCoverLow?Math.round(t):i===e.cloudCoverMid?ni:ri}clamp(e,t,i){return Math.max(t,Math.min(i,e))}}function zr(){return new Fs}const Ur=5;class zs{attribution={text:"© OpenStreetMap",url:"https://osm.org/copyright"};fetchImpl;baseUrl;reverseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://nominatim.openstreetmap.org/search",this.reverseUrl=e.reverseUrl??"https://nominatim.openstreetmap.org/reverse"}async reverse(e,t,i={}){const s=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});i.language&&s.set("accept-language",i.language);const n=`${this.reverseUrl}?${s}`,r=this.cache.get(n);if(r)return r[0];const o=await this.fetchImpl(n,{signal:i.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const a=await o.json(),d=a.error?void 0:this.toMatch(a);return this.cache.set(n,d?[d]:[]),d}async search(e,t={}){const i=e.trim();if(i==="")return[];const s=this.requestUrl(i,t),n=this.cache.get(s);if(n)return n;const r=await this.fetchImpl(s,{signal:t.signal});if(!r.ok)throw new Error(`Nominatim HTTP ${r.status}`);const o=await r.json(),a=(Array.isArray(o)?o:[]).map(d=>this.toMatch(d)).filter(d=>d!==void 0);return this.cache.set(s,a),a}requestUrl(e,t){const i=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??Ur)});return t.language&&i.set("accept-language",t.language),`${this.baseUrl}?${i}`}toMatch(e){const t=e.display_name??e.name,i=this.coordinate(e.lat),s=this.coordinate(e.lon);return t&&i!==void 0&&s!==void 0?{name:t,lat:i,lng:s}:void 0}coordinate(e){if(e===void 0||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}}function _r(){return new zs}const oi=he.point("place").provide(he.BUILT_IN,[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new zs}]),ke=he.point("weather").provide(he.BUILT_IN,[{id:"era5",name:"Open-Meteo",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new Fs}]),It=k=>k.id==="open-meteo-forecast"||ke.some(e=>e.id===k.id);class fs{static of(e,t){if(!t)return e;let i,s;try{i=new URL(e),s=new URL(t)}catch{return e}if(i.origin!==s.origin||!/^https?:$/.test(i.protocol))return e;const n=s.pathname.split("/").slice(0,-1),r=i.pathname.split("/");let o=0;for(;o<n.length&&o<r.length-1&&n[o]===r[o];)o++;const a=n.length-o;return[...Array(a).fill(".."),...r.slice(o)].join("/")+i.search+i.hash}static names(e,t,i){return(e??[]).some(s=>{try{return new URL(s,i??t).href===t}catch{return!1}})}}class ct{constructor(e,t){this.root=e,this.messages=t}static STYLE=`
2722
2722
  .model-picker-button { display: inline-flex; align-items: center; gap: .5em; cursor: pointer; max-width: 100%; }
2723
2723
  .model-picker-button img { width: 2em; height: 1.5em; object-fit: contain; }
2724
2724
  .model-picker-button span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -2750,8 +2750,8 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
2750
2750
  .model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
2751
2751
  .model-picker .model-name { font-weight: 600; }
2752
2752
  .model-picker .model-credit { font-size: .8em; color: #666; }
2753
- `;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await L(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-Ckdb3qoW.js");return{ModelThumbnails:i}},__vite__mapDeps([2,3,1,4,5,6,7,8,9,10]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const s=document.createElement("button");s.type="button",s.className="model-picker-button",e.after(s),e.hidden=!0;let n=0,r;const o=()=>{const 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=>ct.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=ct.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=M.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),L(async()=>{const{ModelViewer:S}=await import("./ModelViewer-B9PZN5c7.js");return{ModelViewer:S}},__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),import.meta.url).then(({ModelViewer:S})=>S.end())},u=S=>{S.key==="Escape"&&(S.stopPropagation(),c())},p=i?.current(),m="\0address",f=S=>S===m&&p?Promise.resolve({url:p.url}):t(S),g=S=>{if(c(),s){S!==m&&s(S);return}S===m||S===e.value||(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const v=new Map,I=S=>{const O=document.createElement("button");O.type="button",O.className="model-card",O.dataset.value=S.value,O.setAttribute("aria-pressed",String(!s&&(S.value===m||S.value===e.value&&!p)));const N=document.createElement("div");N.className="model-thumb";const A=document.createElement("span");if(A.className="model-name",A.textContent=S.textContent,O.append(N,A),S.title){const k=document.createElement("span");k.className="model-credit",k.textContent=S.title,O.append(k)}f(S.value).then(k=>ct.pictureOf(k)).then(k=>{if(!k)return;const T=new Image;T.src=k,T.alt="",N.append(T)});let te,Z=!1;const Ce=()=>{Z&&!(te&&!te.active)||(Z=!0,Promise.all([f(S.value),L(()=>import("./ModelViewer-B9PZN5c7.js"),__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),import.meta.url)]).then(([k,{ModelViewer:T}])=>{!k||!Z||(te=T.show(N,k))}).catch(()=>{}))},Ge=()=>{Z=!1,te?.stop(),te=void 0};return v.set(O,Ce),O.addEventListener("pointerenter",Ce),O.addEventListener("focus",Ce),O.addEventListener("pointerleave",()=>{document.activeElement!==O&&Ge()}),O.addEventListener("blur",Ge),O.addEventListener("click",k=>{if(te?.consumeDrag()){k.preventDefault();return}g(S.value)}),O},x=()=>(b=document.createElement("div"),b.className="model-picker-grid",h.append(b),b);if(p){const S=new Option(p.title||p.url,m);S.title=[p.author,p.license].filter(Boolean).join(" — "),x().append(I(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const O=document.createElement("h3");O.textContent=S.label,h.append(O);const N=x();for(const A of Array.from(S.children))N.append(I(A));b=void 0}else S instanceof HTMLOptionElement&&(b??x()).append(I(S));i&&this.addAddressForm(l,d,o,h,i,n,c),d.addEventListener("click",c),r.addEventListener("click",S=>{S.target===r&&c()}),document.addEventListener("keydown",u,!0),this.root.append(r);const y=o.querySelector('.model-card[aria-pressed="true"]');(y??d).focus(),y&&v.get(y)?.()}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,I,x="")=>{const y=document.createElement("label"),S=document.createElement("span");S.textContent=v;const O=document.createElement("input");return O.type=I,O.placeholder=x,y.append(S,O),d.append(y),O},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 I=n.current();h.value=I?.url??"",c.value=I?.title??"",u.value=I?.author??"",p.value=I?.license??"",m.value=I?.source??"",b(),h.focus()}),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 xi{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=xi.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 Hr{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 oe{static STEP_MS=100;static plan(e){const t=oe.routeOf(e),i=Te.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const o=new Set,a=(c,u,p,m)=>{if(Math.abs(c.radiusM-m)>=m*.1)return!1;const{x:f,z:g}=Es(u,p,c.lat,c.lng);return Math.hypot(f,g)<Te.rebuildDistanceFor(m)};for(let c=0;;c=Math.min(s,c+oe.STEP_MS)){const u=Q(e,c);if(u?.lat!==void 0&&u.lng!==void 0){const p=Te.groundRadiusFor(u.elevationM??0),m=Te.patchRadiusFor(p,u.elevationM??0),f=Math.max(m,i);(!r||!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=Te.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>Te.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=Ts.map(c=>Ct.of(c)).filter(c=>c.reachM&&Ct.eventsOf(e.skyEvents,c).length>0);if(h.length>0){const c=u=>Math.max(...h.map(p=>p.reachM(Ct.eventsOf(e.skyEvents,p),u)));for(const u of[...n])u.far||o.has(u)||n.some(p=>p.far&&p.lat===u.lat&&p.lng===u.lng)||Te.needsFarRing(u.radiusM,0,c(u))&&n.push({lat:u.lat,lng:u.lng,radiusM: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=oe.routeOf(t),d=[];for(const[c,u]of i.entries()){try{const p=await s.elevation.getElevationGrid(dt.boundsOf(u),{width:Bi,height:Bi},{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 ln.encode({takenOn:r,attribution:l,patches:d}),attribution:l,takenOn:r,answered:d.length,patches:i.length}}case"imagery":{const a=new Oi,d=U(lt,s.imagery),l=d.create(a.fetch);let h=0;for(const[p,m]of i.entries()){try{await l.getImageryTexture(dt.boundsOf(m),{width:Ri,height:Ri}),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 Pi.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 oe.vector(s.roads,i,r,o,(a,d)=>a.getRoads(d),a=>a.contemporary);case"water":return oe.vector(s.water,i,r,o,(a,d)=>a.getWater(d));case"railways":return oe.vector(s.railways,i,r,o,(a,d)=>a.getRailways(d),a=>a.contemporary)}}static mapGround(e){const t=dn.of(e);return t&&Ni.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=oe.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Oi,r=U(lt,t),o=r.create(n.fetch),a=Ni.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 Pi.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<=Te.ROADS_MAX_RADIUS_M)try{o.push({...h,items:await n(e,dt.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 X.isLive(this.host.sighting().snapshots,e)}setLive(e,t){if(this.isLive(e)===t)return;const i={...this.host.sighting().snapshots??{}};if(i.live){delete i.live;for(const n of X.NAMES)i[n]={...i[n]??{},live:!0}}const s={...i[e]??{}};t?s.live=!0:delete s.live,i[e]=Object.keys(s).length>0?s:void 0,this.setSnapshots(i)}show(e){this.shown=e,this.render()}render(){if(!this.messages)return;const e=this.shown,t=this.isLive(e),i=this.annex(e),s=this.root.querySelector("#snapshot-state");s.textContent=t?this.messages.snapshotLiveState:i&&!i.refresh?[this.messages.snapshotTakenOn.replaceAll("{date}",i.takenOn??"?"),i.attribution].filter(Boolean).join(" · "):this.messages.snapshotPending;const n=this.root.querySelector("#snapshot-refresh");n.disabled=this.busy||t;const r=i!==void 0&&!i.refresh&&!t,o=r&&j.isInline(i.src);this.sourceInput.url=r?o?this.host.masterUrl():this.address(i.src):"",r||(this.sourceInput.mode="file"),this.sourceInput.disabled=this.busy||t,this.root.querySelector("#annex-export").disabled=i===void 0||this.busy,this.renderEditor(r&&!o?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!j.isZip(t)?await this.textOf(e).catch(()=>{}):void 0;if(t!==this.shown||(this.editorHost.hidden=i===void 0,i===void 0))return;const s=`${t}|${e.src}`;if(this.editor&&this.editorFor===s)return;if(this.editorFor=s,this.editor){this.editor.replaceText(i,!1);return}const{SightingFileEditor:n}=await L(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:r}},__vite__mapDeps([12,13,14]),import.meta.url);if(t!==this.shown||!this.editorHost.isConnected){this.editorFor=void 0;return}this.editor??=new n(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const s={...this.host.sighting().snapshots??{}};let n;try{n=await this.bytesAt(t.url)}catch{n=void 0}if(n!==void 0)try{s[e]={src:t.url,...await j.describe(e,n)}}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}le.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}F.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await L(async()=>{const{InputFileElement:s}=await import("./rr0-ufoathome.mjs").then(n=>n.J);return{InputFileElement:s}},[],import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const s={...this.host.sighting().snapshots??{}},n=this.annex(e);let r;try{r=await j.describe(e,t)}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}const o=n!==void 0&&j.isInline(n.src),a=o?j.dataUrl(e,t):n?.src??X.annexName(this.host.base(),e);o||le.hold(this.address(a),t),s[e]={...s[e]?.live?{live:!0}:{},src:a,...r},F.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=X.annexName(this.host.base(),e),le.hold(this.address(r),n)),i[e]={...s,src:r},this.editorFor=`${e}|${r}`,this.setSnapshots(i)}async exportAnnex(e){const t=this.annex(e);if(!t)return;const i=await this.bytesOf(t),s=j.isInline(t.src)?X.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:j.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(j.isZip(e)){const{unzipSync:s}=await L(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 le.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,oe.plan(this.host.sighting()),this.host.sources(),s))?F.show(this.note,void 0):F.show(this.note,this.messages.snapshotFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setSnapshots(t)}hasWork(){const e=this.host.sighting();return X.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||oe.plan(e).length>0:!0}async prepare(e){const t=this.host.sighting(),i={...t.snapshots??{}},s=new Map;this.busy=!0,this.render();try{const n=h=>X.isLive(i,h),r=h=>i[h]?.src!==void 0?i[h]:void 0;for(const h of X.NAMES)!i.live&&i[h]?.live&&(i[h]={live:!0});const o=oe.plan(t);let a;for(const h of X.TERRAIN){if(n(h))continue;const c=r(h);if(o.length>0&&(!c||c.refresh||!await this.fits(h,c,o))&&await this.take(h,i,o,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");oe.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 oe.freeze(e,this.host.sighting(),i,s,(a,d)=>F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(a)).replaceAll("{of}",String(d))));return F.show(this.note,void 0),o?(t[e]={src:this.place(e,t[e]?.src,n,o.bytes),takenOn:o.takenOn,attribution:o.attribution},!0):!1}async takeMap(e,t,i){F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await oe.freezeMap(this.host.sighting(),t.imagery);return F.show(this.note,void 0),s?(e.map={src:this.place("map",e.map?.src,i,s.bytes),takenOn:s.takenOn,attribution:s.attribution},!0):!1}async fitsMap(e){const t=oe.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await le.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&dt.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 le.zip(s))["index.json"])).patches:(await le.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(o=>o.radiusM<=Te.ROADS_MAX_RADIUS_M);return dt.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??X.annexName(i,e);return le.hold(this.address(n),s),n}async keep(e,t){if(!j.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return le.bytes(this.address(e.src))}address(e){return le.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of X.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=X.isEmpty(e)?void 0:e,this.render(),this.host.changed()}destroy(){clearTimeout(this.editTimer),this.editor?.destroy(),this.editor=void 0,this.editorFor=void 0}static baseOf(e){return e?.match(/^(.*)\.[a-z-]+\.(zip|json)$/)?.[1]}static size(e){return e<1e6?`${Math.max(1,Math.round(e/1e3))} kB`:`${(e/1e6).toFixed(1)} MB`}groupName(e){return{relief:this.messages.snapshotRelief,imagery:this.messages.snapshotImagery,roads:this.messages.snapshotRoads,water:this.messages.snapshotWater,railways:this.messages.snapshotRailways,upperAir:this.messages.snapshotUpperAir,map:this.messages.snapshotMap}[e]}}class Gt{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,F.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().snapshots?.[e]?.src}itemLabel(e){const t=this.messages;return t?{weather:t.fileItemWeather,place:t.fileItemPlace,lightPollution:t.fileItemLightPollution,decor:t.fileItemDecor}[e]:""}where(e){return this.srcOf(e)??this.messages?.annexStorageInline??""}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[H.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 ut(ze.preferencesFor(this.root)).read(t.provenance.at("lightPollution")?.rationale)??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().snapshots??{}};if(t===(i[e]?.src===void 0))return;const{src:s,...n}=i[e]??{};i[e]=t?n:{...n,src:H.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=gi(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:We.CURRENT.sighting,takenOn:i,attribution:s,...H.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)??H.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},F.show(this.note,void 0),this.write(e,a);return}let i;try{const{InputFileElement:a}=await L(async()=>{const{InputFileElement:l}=await import("./rr0-ufoathome.mjs").then(h=>h.J);return{InputFileElement:l}},[],import.meta.url),d=await a.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=We.recording(JSON.parse(new TextDecoder().decode(d))),typeof i!="object"||i===null||H.KEYS[e].every(l=>i[l]===void 0))throw new Error("Not this section")}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...gi(s)};if(e==="decor")H.put(e,n,"timeline"in i?H.taken(e,i):i);else for(const a of H.KEYS[e])n[a]=i[a];const r=Ms(n);Gt.copy(e,r,s);const o={...s.snapshots??{}};t.url?o[e]={...o[e]??{},src:t.url}:o[e]=o[e]??{},F.show(this.note,void 0),this.write(e,o)}write(e,t){this.host.sighting().snapshots=X.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const s of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(s.t,s.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const s of H.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 $r{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 Wr=he.point("timeZone").provide(he.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new $r}]);class ai{static OCCUPATIONS={student:!0,worker:!0,farmer:!0,homemaker:!0,merchant:!0,business:!0,employee:!0,artist:!0,technician:!0,police:!0,pilot:!0,military:!0};static RELATIONS=["friends","family","professional","none"];static ACTIVITIES=["leisure","travelling","cultural","working"]}class K{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=K.select("observerOccupationKind");graduate=K.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=K.select("observersRelation");activity=K.select("observerActivity");factors=new Map(Vn.map(e=>[e,K.select(`strangeness-${e}`)]));labels=new Map;unit=document.createTextNode(" min");strangenessTitle=document.createElement("span");strangenessIntro=Object.assign(document.createElement("p"),{className:"section-intro"});wording;constructor(e,t,i,s){Ae.register(),e.append(this.label(this.occupationKind,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]);K.choices(this.occupationKind,"",d(Object.keys(ai.OCCUPATIONS))),K.choices(this.graduate,"",a),K.choices(this.relation,"",d(ai.RELATIONS)),K.choices(this.activity,"",d(ai.ACTIVITIES));for(const l of this.factors.values())K.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,K.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),K.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),K.choices(this.relation,e.unknown,Object.entries(e.relations)),K.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)K.choices(i,K.READ_FROM_RECORDING.includes(t)?e.fromRecording:e.unknown,[["yes",e.yes],["no",e.no]])}show(e){this.occupationKind.value=e?.observerOccupationKind??"",this.graduate.value=K.yesNo(e?.observerGraduate),this.enquiryMinutes.value=e?.enquiryMinutes?.toString()??"",this.relation.value=e?.observersRelation??"",this.activity.value=e?.activity??"";for(const[t,i]of this.factors)i.value=K.yesNo(e?.strangeness?.[t])}values(){const e=this.enquiryMinutes.value.trim()===""?void 0:Number(this.enquiryMinutes.value),t={};for(const[i,s]of this.factors){const n=K.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:K.boolean(this.graduate.value),enquiryMinutes:e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0,observersRelation:this.relation.value||void 0,activity:this.activity.value||void 0,strangeness:Object.keys(t).length>0?t:void 0}}label(e,t){const i=document.createElement("label"),s=document.createElement("span");return i.append(s," ",e),this.labels.set(s,()=>{if(!this.wording)return;const[n,r]=t(this.wording);Ae.say(s,n,r)}),i}static select(e){return Object.assign(document.createElement("select"),{id:e})}static choices(e,t,i){const s=e.value;e.replaceChildren(new Option(t,""),...i.map(([n,r])=>new Option(r,n))),e.value=s}static yesNo(e){return e===void 0?"":e?"yes":"no"}static boolean(e){return e===""?void 0:e==="yes"}}const Tt=new Set;Ls();Tn();Ds.register();const Ze={width:48,height:28},jr=2500,Mt=40,Lt=10,Gr=30,Kr=10,bs=600,vs=900,Ye=2e-4,Vr=900,qr=-1.46,Zr=3,li=.2,Yr=.5,Jr=3,Xr=.01,Qr=1.6,di=2e3,eo=250,ws=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),to=1,io=5,so=10,Pe=4,nt="ufo-1",no={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function ro(E){return E.kind==="oval"?"oval":"polygon"}const oo=-6,ao=21;class w extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=Wr[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new Hr;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=_r();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 st(zr());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?hn.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 Zt;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=je.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...no};currentSourceId=nt;selectedSourceIds=new Set([nt]);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(ws.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;ws.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>${lr}</style>${ar}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const l of this.shadow.querySelectorAll(Ft))l.build();for(const l of this.shadow.querySelectorAll(Wt))l.build();for(const l of this.shadow.querySelectorAll(Si))l.build();for(const l of this.shadow.querySelectorAll(Ii))l.build();this.sceneElement=document.createElement(cn),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 ht(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(Wt),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 C(this.shadow);const t=this.shadow.getElementById("section-index");this.sectionFolds.indexIn(t,()=>this.groupPanels?.find(l=>!l.hidden)),this.sectionIndexResize=new $e(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 Bs({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=un.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new yi(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 Ns(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 K(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${Ii}[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 Gt(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 xe(this.shadow.getElementById("events-section"),s,void 0),this.phenomenonEventsPanel=new xe(this.shadow.getElementById("phenomenon-events-section"),s,void 0,"phenomenon"),this.bodiesEventsPanel=new xe(this.shadow.getElementById("bodies-events-section"),s,void 0,"bodies"),this.aroundPanel=new ir(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,ue.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 dr(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 fe({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind: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 fe({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect: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 ie(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 L(async()=>{const{SurroundingsSources:c}=await import("./surroundingsSources-Dg6vMWL7.js");return{SurroundingsSources:c}},__vite__mapDeps([15,1,3,4,5,6,7,8,9]),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 pi(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 ct(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 ot(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 ot(this.decorBaseHost,"en","decorBase.",n,(l,h)=>this.enhanceDecorModelChoice(l,h)),this.decorStateForm=new ot(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(pn,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(mn,()=>{const l=this.currentReference();l&&this.syncReferenceStatus(l)}),this.sceneElement.addEventListener(gn,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(fn,()=>{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 pi(this.addShapeButton,"add-shape-kind",l=>{const h=Me.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,Oe.fovOf(this.ufoElement.sighting,c.t)]));this.retuneFieldOfView(l),this.retuneExposure(l),Oe.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(`${Ft}[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=ft.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(),Bt.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=Qn(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()},ci(ze.preferencesFor(this),ui),this.framePlace()),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&(this.ready=this.loadLocaleMessages())}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),ze.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=this.loadLocaleMessages()),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving),he.changes.addEventListener("change",this.onModulesChanged),L(async()=>{const{ModuleSession:t}=await import("./ModuleSession-ClSpEZMn.js");return{ModuleSession:t}},__vite__mapDeps([16,1,3,4,5,6,7,8,9]),import.meta.url).then(({ModuleSession:t})=>t.shared.start(),()=>{});const e=this.getAttribute("src");e&&this.importFromUrl(e)}relisters=[];onModulesChanged=e=>{for(const i of this.relisters)i();const t=e.detail;t==="weather"&&(this.followWeatherRecord(),this.fillWeatherProvider()),t==="surroundings"&&this.surveyIds&&this.fillScenerySources(),t==="decorModels"&&this.sceneElement.setDecorModelProvider(this.decorModelProvider),(t==="skyEvents"||t==="interpretations")&&this.buildSkyParts(),t==="perception"&&(this.perceptionSettings.providers=ft.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),he.changes.removeEventListener("change",this.onModulesChanged),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),clearTimeout(this.moduleNamingTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){const t=We.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]??nt,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:()=>`${fi.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let s="";i?.year!==void 0&&(s=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const n=[t,s].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==n&&(r.textContent=n)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.scheduleModuleNaming(),this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons(),this.refreshEditorHead())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons(),this.refreshEditorHead())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=this.shadow.getElementById("save-refused"),t=q.issues(this.ufoElement.sighting);if(F.show(e,t.length===0?void 0:this.messages.saveRefused.replace("{reasons}",t.map(s=>this.actorIssue(s)).join(" ; ")),"error"),t.length>0)return;const i=_.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=_.namesOf(this.sightingData);this.observerLastNameInput.value=_.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>_.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=_.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=_.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=_.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 H.NAMES){const o=this.sectionFilePanel.annex(r);o&&(/^[a-z][a-z0-9+.-]*:/i.test(o.src)||t.set(o.src,o.bytes),H.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 L(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"),...H.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...X.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,w.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=X.NAMES.includes(e),i=H.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||fe.glue(o)}t&&this.snapshotsPanel.show(e),i&&this.sectionFilePanel.show(i);const n=t&&this.snapshotsPanel.isInlineGroup(e)?["snapshots",e,"src"]:i&&this.sectionFilePanel.isInline(i)?Gt.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 Zt)||he.installed().length===0)return;const t=this.ufoElement.sighting,i=new Set([...t.decor.map(r=>r.model?.id),...(t.interpretation?.bodies??[]).map(r=>r.model?.id)].filter(r=>typeof r=="string")),s=this.sceneElement.documentUrl;let n=t.modules;for(const r of i){const o=await e.moduleOf(r),a=o===void 0?void 0:he.installed().find(d=>d.id===o)?.url;!a||fs.names(n,a,s)||(n=[...n??[],fs.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??=L(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-D4Hos-mF.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([17,1,16,3,4,5,6,7,8,9,18,19,20,21,22,23,24]),import.meta.url).then(({register:e,ModulesPanelElement:t})=>{e();const i=this.shadow.getElementById("modules-panel");this.modulesPanel=i,i.addEventListener("recordingmoduleschange",()=>{const s=i.recordingModules;this.ufoElement.sighting.modules=s.length>0?s:void 0,this.syncFileEditor(!1)}),i.checkContext=()=>({weatherQuery:this.weatherInference.queryOf(this.ufoElement.sighting),interpretation:this.ufoElement.sighting.interpretation}),i.setLanguage(this.language),this.syncModulesPanel()}),this.modulesPanelLoading}syncModulesPanel(){this.modulesPanel&&(this.modulesPanel.base=this.sceneElement.documentUrl,this.modulesPanel.recordingModules=this.ufoElement.sighting.modules)}sectionFromFile(e){return H.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=U(bt,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:U(lt,this.chosenSourceId.get("imagery")).id,roads:wn(),water:vn(),railways:bn()}}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)}));le.release();const i=await this.recordingText(t),s=JSON.parse(i);if(se.isCase(s)){if(se.check(s),this.offerCase(s,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=s,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){this.showLoadError(t)}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await L(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)&&le.hold(le.address(h.slice(o.length),void 0),c);const a=i(s[r]),d=JSON.parse(a);let l=!1;for(const h of H.NAMES){const c=d.snapshots?.[h]?.src,u=c!==void 0?s[o+c]:void 0;if(!u)continue;const p=We.recording(JSON.parse(i(u)));H.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 Xe.recording(e);if(se.isCase(t)){se.check(t);const s=new URL(e,location.href).href;if(this.offerCase(t,s)){this.importInput.url=s;return}throw new Error("A case has no recording to edit here")}const i=t;le.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=_e.local(e)?void 0:new URL(e,location.href).href,this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){this.showLoadError(t)}}loadError;showLoadError(e){this.loadError=e===void 0?void 0:{error:e},this.sayLoadError()}sayLoadError(){F.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof Rt)return e.said(this.messages.formatVersionError);if(!(e instanceof $s))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=yt[0].create();get narrativeSourceId(){return U(yt,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 ce&&i.kind==="cancelled";this.narrativeStatus.textContent=s?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!s)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:s,...n}=i,r=i.timeZone?n:i,o=Ee.stated(r);if(o.length>0){const a=this.ufoElement.sighting.provenance,d=Fi(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=Ee.apply(d,Ht.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(Fi(this.ufoElement.sighting),n.path)})}static valueAt(e,t){let i=e;for(const s of t.split(".")){if(typeof i!="object"||i===null)return;i=i[s]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(s=>s.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[lo[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=U(yt,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 ce))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}static pageCredentials=new Map;static forgetCredentials(){w.pageCredentials.clear(),Yt.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(U(oi,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",Kn,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(U(Et,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",yt,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",oi,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",Et,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",bt,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",lt,()=>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",zi,()=>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=U(t,r.value);Yt.set(f.id,c.value),i(f,!0)});const p=()=>{const f=r.value===w.FILE_SOURCE,g=U(t,f?a():r.value);h.hidden=f||!g.keyUrl,u.href=g.keyUrl??"",c.value=Yt.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(U(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(U(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),d,l,h),n}aircraftPicker(){const e=this.sourcePicker("aircraft",Ui,(t,i)=>this.applyAircraftSource(i));return e.append(this.aircraftStatus),this.showAircraftStatus(),e}get aircraftTabOpen(){return this.isGroupIdOpen("group-weather")&&this.shadow.getElementById("weather-aircraft")?.hidden===!1}showAircraftFlights(){if(this.aircraftTabOpen){if(this.ufoElement.playbackState==="playing"){const e=performance.now();if(e-this.aircraftFlightsShownAt<1e3)return;this.aircraftFlightsShownAt=e}this.aircraftFlights.show(this.sceneElement.aircraftFlights,this.messages)}}aimAtFlight(e){if(e.key===this.aircraftFlights.selectedKey){this.aircraftFlights.select(void 0,this.messages),this.sceneElement.markFlight(void 0);return}if(!e.sky&&e.firstMs===void 0)return;const t=e.sky?this.ufoElement.currentTime:e.firstMs;e.sky||this.goToMark(t),this.sceneElement.lookAtFlight(e.key,t),this.aircraftFlights.select(e.key,this.messages),this.sceneElement.markFlight(e.key),this.showAircraftFlights()}showAircraftStatus(){this.showAircraftFlights();const{status:e,problem:t,partial:i,creditsSpent:s,total:n}=this.sceneElement.aircraftState,r=[];e==="loading"&&r.push(this.messages.aircraftLoading),e==="outside"&&r.push(this.messages.aircraftOutside),e==="byHand"&&r.push(this.messages.aircraftByHand),e==="unavailable"&&!t&&r.push(this.messages.aircraftProblems.network),e==="ready"&&n===0&&r.push(this.messages.aircraftNone),i&&r.push(this.messages.aircraftPartial.replace("{traced}",String(i.traced)).replace("{seen}",`${i.seen}${i.moreSeen?"+":""}`).replace("{km}",String(i.withinKm))),s&&r.push(this.messages.aircraftCredits.replace("{credits}",String(s))),t?F.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):F.show(this.aircraftStatus,r.length>0?r.join(" "):void 0,"info")}groupChoice(e){return{item:e[0],fromFile:()=>!this.snapshotsPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.snapshotsPanel.setLive(i,!t)},label:()=>this.snapshotsPanel.itemLabel(e[0]),where:()=>this.snapshotsPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const s={...this.ufoElement.sighting.snapshots??{}};i?s[e]=s[e]??{}:delete s[e],this.ufoElement.sighting.snapshots=X.isEmpty(s)?void 0:s,this.touch(),this.scheduleFileSync(),this.refreshFileItems(),i||t()},label:()=>this.sectionFilePanel.itemLabel(e),where:()=>this.sectionFilePanel.where(e)}}static FILE_SOURCE="file";filePickers=new Map;syncFilePickers(){for(const e of this.filePickers.values())e()}openFileItem(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-file");t&&this.toggleGroup(t,!0),this.fileItemSelect.value=e,this.showFileItem(e)}static LIVE_ROADS={id:"ign-osm",name:"IGN BD TOPO / OpenStreetMap",credit:"© IGN, BD TOPO (Licence Ouverte 2.0) in France; © OpenStreetMap contributors (ODbL) elsewhere",creditUrl:"https://www.openstreetmap.org/copyright",create:()=>{}};static LIVE_WATER=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(U(oi,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(U(Et,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:U(bt,this.chosenSourceId.get("elevation")).create(),imagery:U(lt,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(U(Ui,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new Zt(U(zi,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)<Ye&&Math.abs(i-this.namedCoordinates.lng)<Ye||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),vs))}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)<Ye&&Math.abs(i-s.lng)<Ye||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),vs))}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?ye.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),f=this.numberOrUndefined(this.fNumberInput.value),g=this.filterSelect.value,b=ae.byId(a.getLatestPoseAt(d-1)?.filter),v=g===ae.NONE.id||g===""?b===ae.NONE?void 0:ae.NONE.id:g,I=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=I===u.exposureSeconds?void 0:I;const x=this.numberOrUndefined(this.focusDistanceInput.value),y=Math.abs(m-ye.fieldOfViewDeg(u))>.01||f!==u.fNumber||x!==void 0||v!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&c===0&&!y?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:x,filter:v});const O=this.stringOrUndefined(this.placeNameInput.value.trim()),N=a.getInterpolatedPoseAt(0);o.place=e!==void 0&&t!==void 0?[{lat:N?.lat??e,lng:N?.lng??t,name:O}]:void 0;const A=this.plantingCentre();this.surroundings.placeChanged(A?.lat,A?.lng),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!kt.isFirm(t))return;const s=kt.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&&kt.at(i,e)===t)return;const s=kt.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&&Nt({...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:ft.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={...re(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...re(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(s=>s.id===this.currentReferenceId),t=e!==void 0;fe.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const s of[this.referenceSelect,...this.referenceFields])s.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.syncVideoFields(e),this.showRegistration(this.registrationShown(e)),this.syncReferenceStatus(e)}syncVideoFields(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.referenceVideoFromInput.value=e.video?.fromS===void 0?"":String(e.video.fromS),this.referenceVideoToInput.value=e.video?.toS===void 0?"":String(e.video.toS),this.referenceVideoRateInput.value=e.video?.rate===void 0?"":String(e.video.rate),this.syncReferenceKeyButton(e)}syncReferenceKeyButton(e){this.referenceRemoveKeyButton.hidden=e.kind!=="video"||Re.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=Re.registrationAt(e,this.ufoElement.currentTime);return{headingDeg:this.rounded(t),pitchDeg:this.rounded(i),rollDeg:s===void 0?void 0:this.rounded(s),fovDeg:this.rounded(n)}}showRegistration({headingDeg:e,pitchDeg:t,rollDeg:i,fovDeg:s}){this.referenceHeadingInput.value=String(e),this.referencePitchInput.value=String(t),this.referenceRollInput.value=String(i??0),this.referenceFovInput.value=String(s)}syncVideoRegistrationFields(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);e?.kind==="video"&&(this.syncReferenceKeyButton(e),e.registrationTrack?.length&&this.showRegistration(this.registrationShown(e)))}removeReferenceKey(){const e=this.ufoElement.sighting.references.find(i=>i.id===this.currentReferenceId);if(!e)return;const t=Re.withoutKey(e,this.ufoElement.currentTime);this.ufoElement.sighting.references=this.ufoElement.sighting.references.map(i=>i===e?t:i),this.syncReferenceFields(),this.ufoElement.refresh()}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(F.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>xr?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)||xt))},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?Re.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=Q(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(Re.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=Q(this.ufoElement.sighting,this.ufoElement.currentTime);return e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0}addReference(e,t,i={}){const s=this.ufoElement.sighting,n=Q(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:Er,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:xt},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=Re.kindOfSource(e.file?{type:e.file.type}:{url:e.url});s.references=s.references.map(r=>r.id!==t?r:{...r,src:i,kind:n==="video"||n==="photo"&&r.kind==="video"?n:r.kind,from:n==="video"?void 0:r.from,title:r.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=L(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-LxhNTA4v.js");return{PictureRegistration:e}},__vite__mapDeps([25,3,1,4,5,6,7,8,9]),import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);return e?.registrationTrack?.length?{...e,registration:Re.registrationAt(e,this.ufoElement.currentTime)}:e}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const s=this.pictureAspect(t.id);if(!(s!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,s)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const s=8;for(const n of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(n.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=s)return{landmarkId:n.id,end:"picture"};const o=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=s)return{landmarkId:n.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const s=i.x-t.startPointer.x,n=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(s,n)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+s*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-n*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const s=this.currentReference(),n=s?this.pictureAspect(s.id):void 0;if(!s||n===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:this.pictureRegistration.aimOf(r)};const 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)||xt,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);fe.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=s===void 0,this.referenceLandmarkLabelInput.disabled=s===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(s?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),s=i.findIndex(o=>o.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const o=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.pictureAspect(t.id);if(i===void 0)return;const{registration:s}=t,n=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o,s,i))),r=this.currentLandmarks().map((o,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(Re.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=Q(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),i=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const s=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.addReferenceButton.disabled=!0;try{this.streetPictures$??=new(await L(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:xt}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;fe.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t;this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(s=>s.id!==this.currentTraceId?s:{...s,title:this.said.write(s.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(s.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(s=>s.value===this.currentTraceId),i=e.traces.find(s=>s.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{TraceImport:l}=await L(async()=>{const{TraceImport:h}=await import("./TraceImport-CntRHXoJ.js");return{TraceImport:h}},__vite__mapDeps([26,1]),import.meta.url);i=await l.fromBytes(await Ws.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 L(async()=>{const{GEO_EXPORT_TEXTS:o}=await import("./GeoExportTexts-3a51cuxQ.js");return{GEO_EXPORT_TEXTS:o}},__vite__mapDeps([27,1]),import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:o}=await L(async()=>{const{KmlExport:d}=await import("./KmlExport-De-2dnYz.js");return{KmlExport:d}},__vite__mapDeps([28,29,5,6,1,4,3,7,8,9]),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 L(async()=>{const{GeoJsonExport:o}=await import("./GeoJsonExport-Czm1iAIW.js");return{GeoJsonExport:o}},__vite__mapDeps([30,29,5,6,1,4,3,7,8,9]),import.meta.url),r=n.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([r],{type:"application/geo+json"}),`${t}.geojson`)}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of Pn){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(),jr)}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=Bn(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 st(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===w.FILE_SOURCE;if(!e){const t=U(ke,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new st(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(H.fromFile(t.snapshots,"weather")===e)return;const i={...t.snapshots??{}};e?i.weather={...i.weather??{},live:void 0}:delete i.weather,i.weather&&i.weather.live===void 0&&delete i.weather.live,t.snapshots=X.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=ke.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==U(ke,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new st(e.create())}else!e&&t!==void 0&&!ke.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new st(U(ke,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...ke.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&&!It(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:U(ke,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=U(ke,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&&!It(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),bs))}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||!It(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&&It(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const s=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s,this.syncWeatherProvider();const n=t&&e!==void 0;if(this.weatherSourceLink.hidden=!n,n){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=[e.name,this.observationInstantLabel()].filter(Boolean).join(", ");return}const r=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&be(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherLookupResult=void 0,this.followWeatherRecord(),this.weatherFromRecords=!H.fromFile(e.snapshots,"weather")&&(e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0),this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=Et[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),bs)}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=Nt(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=Nn(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?Jt.MUTED:Jt.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(),M.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(at.opensPrecise(e.time)),this.endDate.setPrecise(at.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)>Zr;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),Vr))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ye&&Math.abs(e.lng-i)<Ye}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=U(bt,this.chosenSourceId.get("elevation")),n=await new xi(s.create()).at(e,t);if(i!==this.groundElevationToken||n===void 0)return;this.groundElevationFor={lat:e,lng:t};const r=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(n);const o=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime)?.altitudeM;this.syncElevationField(r,o)}syncElevationField(e,t){const i=this.groundElevationM;this.elevationInput.value=String(Math.round(t??(i??0)+e)),this.elevationInput.min=i===void 0?"":String(i),this.elevationInput.title=i===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=i===void 0||Math.round(e)===0?"":this.messages.groundAt.replace("{m}",String(i))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0;const e=Q(this.ufoElement.sighting,0);this.syncElevationField(e?.elevationM??0,e?.altitudeM),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncObserverMetadataFields(){this.witnessErrorView?.refresh();const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=this.said.read(e.observer?.title)??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.observerList.rename(w.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(at.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.evaluationFields.show(e.account),this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.skySourcesInput.checked=e.skySources!==!1,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=re(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??bi)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??Fn)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),s!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),s!==this.elevationInput&&this.syncElevationField(t?.elevationM??0,t?.altitudeM)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,n=i.getInterpolatedShapeAt(s,this.currentSourceId),r=this.buildAppearanceShape(e??n?.bounds??this.defaultBounds(),n,t);this.commitShapes(s,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const s=es(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 L(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:t}},__vite__mapDeps([12,13,14]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const s=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(s!==void 0){this.fileFocus="shape",this.selectUnit(s.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(s=>s.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,s]of t.entries()){const n=s.shapes.findIndex(r=>r.sourceId===e);if(n>=0)return["timeline","keyframes",i,"shapes",n]}}showFileNote(e,t="info"){F.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of H.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&H.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of H.NAMES){const n=H.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||H.put(s,e,H.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return ns.of(e,t,t==="thin"?Oe.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(w.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(w.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Ms(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=ns.of(this.ownJson(gi(e)),t,t==="thin"?Oe.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){if(t.edited)try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i))return;const s=JSON.stringify(i.weatherTrack);if(i=this.withAnnexed(i),!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,r=!t&&this.fileTextApplied!==void 0&&s!==JSON.stringify(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()):ke.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 Rt?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=Oe.fovOf(i,s),h=2*Xt.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 ne({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=be(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=>Ve(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=>Xe.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||Dt.computes(d,At.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=be(i.time,s.lng,i.utcOffsetHours);l&&(t.sunAltitudeDeg=V("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=re(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,I=Math.sin(g.altitudeDeg*v)*Math.sin(b.altitudeDeg*v)+Math.cos(g.altitudeDeg*v)*Math.cos(b.altitudeDeg*v)*Math.cos((g.azimuthDeg-b.azimuthDeg)*v);return Math.acos(Math.max(-1,Math.min(1,I)))/v},p=h.slice(1).map((g,b)=>({deg:u(h[b].shape.aim,g.shape.aim),s:(g.t-h[b].t)/1e3}));t.sweepDeg=u(h[0].shape.aim,h[h.length-1].shape.aim);const m=p.reduce((g,b)=>g+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const f=(h[h.length-1].t-h[0].t)/1e3;if(f>0){t.speedDegPerS=m/f;const g=Math.max(...p.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const o=new Set(n.sourceIds.map(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"?ue.observerTrackIsExpanded(t):ue.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||!ue.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=Jt.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=At.kinds();if(Dt.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Dt.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),Is.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 yn(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(`
2754
- `)}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&&fe.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=e?t:this.fieldHints.get(i.id)??""}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:ro(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,ge.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,ge.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(ge.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(ge.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!s)return;const n=this.currentProjection(),r=n.degToPx(e),o=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),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={[ae.NONE.id]:this.messages.filterNone,[ae.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[ae.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==ae.ALL.length||ae.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||ae.NONE.id;this.filterSelect.replaceChildren();for(const r of ae.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||ae.usableWith(ae.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=ye.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=ye.CATEGORIES.map(r=>({label:s[r],children:zn.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=Q(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??ye.fieldOfViewDeg(t),r=s?ye.focalLengthMmFor(t,n):n;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=s?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=s?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=s!==void 0&&s.focalRangeMm===void 0,this.focalLengthInput.min=String(s?s.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(s?s.focalRangeMm?.maxMm??2e3:179),Bt.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,kn.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=vt.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=ae.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=ye.fieldOfViewDeg(e),s=ye.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>Xr||t.observerTrack.addKeyframe(n.t,{...n.pose,fovDeg:s})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,s=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!s){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(s.max,Math.max(s.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return Q(e,this.ufoElement.currentTime)?.fovDeg??ye.fieldOfViewDeg(e.instrument)}currentProjection(){return Xt.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=ge.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const s=Q(this.ufoElement.sighting,this.ufoElement.currentTime),n=s?.focusDistanceM;if(n!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(n));return}const r=(s?ye.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,o=s?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const a=this.ufoElement.canvasElement.height;if(a<=0)return;const d=2*En*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)??Kr,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(ge.sizeMAt(d,l),2),lengthM:s(ge.sizeMAt(d,l),2),heightM:s(ge.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??=L(async()=>{const{BodyEditor:e}=await import("./BodyEditor-BwsMj37A.js");return{BodyEditor:e}},__vite__mapDeps([31,3,1,4,5,6,7,8,9,18,20]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,bodySelected:()=>this.bodiesEventsPanel.render(),said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},duration:()=>this.ufoElement.seekableDuration,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,s)=>this.sceneElement.groundAlong(t,i,s)},this.language),this.bodyEditor)),this.bodyEditorLoading}openSkyParts(){return[...this.skyParts.values()].filter(e=>!e.panel.hidden)}wantedSkyParts(){const e=At.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=Ts.map(i=>Ct.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=M.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(ft.ALL.map(i=>i.messages))];Promise.all(t.map(i=>i.load(e))).then(i=>{this.decidedLanguage===e&&(this.perceptionSettings.labels=Object.assign({},...i))},()=>{})}nameSkyPart(e,t){const i=this.decidedLanguage;i!==void 0&&t.load(i).then(s=>{this.decidedLanguage===i&&(e.textContent=s.title)},()=>{})}loadSkyPartEditor(e){return e.loading??=e.create().then(t=>(e.editor=t(e.panel.querySelector(`#${e.id}-editor`)),e.editor)),e.loading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const n=i===void 0||i<=0?void 0:ge.sizeMAt(e.distanceM,i);this.realWidthInput.value=n===void 0?"":this.plain(n,n<1?2:n<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const s={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=s.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,s=Xt.of(i.instrument,ge.CANVAS_HEIGHT_PX,Oe.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const o=Oe.aimOf(i,e,r.shape.bounds),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},...Me.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),s=e.shapesIn(i,this.currentAppearance),n=this.newSourceIds(s.length),r=this.shapeAddKinds().find(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]??nt,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:_i.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Cs}:{},windows:Os(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 L(()=>import("./surroundingsSources-Dg6vMWL7.js"),__vite__mapDeps([15,1,3,4,5,6,7,8,9]),import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const s=document.createElement("option");s.value=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=X.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?zt.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*di,t=Math.round(e/eo*1e3);return{lights:_i.byId("airliner")?.create(),track:[{t:0,eastM:-di,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:di,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=jn(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?ts[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=Hi([...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=Hi(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;fe.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=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 L(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([32,33]),import.meta.url),i=this.messages,s={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},n=await new t(this.ghostsStatus,s).search(e.src);this.ghostFinding=n&&n.pairs.length>0?{referenceId:e.id,src:e.src,search:n}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t||e?.kind==="video",this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}syncFilmStocks(e,t){const i=vt.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:vt.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(vt.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 Pt(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?it.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(rt.resolve(me.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(rt.resolve(me.STATE,this.decorParameterTexts),i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const s of this.ufoElement.sighting.decor){if(s.id===e)continue;const{eastM:n,northM:r}=is(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=$i.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:Wi.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:$i.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:me.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:ts[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=it.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const o=this.ufoElement.sighting;o.decor=o.decor.map(d=>d.id===s.id?it.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?Ss.of(e,this.publishedParametersOf(e)):void 0,i=t&&rt.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 Pt(()=>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?be(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=V("Sun",i,t).altitudeDeg;return Ve(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Gn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new ji;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new ut(["en"]);tagNames=new Gi({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){if(!this.worded)return;this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,s=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?be(i,t.lng,e.event.utcOffsetHours):void 0,n=JSON.stringify([s?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,re(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey,e.skySources]);if(n===this.skyCandidatesKey)return;if(this.skyCandidatesKey=n,!s||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=e.skySources!==!1,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 xn.gainFor(e.instrument,{fNumber:Q(e,0)?.fNumber,fieldOfViewDeg:Oe.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=V("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=Ve(i,s,n),o=l=>l.toLocaleString(void 0,{maximumFractionDigits:1});if(r<qr)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(Ve(i,0,n)));return r<=Ki?d:d+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Ki))}showerClause(e,t){const i=Vi.observedRatePerHour(Vi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=Qt.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=Qt.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:Qt.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=ei.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=Zi.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=Sn.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=V("Sun",i.peak,t),n=r=>r.replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),o=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} s`)}return n(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=V("Moon",e,t);if(i.altitudeDeg<=0||Je(e).illuminatedFraction<.97)return;const s=[],n=qe.distanceKm(e,t),r=qe.relativeToMean(qe.radiusAtKm(n)),o=n<=qe.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=qe.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(qe.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),jt.isIn(e)&&s.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),s.length>0?s.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=ve.visibilityAt(e,t),s=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(s!==void 0)return s;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const n=Ve(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=ve.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=V("Sun",i.peak.date,t);return s<=Ve(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=Q(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=be(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(s=>`${s.object.norad}@${s.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>Yi.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Yi.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,s)=>i.magnitude-s.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,s=i.from[2]-i.to[2],n=Math.abs(s)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/s));return i.t-t.getTime()+n*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const s=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",s.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(s.record.t))).replace("{altitude}",String(Math.round(s.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(s.peak.azimuthDeg)).replace("{distance}",String(Math.round(s.peak.distanceKm/10)*10)).replace("{stations}",String(s.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const s=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=this.aimableFireballs(this.strikingFireballs(s,this.observerAtStart()),s);if(n.length===0)return;const r=n[this.fireballRank++%n.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,s),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=re(this.ufoElement.sighting,0),s=V("Sun",e,t),n=V("Moon",e,t),r=wt.deckLitUntilDeg(wt.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(wt.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(wt.formsAt(a.altitudeDeg,r).map(u=>this.opticsFormName(u))),c=i.iceCrystalAlignment??bi;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=re(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=V("Sun",e,t),n=V("Moon",e,t),r=s.altitudeDeg>0,o=r?s:n;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const a=i.lowerCloudCover??i.cloudCover;if(ti.strength(i.precipitationIntensity,a,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const d=ti.formsAt(o.altitudeDeg);if(d.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(ti.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(Je(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",l).replace("{lit}",String(h))}glowClause(e,t){const i=V("Sun",e,t);if(i.altitudeDeg>oo)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<=R.CONE_SEPARATION_DEG;n.push((u?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(s.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(s.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(s.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(s.zodiacal.sunSeparationDeg))))}if(n.length>0)return this.listed(n);const r=this.decimal(s.darkestSkyMagPerArcsec2,1),o=V("Moon",e,t),a=s.darkestSkyMagPerArcsec2<ao,d=this.ufoElement.sighting.lightPollution,l=pe.scatteringAt(90-o.altitudeDeg)*pe.moonOutput(pe.phaseAngleOf(Je(e).illuminatedFraction),o.altitudeDeg)*pe.scatteredFraction(90),h=pe.artificialZenithNanolamberts(d)>l;if(a&&o.altitudeDeg>0&&!h){const u=Math.round(Je(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(u)).replace("{sky}",r)}const c=pe.artificialZenithNanolamberts(d)>pe.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=V("Sun",e,t),s=V("Moon",e,t);return pe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(Je(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new R;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<ei.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=ei.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Zi.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}=is(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-Qr-(Q(this.ufoElement.sighting,this.ufoElement.currentTime)?.elevationM??0),r)*180/Math.PI;this.headingInput.value=String(Math.round(o*10)/10),this.pitchInput.value=String(Math.round(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 es(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Ze.width/2,y:e.height/2-Ze.height/2,width:Ze.width,height:Ze.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new Ei(this.ufoElement.sighting.timeline,new hr(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"})),M.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=ze.preferencesFor(this);this.preferences=t;const i=ci(t,ui),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([ks.load(i),i==="en"?{}:js(i),Gs(i),sr.load(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.decorParameterTexts=d,this.naming=new ji(a),this.said=new ut(t),this.tagNames=new Gi(o),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new Ji(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===nt&&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(Si))n.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.applyPerceptionLabels(),this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,Ae.say(this.labelAccountUrl,e.accountUrl,e.accountUrlHint),this.labelAccountFollowedUp.textContent=e.accountFollowedUp,this.evaluationFields.messages=e.accountEvaluation;for(const[n,r]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const o=this.shadow.getElementById(n);o&&(o.textContent=r)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.label("label-film-stock",e.filmStock),this.filmStockKey=void 0,this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.label("label-sky-sources",e.skySources),this.skySourcesInput.closest("label").title=e.skySourcesHint,this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"peak",label:e.decorPeak},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const s=this.shadow.getElementById("option-scenery-none");s&&(s.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[n,r]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=r,n.setAttribute("aria-label",r);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.decorBaseShownFor=void 0,this.decorBaseShown=!1,this.decorParametersShownFor=void 0,this.isConnected&&this.syncDecorVisibility(),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup;for(const n of this.skyParts.values())this.nameSkyPart(n.label,n.titles);for(const n of["location","decor","weather"]){const r=this.shadow.getElementById(`${n}-settings-button`);r?.setAttribute("title",e.dataSources),r?.setAttribute("aria-label",e.dataSources);const o=this.shadow.getElementById(`label-${n}-settings`);o&&(o.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language);for(const n of this.skyParts.values())n.editor?.setLanguage(this.language);this.modulesPanel?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new Ji(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language},this.decorParameterTexts),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.shadow.getElementById("label-aircraft-group").textContent=e.aircraftGroup,this.aircraftFlights.show(this.sceneElement.aircraftFlights,e,!0),this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.referenceKindSelect.querySelector("#reference-kind-video").textContent=e.referenceVideo,this.shadow.getElementById("label-reference-video-from").textContent=e.referenceVideoFrom,this.shadow.getElementById("label-reference-video-to").textContent=e.referenceVideoTo,this.shadow.getElementById("label-reference-video-rate").textContent=e.referenceVideoRate,this.referenceRemoveKeyButton.textContent=e.referenceRemoveKey,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=this.currentReference()?.kind==="video"?e.referenceVideoT:e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,Ae.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,r]of this.soundKindOptions)r.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e),this.refreshFileItems(),this.refreshSkyCandidates()}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.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"])Fe.popover(this.shadow.getElementById(s),e.close);Fe.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),Fe.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),Fe.button(this.contextMenu,e.close,()=>this.hideContextMenu()),Fe.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 ii(this.selectedMembers()),c=J.hitTestHandle({bounds:h.bounds(),angle:0},t);if(c==="rotate"){if(o)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(c){if(o)return;this.dragState={kind:"group-resize",group:h,handle:c},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(r,this.currentSourceId),c=h?.kind==="polygon"?J.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&c!==void 0){if(o)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:c},this.startDragListening();return}const u=h&&J.hitTestHandle(h,t);if(h&&u){if(o)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const d=this.ufoElement.shapeAt(t.x,t.y,Tt);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"&&J.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId,shape:n}:this.ufoElement.shapeAt(t.x,t.y,Tt);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?J.hitTestVertex(d,this.contextMenuPoint):void 0,c=l&&d.points.length<=In;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=J.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const s=J.hitTestVertex(i,e);if(s===void 0)return;const n=J.deleteVertex(i,s);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,s,n){this.dragState={kind:e,sourceId:t,original:i,handle:n,startPointer:s},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!s||!i)return!1;i.show(s);const n=i.readingNow(),r=this.skyDirectionOf(e);return!n||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:n.azimuthDeg,bodyAltitudeDeg:n.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const s=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+s,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(Mt,(e.maxX-e.minX)/2*t.width),s=Math.max(Mt,(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=Lt,a=Lt+Gr,d=t.width-Lt,l=t.height-r-Lt,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<Mt||p-c<Mt?e:{x:h,y:c,width:u-h,height:p-c}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),s=e.reading();if(!i||!s)return!1;const n=J.hitTestHandle({bounds:i,angle:0},t);if(!n)return!1;if(n==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...s.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:n,centre:r,startPointer:t,startSizeM:{...s.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const c=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,u=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,p=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:p.headingDeg,pitchDeg:p.pitchDeg+u,rollDeg:p.rollDeg+c}:{headingDeg:p.headingDeg+c,pitchDeg:p.pitchDeg,rollDeg:p.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:s,startPointer:n,startSizeM:r,handle:o}=t,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:li};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:Yr};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=Wi.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:it.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,Tt)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=it.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&&ss(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&ss(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=J.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"?J.resizeShape(r,o,t):J.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)<Jr)return;this.cameraDragState.moved=!0}const o=s+(t.x-i.x)*li,a=Math.max(-90,Math.min(90,n-(t.y-i.y)*li));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?so: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)*io*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)*to*t,o=i*Math.PI/180,a=Js(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=Es(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(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(Xi,i.width-Pe);break;case"ArrowRight":i.width+=Pe;break;case"ArrowUp":i.height=Math.max(Xi,i.height-Pe);break;case"ArrowDown":i.height+=Pe;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Pe;break;case"ArrowRight":i.x+=Pe;break;case"ArrowUp":i.y-=Pe;break;case"ArrowDown":i.y+=Pe;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:s,shape:n}=i[0];this.commitShapes(t,[{sourceId:s,shape:{...n,bounds:this.nudgeBounds(n.bounds,e)}}])}else{const s=new ii(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&&J.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&&J.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,Tt)&&this.grabsDecor(e,t,l))return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const a=J.hitTestHandle({bounds:new ii(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"&&J.hitTestVertex(a,t)!==void 0)return"vertex";const d=a&&J.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-${J.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),s=e.clientX-i.left,n=e.clientY-i.top;this.recorder?.onPointerMove(s,n),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(As(this.buildPrototype({x:0,y:0,width:Ze.width,height:Ze.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 lo={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},ys="rr0-sighting-editor";function Us(){Rs(),xs(),Hs(),gr(),pr(),vr(),Ls(),customElements.get(ys)||customElements.define(ys,w)}const vi="rr0-case-editor",ho=`
2753
+ `;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await D(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-C25E4WMl.js");return{ModelThumbnails:i}},__vite__mapDeps([2,3,1,4,5,6,7,8,9,10]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const s=document.createElement("button");s.type="button",s.className="model-picker-button",e.after(s),e.hidden=!0;let n=0,r;const o=()=>{const 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=>ct.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=ct.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=L.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),D(async()=>{const{ModelViewer:I}=await import("./ModelViewer-D6JaOQS7.js");return{ModelViewer:I}},__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),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,E=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 T=document.createElement("span");if(T.className="model-name",T.textContent=I.textContent,C.append(R,T),I.title){const y=document.createElement("span");y.className="model-credit",y.textContent=I.title,C.append(y)}f(I.value).then(y=>ct.pictureOf(y)).then(y=>{if(!y)return;const M=new Image;M.src=y,M.alt="",R.append(M)});let Z,Y=!1;const Ce=()=>{Y&&!(Z&&!Z.active)||(Y=!0,Promise.all([f(I.value),D(()=>import("./ModelViewer-D6JaOQS7.js"),__vite__mapDeps([11,3,1,4,5,6,7,8,9,10]),import.meta.url)]).then(([y,{ModelViewer:M}])=>{!y||!Y||(Z=M.show(R,y))}).catch(()=>{}))},Ke=()=>{Y=!1,Z?.stop(),Z=void 0};return v.set(C,Ce),C.addEventListener("pointerenter",Ce),C.addEventListener("focus",Ce),C.addEventListener("pointerleave",()=>{document.activeElement!==C&&Ke()}),C.addEventListener("blur",Ke),C.addEventListener("click",y=>{if(Z?.consumeDrag()){y.preventDefault();return}g(I.value)}),C},x=()=>(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(" — "),x().append(E(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=x();for(const T of Array.from(I.children))R.append(E(T));b=void 0}else I instanceof HTMLOptionElement&&(b??x()).append(E(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 S=o.querySelector('.model-card[aria-pressed="true"]');(S??d).focus(),S&&v.get(S)?.()}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,E,x="")=>{const S=document.createElement("label"),I=document.createElement("span");I.textContent=v;const C=document.createElement("input");return C.type=E,C.placeholder=x,S.append(I,C),d.append(S),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 E=n.current();h.value=E?.url??"",c.value=E?.title??"",u.value=E?.author??"",p.value=E?.license??"",m.value=E?.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 xi{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=xi.SPAN_DEG;try{const n=(await this.provider.getElevationGrid({south:e-i,north:e+i,west:t-i,east:t+i},{width:2,height:2})).heights[0];return Number.isFinite(n)?n:void 0}catch{return}}}class $r{formatters=new Map;available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const i=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),s=this.zoneOffsetHours(e,new Date(i));if(s!==void 0)return this.zoneOffsetHours(e,new Date(i-s*36e5))??s}zoneOffsetHours(e,t){let i=this.formatters.get(e);if(i===void 0){try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"})}catch{i=null}this.formatters.set(e,i)}if(i===null)return;const s=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(s);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[3])/60):0}zonesAt(e,t){const i=t?.year!==void 0?t:{year:new Date().getFullYear(),month:1,day:1,hour:12};return this.available().filter(s=>this.offsetHoursAt(s,i)===e)}}class oe{static STEP_MS=100;static plan(e){const t=oe.routeOf(e),i=Te.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const o=new Set,a=(c,u,p,m)=>{if(Math.abs(c.radiusM-m)>=m*.1)return!1;const{x:f,z:g}=Es(u,p,c.lat,c.lng);return Math.hypot(f,g)<Te.rebuildDistanceFor(m)};for(let c=0;;c=Math.min(s,c+oe.STEP_MS)){const u=ee(e,c);if(u?.lat!==void 0&&u.lng!==void 0){const p=Te.groundRadiusFor(u.elevationM??0),m=Te.patchRadiusFor(p,u.elevationM??0),f=Math.max(m,i);(!r||!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=Te.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>Te.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=Ts.map(c=>Ct.of(c)).filter(c=>c.reachM&&Ct.eventsOf(e.skyEvents,c).length>0);if(h.length>0){const c=u=>Math.max(...h.map(p=>p.reachM(Ct.eventsOf(e.skyEvents,p),u)));for(const u of[...n])u.far||o.has(u)||n.some(p=>p.far&&p.lat===u.lat&&p.lng===u.lng)||Te.needsFarRing(u.radiusM,0,c(u))&&n.push({lat:u.lat,lng:u.lng,radiusM: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=oe.routeOf(t),d=[];for(const[c,u]of i.entries()){try{const p=await s.elevation.getElevationGrid(dt.boundsOf(u),{width:Bi,height:Bi},{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 ln.encode({takenOn:r,attribution:l,patches:d}),attribution:l,takenOn:r,answered:d.length,patches:i.length}}case"imagery":{const a=new Oi,d=U(lt,s.imagery),l=d.create(a.fetch);let h=0;for(const[p,m]of i.entries()){try{await l.getImageryTexture(dt.boundsOf(m),{width:Ri,height:Ri}),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 Pi.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 oe.vector(s.roads,i,r,o,(a,d)=>a.getRoads(d),a=>a.contemporary);case"water":return oe.vector(s.water,i,r,o,(a,d)=>a.getWater(d));case"railways":return oe.vector(s.railways,i,r,o,(a,d)=>a.getRailways(d),a=>a.contemporary)}}static mapGround(e){const t=dn.of(e);return t&&Ni.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=oe.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Oi,r=U(lt,t),o=r.create(n.fetch),a=Ni.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 Pi.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<=Te.ROADS_MAX_RADIUS_M)try{o.push({...h,items:await n(e,dt.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 Q.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 Q.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 D(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:r}},__vite__mapDeps([12,13,14]),import.meta.url);if(t!==this.shown||!this.editorHost.isConnected){this.editorFor=void 0;return}this.editor??=new n(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const s={...this.host.sighting().snapshots??{}};let n;try{n=await this.bytesAt(t.url)}catch{n=void 0}if(n!==void 0)try{s[e]={src:t.url,...await j.describe(e,n)}}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}le.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}F.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await D(async()=>{const{InputFileElement:s}=await import("./rr0-ufoathome.mjs").then(n=>n.J);return{InputFileElement:s}},[],import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const s={...this.host.sighting().snapshots??{}},n=this.annex(e);let r;try{r=await j.describe(e,t)}catch{F.show(this.note,this.messages.annexUnreadable,"warning");return}const o=n!==void 0&&j.isInline(n.src),a=o?j.dataUrl(e,t):n?.src??Q.annexName(this.host.base(),e);o||le.hold(this.address(a),t),s[e]={...s[e]?.live?{live:!0}:{},src:a,...r},F.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=Q.annexName(this.host.base(),e),le.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)?Q.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 D(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 le.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,oe.plan(this.host.sighting()),this.host.sources(),s))?F.show(this.note,void 0):F.show(this.note,this.messages.snapshotFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setSnapshots(t)}hasWork(){const e=this.host.sighting();return Q.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||oe.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=>Q.isLive(i,h),r=h=>i[h]?.src!==void 0?i[h]:void 0;for(const h of Q.NAMES)!i.live&&i[h]?.live&&(i[h]={live:!0});const o=oe.plan(t);let a;for(const h of Q.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");oe.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 oe.freeze(e,this.host.sighting(),i,s,(a,d)=>F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(a)).replaceAll("{of}",String(d))));return F.show(this.note,void 0),o?(t[e]={src:this.place(e,t[e]?.src,n,o.bytes),takenOn:o.takenOn,attribution:o.attribution},!0):!1}async takeMap(e,t,i){F.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await oe.freezeMap(this.host.sighting(),t.imagery);return F.show(this.note,void 0),s?(e.map={src:this.place("map",e.map?.src,i,s.bytes),takenOn:s.takenOn,attribution:s.attribution},!0):!1}async fitsMap(e){const t=oe.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await le.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&dt.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 le.zip(s))["index.json"])).patches:(await le.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(o=>o.radiusM<=Te.ROADS_MAX_RADIUS_M);return dt.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??Q.annexName(i,e);return le.hold(this.address(n),s),n}async keep(e,t){if(!j.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{F.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return le.bytes(this.address(e.src))}address(e){return le.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of Q.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=Q.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 Gt{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,F.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().snapshots?.[e]?.src}itemLabel(e){const t=this.messages;return t?{weather:t.fileItemWeather,place:t.fileItemPlace,lightPollution:t.fileItemLightPollution,decor:t.fileItemDecor}[e]:""}where(e){return this.srcOf(e)??this.messages?.annexStorageInline??""}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[$.KEYS[e][0]]}render(){if(!this.messages)return;const e=this.srcOf(this.shown);this.sourceInput.url=e?this.resolve(e):this.host.masterUrl(),this.root.querySelector("#section-annex-state").textContent=this.state(this.shown)}state(e){const t=this.host.sighting();switch(e){case"weather":return t.weatherSource?.name??this.messages.weatherStatedByObserver;case"place":return t.event.place?.[0]?.name??"";case"lightPollution":return new ut(ze.preferencesFor(this.root)).read(t.provenance.at("lightPollution")?.rationale)??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().snapshots??{}};if(t===(i[e]?.src===void 0))return;const{src:s,...n}=i[e]??{};i[e]=t?n:{...n,src:$.annexName(this.host.base(),e)},this.write(e,i)}annex(e){const t=this.srcOf(e);return t===void 0?void 0:{src:t,bytes:this.bytesOf(e)}}bytesOf(e){const t=gi(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:je.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},F.show(this.note,void 0),this.write(e,a);return}let i;try{const{InputFileElement:a}=await D(async()=>{const{InputFileElement:l}=await import("./rr0-ufoathome.mjs").then(h=>h.J);return{InputFileElement:l}},[],import.meta.url),d=await a.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=je.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{F.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...gi(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=Ms(n);Gt.copy(e,r,s);const o={...s.snapshots??{}};t.url?o[e]={...o[e]??{},src:t.url}:o[e]=o[e]??{},F.show(this.note,void 0),this.write(e,o)}write(e,t){this.host.sighting().snapshots=Q.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const s of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(s.t,s.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const s of $.KEYS[e]){i.provenance.clear(s);for(const n of t.provenance.paths())(n===s||n.startsWith(`${s}.`))&&i.provenance.set(n,t.provenance.at(n))}}}class Hr{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const i=new URL(this.endpoint);i.searchParams.set("latitude",String(e)),i.searchParams.set("longitude",String(t)),i.searchParams.set("timezone","auto"),i.searchParams.set("forecast_days","1");try{const s=await fetch(i.toString());if(!s.ok)return;const n=await s.json();return n.timezone&&n.timezone!=="GMT"?n.timezone:void 0}catch{return}}}const Wr=he.point("timeZone").provide(he.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new Hr}]);class ai{static OCCUPATIONS={student:!0,worker:!0,farmer:!0,homemaker:!0,merchant:!0,business:!0,employee:!0,artist:!0,technician:!0,police:!0,pilot:!0,military:!0};static RELATIONS=["friends","family","professional","none"];static ACTIVITIES=["leisure","travelling","cultural","working"]}class K{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=K.select("observerOccupationKind");graduate=K.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=K.select("observersRelation");activity=K.select("observerActivity");factors=new Map(Vn.map(e=>[e,K.select(`strangeness-${e}`)]));labels=new Map;unit=document.createTextNode(" min");strangenessTitle=document.createElement("span");strangenessIntro=Object.assign(document.createElement("p"),{className:"section-intro"});wording;constructor(e,t,i,s){Ae.register(),e.append(this.label(this.occupationKind,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]);K.choices(this.occupationKind,"",d(Object.keys(ai.OCCUPATIONS))),K.choices(this.graduate,"",a),K.choices(this.relation,"",d(ai.RELATIONS)),K.choices(this.activity,"",d(ai.ACTIVITIES));for(const l of this.factors.values())K.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,K.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),K.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),K.choices(this.relation,e.unknown,Object.entries(e.relations)),K.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)K.choices(i,K.READ_FROM_RECORDING.includes(t)?e.fromRecording:e.unknown,[["yes",e.yes],["no",e.no]])}show(e){this.occupationKind.value=e?.observerOccupationKind??"",this.graduate.value=K.yesNo(e?.observerGraduate),this.enquiryMinutes.value=e?.enquiryMinutes?.toString()??"",this.relation.value=e?.observersRelation??"",this.activity.value=e?.activity??"";for(const[t,i]of this.factors)i.value=K.yesNo(e?.strangeness?.[t])}values(){const e=this.enquiryMinutes.value.trim()===""?void 0:Number(this.enquiryMinutes.value),t={};for(const[i,s]of this.factors){const n=K.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:K.boolean(this.graduate.value),enquiryMinutes:e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0,observersRelation:this.relation.value||void 0,activity:this.activity.value||void 0,strangeness:Object.keys(t).length>0?t:void 0}}label(e,t){const i=document.createElement("label"),s=document.createElement("span");return i.append(s," ",e),this.labels.set(s,()=>{if(!this.wording)return;const[n,r]=t(this.wording);Ae.say(s,n,r)}),i}static select(e){return Object.assign(document.createElement("select"),{id:e})}static choices(e,t,i){const s=e.value;e.replaceChildren(new Option(t,""),...i.map(([n,r])=>new Option(r,n))),e.value=s}static yesNo(e){return e===void 0?"":e?"yes":"no"}static boolean(e){return e===""?void 0:e==="yes"}}const Tt=new Set;Ls();Tn();Ds.register();const Ye={width:48,height:28},jr=2500,Mt=40,Lt=10,Gr=30,Kr=10,bs=600,vs=900,Je=2e-4,Vr=900,qr=-1.46,Zr=3,li=.2,Yr=.5,Jr=3,Xr=.01,Qr=1.6,di=2e3,eo=250,ws=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),to=1,io=5,so=10,Pe=4,nt="ufo-1",no={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function ro(k){return k.kind==="oval"?"oval":"polygon"}const oo=-6,ao=21;class w extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=Wr[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new $r;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;exportKmlButton;exportGeoJsonButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;saidInterviews;candidatesView;sectionFolds;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=_r();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 st(zr());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?hn.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 Zt;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=Ge.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...no};currentSourceId=nt;selectedSourceIds=new Set([nt]);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(ws.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;ws.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>${lr}</style>${ar}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const l of this.shadow.querySelectorAll(Ft))l.build();for(const l of this.shadow.querySelectorAll(Wt))l.build();for(const l of this.shadow.querySelectorAll(Si))l.build();for(const l of this.shadow.querySelectorAll(Ii))l.build();this.sceneElement=document.createElement(cn),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 ht(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(Wt),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 We(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 Bs({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=un.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new yi(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 Ns(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 K(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.rareIceCrystalsInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${Ii}[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 Gt(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 xe(this.shadow.getElementById("events-section"),s,void 0),this.phenomenonEventsPanel=new xe(this.shadow.getElementById("phenomenon-events-section"),s,void 0,"phenomenon"),this.bodiesEventsPanel=new xe(this.shadow.getElementById("bodies-events-section"),s,void 0,"bodies"),this.aroundPanel=new ir(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,ue.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 dr(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 fe({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind: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 fe({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect: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 ie(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 D(async()=>{const{SurroundingsSources:c}=await import("./surroundingsSources-B--F7TR5.js");return{SurroundingsSources:c}},__vite__mapDeps([15,1,3,4,5,6,7,8,9]),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 pi(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 ct(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 ot(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 ot(this.decorBaseHost,"en","decorBase.",n,(l,h)=>this.enhanceDecorModelChoice(l,h)),this.decorStateForm=new ot(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(pn,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(mn,()=>{const l=this.currentReference();l&&this.syncReferenceStatus(l)}),this.sceneElement.addEventListener(gn,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(fn,()=>{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 pi(this.addShapeButton,"add-shape-kind",l=>{const h=Me.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,Oe.fovOf(this.ufoElement.sighting,c.t)]));this.retuneFieldOfView(l),this.retuneExposure(l),Oe.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(`${Ft}[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=ft.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(),Bt.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=Qn(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()},ci(ze.preferencesFor(this),ui),this.framePlace()),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&(this.ready=this.loadLocaleMessages())}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),ze.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=this.loadLocaleMessages()),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving),he.changes.addEventListener("change",this.onModulesChanged),D(async()=>{const{ModuleSession:t}=await import("./ModuleSession-pXE1aOJF.js");return{ModuleSession:t}},__vite__mapDeps([16,1,3,4,5,6,7,8,9]),import.meta.url).then(({ModuleSession:t})=>t.shared.start(),()=>{});const e=this.getAttribute("src");e&&this.importFromUrl(e)}relisters=[];onModulesChanged=e=>{for(const i of this.relisters)i();const t=e.detail;t==="weather"&&(this.followWeatherRecord(),this.fillWeatherProvider()),t==="surroundings"&&this.surveyIds&&this.fillScenerySources(),t==="decorModels"&&this.sceneElement.setDecorModelProvider(this.decorModelProvider),(t==="skyEvents"||t==="interpretations")&&this.buildSkyParts(),t==="perception"&&(this.perceptionSettings.providers=ft.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),he.changes.removeEventListener("change",this.onModulesChanged),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),clearTimeout(this.moduleNamingTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){const t=je.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]??nt,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:()=>`${fi.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let s="";i?.year!==void 0&&(s=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const n=[t,s].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==n&&(r.textContent=n)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.scheduleModuleNaming(),this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons(),this.refreshEditorHead())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons(),this.refreshEditorHead())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=this.shadow.getElementById("save-refused"),t=q.issues(this.ufoElement.sighting);if(F.show(e,t.length===0?void 0:this.messages.saveRefused.replace("{reasons}",t.map(s=>this.actorIssue(s)).join(" ; ")),"error"),t.length>0)return;const i=_.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=_.namesOf(this.sightingData);this.observerLastNameInput.value=_.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>_.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=_.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=_.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=_.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 D(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)),...Q.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=Q.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||fe.glue(o)}t&&this.snapshotsPanel.show(e),i&&this.sectionFilePanel.show(i);const n=t&&this.snapshotsPanel.isInlineGroup(e)?["snapshots",e,"src"]:i&&this.sectionFilePanel.isInline(i)?Gt.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 Zt)||he.installed().length===0)return;const t=this.ufoElement.sighting,i=new Set([...t.decor.map(r=>r.model?.id),...(t.interpretation?.bodies??[]).map(r=>r.model?.id)].filter(r=>typeof r=="string")),s=this.sceneElement.documentUrl;let n=t.modules;for(const r of i){const o=await e.moduleOf(r),a=o===void 0?void 0:he.installed().find(d=>d.id===o)?.url;!a||fs.names(n,a,s)||(n=[...n??[],fs.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??=D(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-Bio6lzC6.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([17,1,16,3,4,5,6,7,8,9,18,19,20,21,22,23,24]),import.meta.url).then(({register:e,ModulesPanelElement:t})=>{e();const i=this.shadow.getElementById("modules-panel");this.modulesPanel=i,i.addEventListener("recordingmoduleschange",()=>{const s=i.recordingModules;this.ufoElement.sighting.modules=s.length>0?s:void 0,this.syncFileEditor(!1)}),i.checkContext=()=>({weatherQuery:this.weatherInference.queryOf(this.ufoElement.sighting),interpretation:this.ufoElement.sighting.interpretation}),i.setLanguage(this.language),this.syncModulesPanel()}),this.modulesPanelLoading}syncModulesPanel(){this.modulesPanel&&(this.modulesPanel.base=this.sceneElement.documentUrl,this.modulesPanel.recordingModules=this.ufoElement.sighting.modules)}sectionFromFile(e){return $.fromFile(this.ufoElement.sighting.snapshots,e)}masterUrl(){return this.sceneElement.documentUrl??new URL(`${this.fileBase()}.json`,location.href).href}weatherFileItemLabel(){return this.sectionFilePanel?.itemLabel("weather")??""}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}snapshotSources(){const e=U(bt,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:U(lt,this.chosenSourceId.get("imagery")).id,roads:wn(),water:vn(),railways:bn()}}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)}));le.release();const i=await this.recordingText(t),s=JSON.parse(i);if(se.isCase(s)){if(se.check(s),this.offerCase(s,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=s,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){this.showLoadError(t)}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await D(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)&&le.hold(le.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=je.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 Qe.recording(e);if(se.isCase(t)){se.check(t);const s=new URL(e,location.href).href;if(this.offerCase(t,s)){this.importInput.url=s;return}throw new Error("A case has no recording to edit here")}const i=t;le.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=_e.local(e)?void 0:new URL(e,location.href).href,this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){this.showLoadError(t)}}loadError;showLoadError(e){this.loadError=e===void 0?void 0:{error:e},this.sayLoadError()}sayLoadError(){F.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof Rt)return e.said(this.messages.formatVersionError);if(!(e instanceof Hs))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";static SCENERY_STORAGE="rr0-sighting-editor.surroundings";static SCENERY_RADIUS_STORAGE="rr0-sighting-editor.surroundings-radius";static NO_SCENERY="none";narrativeProvider=yt[0].create();get narrativeSourceId(){return U(yt,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 ce&&i.kind==="cancelled";this.narrativeStatus.textContent=s?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!s)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:s,...n}=i,r=i.timeZone?n:i,o=Ee.stated(r);if(o.length>0){const a=this.ufoElement.sighting.provenance,d=Fi(this.ufoElement.sighting);this.patchingDraft=!0;try{this.sightingData=Ee.apply(d,$t.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(Fi(this.ufoElement.sighting),n.path)})}static valueAt(e,t){let i=e;for(const s of t.split(".")){if(typeof i!="object"||i===null)return;i=i[s]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(s=>s.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[lo[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=U(yt,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 ce))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}static pageCredentials=new Map;static forgetCredentials(){w.pageCredentials.clear(),Yt.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(U(oi,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",Kn,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(U(Et,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",yt,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",oi,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",Et,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",bt,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",lt,()=>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",zi,()=>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=U(t,r.value);Yt.set(f.id,c.value),i(f,!0)});const p=()=>{const f=r.value===w.FILE_SOURCE,g=U(t,f?a():r.value);h.hidden=f||!g.keyUrl,u.href=g.keyUrl??"",c.value=Yt.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(U(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(U(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),d,l,h),n}aircraftPicker(){const e=this.sourcePicker("aircraft",Ui,(t,i)=>this.applyAircraftSource(i));return e.append(this.aircraftStatus),this.showAircraftStatus(),e}get aircraftTabOpen(){return this.isGroupIdOpen("group-weather")&&this.shadow.getElementById("weather-aircraft")?.hidden===!1}showAircraftFlights(){if(this.aircraftTabOpen){if(this.ufoElement.playbackState==="playing"){const e=performance.now();if(e-this.aircraftFlightsShownAt<1e3)return;this.aircraftFlightsShownAt=e}this.aircraftFlights.show(this.sceneElement.aircraftFlights,this.messages)}}aimAtFlight(e){if(e.key===this.aircraftFlights.selectedKey){this.aircraftFlights.select(void 0,this.messages),this.sceneElement.markFlight(void 0);return}if(!e.sky&&e.firstMs===void 0)return;const t=e.sky?this.ufoElement.currentTime:e.firstMs;e.sky||this.goToMark(t),this.sceneElement.lookAtFlight(e.key,t),this.aircraftFlights.select(e.key,this.messages),this.sceneElement.markFlight(e.key),this.showAircraftFlights()}showAircraftStatus(){this.showAircraftFlights();const{status:e,problem:t,partial:i,creditsSpent:s,total:n}=this.sceneElement.aircraftState,r=[];e==="loading"&&r.push(this.messages.aircraftLoading),e==="outside"&&r.push(this.messages.aircraftOutside),e==="byHand"&&r.push(this.messages.aircraftByHand),e==="unavailable"&&!t&&r.push(this.messages.aircraftProblems.network),e==="ready"&&n===0&&r.push(this.messages.aircraftNone),i&&r.push(this.messages.aircraftPartial.replace("{traced}",String(i.traced)).replace("{seen}",`${i.seen}${i.moreSeen?"+":""}`).replace("{km}",String(i.withinKm))),s&&r.push(this.messages.aircraftCredits.replace("{credits}",String(s))),t?F.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):F.show(this.aircraftStatus,r.length>0?r.join(" "):void 0,"info")}groupChoice(e){return{item:e[0],fromFile:()=>!this.snapshotsPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.snapshotsPanel.setLive(i,!t)},label:()=>this.snapshotsPanel.itemLabel(e[0]),where:()=>this.snapshotsPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const s={...this.ufoElement.sighting.snapshots??{}};i?s[e]=s[e]??{}:delete s[e],this.ufoElement.sighting.snapshots=Q.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(U(oi,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),w.creditLink(U(Et,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:U(bt,this.chosenSourceId.get("elevation")).create(),imagery:U(lt,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(U(Ui,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new Zt(U(zi,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)<Je&&Math.abs(i-this.namedCoordinates.lng)<Je||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(t,i),vs))}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)<Je&&Math.abs(i-s.lng)<Je||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),vs))}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?ye.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),f=this.numberOrUndefined(this.fNumberInput.value),g=this.filterSelect.value,b=ae.byId(a.getLatestPoseAt(d-1)?.filter),v=g===ae.NONE.id||g===""?b===ae.NONE?void 0:ae.NONE.id:g,E=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=E===u.exposureSeconds?void 0:E;const x=this.numberOrUndefined(this.focusDistanceInput.value),S=Math.abs(m-ye.fieldOfViewDeg(u))>.01||f!==u.fNumber||x!==void 0||v!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&c===0&&!S?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:x,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 T=this.plantingCentre();this.surroundings.placeChanged(T?.lat,T?.lng),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!kt.isFirm(t))return;const s=kt.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&&kt.at(i,e)===t)return;const s=kt.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&&Nt({...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:ft.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={...re(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...re(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(s=>s.id===this.currentReferenceId),t=e!==void 0;fe.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const s of[this.referenceSelect,...this.referenceFields])s.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.syncVideoFields(e),this.showRegistration(this.registrationShown(e)),this.syncReferenceStatus(e)}syncVideoFields(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.referenceVideoFromInput.value=e.video?.fromS===void 0?"":String(e.video.fromS),this.referenceVideoToInput.value=e.video?.toS===void 0?"":String(e.video.toS),this.referenceVideoRateInput.value=e.video?.rate===void 0?"":String(e.video.rate),this.syncReferenceKeyButton(e)}syncReferenceKeyButton(e){this.referenceRemoveKeyButton.hidden=e.kind!=="video"||Re.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=Re.registrationAt(e,this.ufoElement.currentTime);return{headingDeg:this.rounded(t),pitchDeg:this.rounded(i),rollDeg:s===void 0?void 0:this.rounded(s),fovDeg:this.rounded(n)}}showRegistration({headingDeg:e,pitchDeg:t,rollDeg:i,fovDeg:s}){this.referenceHeadingInput.value=String(e),this.referencePitchInput.value=String(t),this.referenceRollInput.value=String(i??0),this.referenceFovInput.value=String(s)}syncVideoRegistrationFields(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);e?.kind==="video"&&(this.syncReferenceKeyButton(e),e.registrationTrack?.length&&this.showRegistration(this.registrationShown(e)))}removeReferenceKey(){const e=this.ufoElement.sighting.references.find(i=>i.id===this.currentReferenceId);if(!e)return;const t=Re.withoutKey(e,this.ufoElement.currentTime);this.ufoElement.sighting.references=this.ufoElement.sighting.references.map(i=>i===e?t:i),this.syncReferenceFields(),this.ufoElement.refresh()}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(F.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>xr?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)||xt))},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?Re.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=ee(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(Re.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=ee(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=ee(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:Er,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:xt},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=Re.kindOfSource(e.file?{type:e.file.type}:{url:e.url});s.references=s.references.map(r=>r.id!==t?r:{...r,src:i,kind:n==="video"||n==="photo"&&r.kind==="video"?n:r.kind,from:n==="video"?void 0:r.from,title:r.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=D(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-Dbr0O7NF.js");return{PictureRegistration:e}},__vite__mapDeps([25,3,1,4,5,6,7,8,9]),import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);return e?.registrationTrack?.length?{...e,registration:Re.registrationAt(e,this.ufoElement.currentTime)}:e}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const s=this.pictureAspect(t.id);if(!(s!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,s)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const s=8;for(const n of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(n.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=s)return{landmarkId:n.id,end:"picture"};const o=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=s)return{landmarkId:n.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const s=i.x-t.startPointer.x,n=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(s,n)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+s*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-n*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const s=this.currentReference(),n=s?this.pictureAspect(s.id):void 0;if(!s||n===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:this.pictureRegistration.aimOf(r)};const 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)||xt,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);fe.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=s===void 0,this.referenceLandmarkLabelInput.disabled=s===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(s?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),s=i.findIndex(o=>o.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const o=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.pictureAspect(t.id);if(i===void 0)return;const{registration:s}=t,n=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(o,s,i))),r=this.currentLandmarks().map((o,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(Re.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=ee(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 D(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:xt}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;fe.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t;this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(s=>s.id!==this.currentTraceId?s:{...s,title:this.said.write(s.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(s.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(s=>s.value===this.currentTraceId),i=e.traces.find(s=>s.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{TraceImport:l}=await D(async()=>{const{TraceImport:h}=await import("./TraceImport-CntRHXoJ.js");return{TraceImport:h}},__vite__mapDeps([26,1]),import.meta.url);i=await l.fromBytes(await Ws.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 D(async()=>{const{GEO_EXPORT_TEXTS:o}=await import("./GeoExportTexts-3a51cuxQ.js");return{GEO_EXPORT_TEXTS:o}},__vite__mapDeps([27,1]),import.meta.url),s=await i.load(this.writingLanguage);if(e==="kml"){const{KmlExport:o}=await D(async()=>{const{KmlExport:d}=await import("./KmlExport-AzofE76s.js");return{KmlExport:d}},__vite__mapDeps([28,29,5,6,1,4,3,7,8,9]),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 D(async()=>{const{GeoJsonExport:o}=await import("./GeoJsonExport-B2qogWLj.js");return{GeoJsonExport:o}},__vite__mapDeps([30,29,5,6,1,4,3,7,8,9]),import.meta.url),r=n.of(this.ufoElement.sighting,t,s,this.said);this.download(new Blob([r],{type:"application/geo+json"}),`${t}.geojson`)}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of Pn){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(),jr)}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=Bn(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 st(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===w.FILE_SOURCE;if(!e){const t=U(ke,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new st(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=Q.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=ke.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==U(ke,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new st(e.create())}else!e&&t!==void 0&&!ke.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new st(U(ke,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...ke.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&&!It(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:U(ke,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=U(ke,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&&!It(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),bs))}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||!It(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&&It(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const s=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s,this.syncWeatherProvider();const n=t&&e!==void 0;if(this.weatherSourceLink.hidden=!n,n){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=[e.name,this.observationInstantLabel()].filter(Boolean).join(", ");return}const r=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&be(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherLookupResult=void 0,this.followWeatherRecord(),this.weatherFromRecords=!$.fromFile(e.snapshots,"weather")&&(e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0),this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=Et[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),bs)}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=Nt(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=Nn(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?Jt.MUTED:Jt.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(),L.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(at.opensPrecise(e.time)),this.endDate.setPrecise(at.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)>Zr;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),Vr))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Je&&Math.abs(e.lng-i)<Je}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=U(bt,this.chosenSourceId.get("elevation")),n=await new xi(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=ee(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(at.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.evaluationFields.show(e.account),this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.skySourcesInput.checked=e.skySources!==!1,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=re(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??bi)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??Fn)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),s!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),s!==this.elevationInput&&this.syncElevationField(t?.elevationM??0,t?.altitudeM)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,n=i.getInterpolatedShapeAt(s,this.currentSourceId),r=this.buildAppearanceShape(e??n?.bounds??this.defaultBounds(),n,t);this.commitShapes(s,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const s=es(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 D(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-Cllslp2u.js");return{SightingFileEditor:t}},__vite__mapDeps([12,13,14]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const s=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(s!==void 0){this.fileFocus="shape",this.selectUnit(s.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(s=>s.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,s]of t.entries()){const n=s.shapes.findIndex(r=>r.sourceId===e);if(n>=0)return["timeline","keyframes",i,"shapes",n]}}showFileNote(e,t="info"){F.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of $.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&$.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of $.NAMES){const n=$.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||$.put(s,e,$.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return ns.of(e,t,t==="thin"?Oe.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(w.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(w.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Ms(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=ns.of(this.ownJson(gi(e)),t,t==="thin"?Oe.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){if(t.edited)try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i))return;const s=JSON.stringify(i.weatherTrack);if(i=this.withAnnexed(i),!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,r=!t&&this.fileTextApplied!==void 0&&s!==JSON.stringify(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()):ke.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 Rt?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=Oe.fovOf(i,s),h=2*Xt.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 ne({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=be(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=>qe(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=>Qe.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||Dt.computes(d,At.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=be(i.time,s.lng,i.utcOffsetHours);l&&(t.sunAltitudeDeg=V("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=re(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,E=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,E)))/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"?ue.observerTrackIsExpanded(t):ue.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||!ue.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=Jt.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=At.kinds();if(Dt.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Dt.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),Is.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 yn(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(`
2754
+ `)}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&&fe.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.shapeRotationInput])i.disabled=e,i.title=e?t:this.fieldHints.get(i.id)??""}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:ro(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,ge.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,ge.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(ge.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(ge.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!s)return;const n=this.currentProjection(),r=n.degToPx(e),o=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),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={[ae.NONE.id]:this.messages.filterNone,[ae.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[ae.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==ae.ALL.length||ae.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||ae.NONE.id;this.filterSelect.replaceChildren();for(const r of ae.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||ae.usableWith(ae.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=ye.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=ye.CATEGORIES.map(r=>({label:s[r],children:zn.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=ee(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??ye.fieldOfViewDeg(t),r=s?ye.focalLengthMmFor(t,n):n;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=s?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=s?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=s!==void 0&&s.focalRangeMm===void 0,this.focalLengthInput.min=String(s?s.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(s?s.focalRangeMm?.maxMm??2e3:179),Bt.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,kn.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=vt.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=ae.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=ye.fieldOfViewDeg(e),s=ye.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>Xr||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 ee(e,this.ufoElement.currentTime)?.fovDeg??ye.fieldOfViewDeg(e.instrument)}currentProjection(){return Xt.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=ge.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const s=ee(this.ufoElement.sighting,this.ufoElement.currentTime),n=s?.focusDistanceM;if(n!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(n));return}const r=(s?ye.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,o=s?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const a=this.ufoElement.canvasElement.height;if(a<=0)return;const d=2*En*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)??Kr,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(ge.sizeMAt(d,l),2),lengthM:s(ge.sizeMAt(d,l),2),heightM:s(ge.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??=D(async()=>{const{BodyEditor:e}=await import("./BodyEditor-B96fap0d.js");return{BodyEditor:e}},__vite__mapDeps([31,3,1,4,5,6,7,8,9,18,20]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,bodySelected:()=>this.bodiesEventsPanel.render(),said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,seekTo:t=>{this.ufoElement.currentTime=t},duration:()=>this.ufoElement.seekableDuration,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,s)=>this.sceneElement.groundAlong(t,i,s)},this.language),this.bodyEditor)),this.bodyEditorLoading}openSkyParts(){return[...this.skyParts.values()].filter(e=>!e.panel.hidden)}wantedSkyParts(){const e=At.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=Ts.map(i=>Ct.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=L.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(ft.ALL.map(i=>i.messages))];Promise.all(t.map(i=>i.load(e))).then(i=>{this.decidedLanguage===e&&(this.perceptionSettings.labels=Object.assign({},...i))},()=>{})}nameSkyPart(e,t){const i=this.decidedLanguage;i!==void 0&&t.load(i).then(s=>{this.decidedLanguage===i&&(e.textContent=s.title)},()=>{})}loadSkyPartEditor(e){return e.loading??=e.create().then(t=>(e.editor=t(e.panel.querySelector(`#${e.id}-editor`)),e.editor)),e.loading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const n=i===void 0||i<=0?void 0:ge.sizeMAt(e.distanceM,i);this.realWidthInput.value=n===void 0?"":this.plain(n,n<1?2:n<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const s={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=s.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,s=Xt.of(i.instrument,ge.CANVAS_HEIGHT_PX,Oe.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const o=Oe.aimOf(i,e,r.shape.bounds),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},...Me.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),s=e.shapesIn(i,this.currentAppearance),n=this.newSourceIds(s.length),r=this.shapeAddKinds().find(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]??nt,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:_i.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Cs}:{},windows:Os(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 D(()=>import("./surroundingsSources-B--F7TR5.js"),__vite__mapDeps([15,1,3,4,5,6,7,8,9]),import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const s=document.createElement("option");s.value=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=Q.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?zt.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*di,t=Math.round(e/eo*1e3);return{lights:_i.byId("airliner")?.create(),track:[{t:0,eastM:-di,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:di,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=jn(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?ts[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=$i([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(s=>s.t===e);i&&(t.milestones=t.milestones.filter(s=>s.t!==i.t),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh())}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=$i(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;fe.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!t;this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=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 D(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([32,33]),import.meta.url),i=this.messages,s={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},n=await new t(this.ghostsStatus,s).search(e.src);this.ghostFinding=n&&n.pairs.length>0?{referenceId:e.id,src:e.src,search:n}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t||e?.kind==="video",this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}syncFilmStocks(e,t){const i=vt.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:vt.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(vt.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 Pt(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?it.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(rt.resolve(me.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(rt.resolve(me.STATE,this.decorParameterTexts),i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const s of this.ufoElement.sighting.decor){if(s.id===e)continue;const{eastM:n,northM:r}=is(s,t);i.push({id:s.id,label:this.decorLabel(s),eastM:n,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(n=>n.id!==void 0)};const s=JSON.stringify(this.observerSaid??null);s!==this.observerSaidShown&&(this.observerSaidShown=s,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const s of e)t===void 0||t==="stated"?i.clear(s):i.set(s,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=Hi.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:Wi.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Hi.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:me.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:ts[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=it.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const o=this.ufoElement.sighting;o.decor=o.decor.map(d=>d.id===s.id?it.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?Ss.of(e,this.publishedParametersOf(e)):void 0,i=t&&rt.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 Pt(()=>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?be(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=V("Sun",i,t).altitudeDeg;return qe(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new Gn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new ji;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new ut(["en"]);tagNames=new Gi({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){if(!this.worded)return;this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,s=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?be(i,t.lng,e.event.utcOffsetHours):void 0,n=JSON.stringify([s?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,re(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey,e.skySources]);if(n===this.skyCandidatesKey)return;if(this.skyCandidatesKey=n,!s||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=e.skySources!==!1,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 xn.gainFor(e.instrument,{fNumber:ee(e,0)?.fNumber,fieldOfViewDeg:Oe.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=V("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=qe(i,s,n),o=l=>l.toLocaleString(void 0,{maximumFractionDigits:1});if(r<qr)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(qe(i,0,n)));return r<=Ki?d:d+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Ki))}showerClause(e,t){const i=Vi.observedRatePerHour(Vi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=Qt.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=Qt.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:Qt.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=ei.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=Zi.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=Sn.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=V("Sun",i.peak,t),n=r=>r.replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),o=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} s`)}return n(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=V("Moon",e,t);if(i.altitudeDeg<=0||Xe(e).illuminatedFraction<.97)return;const s=[],n=Ze.distanceKm(e,t),r=Ze.relativeToMean(Ze.radiusAtKm(n)),o=n<=Ze.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Ze.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(Ze.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),jt.isIn(e)&&s.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),s.length>0?s.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=ve.visibilityAt(e,t),s=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(s!==void 0)return s;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const n=qe(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=ve.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=V("Sun",i.peak.date,t);return s<=qe(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=ee(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=be(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(s=>`${s.object.norad}@${s.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>Yi.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Yi.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,s)=>i.magnitude-s.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,s=i.from[2]-i.to[2],n=Math.abs(s)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/s));return i.t-t.getTime()+n*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const s=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",s.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(s.record.t))).replace("{altitude}",String(Math.round(s.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(s.peak.azimuthDeg)).replace("{distance}",String(Math.round(s.peak.distanceKm/10)*10)).replace("{stations}",String(s.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const s=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=this.aimableFireballs(this.strikingFireballs(s,this.observerAtStart()),s);if(n.length===0)return;const r=n[this.fireballRank++%n.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,s),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=re(this.ufoElement.sighting,0),s=V("Sun",e,t),n=V("Moon",e,t),r=wt.deckLitUntilDeg(wt.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(wt.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(wt.formsAt(a.altitudeDeg,r).map(u=>this.opticsFormName(u))),c=i.iceCrystalAlignment??bi;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=re(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=V("Sun",e,t),n=V("Moon",e,t),r=s.altitudeDeg>0,o=r?s:n;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const a=i.lowerCloudCover??i.cloudCover;if(ti.strength(i.precipitationIntensity,a,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const d=ti.formsAt(o.altitudeDeg);if(d.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(ti.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(Xe(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",l).replace("{lit}",String(h))}glowClause(e,t){const i=V("Sun",e,t);if(i.altitudeDeg>oo)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=V("Moon",e,t),a=s.darkestSkyMagPerArcsec2<ao,d=this.ufoElement.sighting.lightPollution,l=pe.scatteringAt(90-o.altitudeDeg)*pe.moonOutput(pe.phaseAngleOf(Xe(e).illuminatedFraction),o.altitudeDeg)*pe.scatteredFraction(90),h=pe.artificialZenithNanolamberts(d)>l;if(a&&o.altitudeDeg>0&&!h){const u=Math.round(Xe(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(u)).replace("{sky}",r)}const c=pe.artificialZenithNanolamberts(d)>pe.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=V("Sun",e,t),s=V("Moon",e,t);return pe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(Xe(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<ei.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=ei.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const s=be(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=Zi.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}=is(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-Qr-(ee(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 es(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Ye.width/2,y:e.height/2-Ye.height/2,width:Ye.width,height:Ye.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new Ei(this.ufoElement.sighting.timeline,new hr(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"})),L.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=ze.preferencesFor(this);this.preferences=t;const i=ci(t,ui),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([ks.load(i),i==="en"?{}:js(i),Gs(i),sr.load(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.decorParameterTexts=d,this.naming=new ji(a),this.said=new ut(t),this.tagNames=new Gi(o),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new Ji(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===nt&&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(Si))n.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.applyPerceptionLabels(),this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,Ae.say(this.labelAccountUrl,e.accountUrl,e.accountUrlHint),this.labelAccountFollowedUp.textContent=e.accountFollowedUp,this.evaluationFields.messages=e.accountEvaluation;for(const[n,r]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const o=this.shadow.getElementById(n);o&&(o.textContent=r)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.label("label-iso",e.iso),this.label("label-film-stock",e.filmStock),this.filmStockKey=void 0,this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.label("label-sky-sources",e.skySources),this.skySourcesInput.closest("label").title=e.skySourcesHint,this.lensShelteredInput.title=e.lensShelteredTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.shapeAddMenu.panel.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"trafficlight",label:e.decorTrafficLight},{value:"peak",label:e.decorPeak},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const s=this.shadow.getElementById("option-scenery-none");s&&(s.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[n,r]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=r,n.setAttribute("aria-label",r);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.decorBaseShownFor=void 0,this.decorBaseShown=!1,this.decorParametersShownFor=void 0,this.isConnected&&this.syncDecorVisibility(),this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup;for(const n of this.skyParts.values())this.nameSkyPart(n.label,n.titles);for(const n of["location","decor","weather"]){const r=this.shadow.getElementById(`${n}-settings-button`);r?.setAttribute("title",e.dataSources),r?.setAttribute("aria-label",e.dataSources);const o=this.shadow.getElementById(`label-${n}-settings`);o&&(o.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language);for(const n of this.skyParts.values())n.editor?.setLanguage(this.language);this.modulesPanel?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new Ji(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language},this.decorParameterTexts),this.refreshParamSummary(),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelRareIce.textContent=e.rareIceCrystals,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.shadow.getElementById("label-aircraft-group").textContent=e.aircraftGroup,this.aircraftFlights.show(this.sceneElement.aircraftFlights,e,!0),this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.referenceKindSelect.querySelector("#reference-kind-video").textContent=e.referenceVideo,this.shadow.getElementById("label-reference-video-from").textContent=e.referenceVideoFrom,this.shadow.getElementById("label-reference-video-to").textContent=e.referenceVideoTo,this.shadow.getElementById("label-reference-video-rate").textContent=e.referenceVideoRate,this.referenceRemoveKeyButton.textContent=e.referenceRemoveKey,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=this.currentReference()?.kind==="video"?e.referenceVideoT:e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",e.addReferenceLandmark),this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,Ae.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,r]of this.soundKindOptions)r.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e),this.refreshFileItems(),this.refreshSkyCandidates()}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.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"])Fe.popover(this.shadow.getElementById(s),e.close);Fe.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),Fe.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),Fe.button(this.contextMenu,e.close,()=>this.hideContextMenu()),Fe.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 ii(this.selectedMembers()),c=X.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"?X.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&&X.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,Tt);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"&&X.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId,shape:n}:this.ufoElement.shapeAt(t.x,t.y,Tt);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?X.hitTestVertex(d,this.contextMenuPoint):void 0,c=l&&d.points.length<=In;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=X.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=X.hitTestVertex(i,e);if(s===void 0)return;const n=X.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(Mt,(e.maxX-e.minX)/2*t.width),s=Math.max(Mt,(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=Lt,a=Lt+Gr,d=t.width-Lt,l=t.height-r-Lt,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<Mt||p-c<Mt?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=X.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:li};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:Yr};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=Wi.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:it.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,Tt)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=it.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&&ss(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&ss(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=X.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"?X.resizeShape(r,o,t):X.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)<Jr)return;this.cameraDragState.moved=!0}const o=s+(t.x-i.x)*li,a=Math.max(-90,Math.min(90,n-(t.y-i.y)*li));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?so: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)*io*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)*to*t,o=i*Math.PI/180,a=Js(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=Es(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(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(Xi,i.width-Pe);break;case"ArrowRight":i.width+=Pe;break;case"ArrowUp":i.height=Math.max(Xi,i.height-Pe);break;case"ArrowDown":i.height+=Pe;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Pe;break;case"ArrowRight":i.x+=Pe;break;case"ArrowUp":i.y-=Pe;break;case"ArrowDown":i.y+=Pe;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:s,shape:n}=i[0];this.commitShapes(t,[{sourceId:s,shape:{...n,bounds:this.nudgeBounds(n.bounds,e)}}])}else{const s=new ii(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&&X.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&&X.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,Tt)&&this.grabsDecor(e,t,l))return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const a=X.hitTestHandle({bounds:new ii(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"&&X.hitTestVertex(a,t)!==void 0)return"vertex";const d=a&&X.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-${X.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(As(this.buildPrototype({x:0,y:0,width:Ye.width,height:Ye.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 lo={established:"narrativeStated",measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed",fitted:"narrativeAssumed"},ys="rr0-sighting-editor";function Us(){Rs(),xs(),$s(),gr(),pr(),vr(),Ls(),customElements.get(ys)||customElements.define(ys,w)}const vi="rr0-case-editor",ho=`
2755
2755
  <style>
2756
2756
  /* What the layout adapts to: the width this editor is given, never the window's. */
2757
2757
  :host { display: block; container-type: inline-size; }
@@ -2833,15 +2833,19 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
2833
2833
  ${fe.CSS}
2834
2834
  /* ---- The design handoff's look (design_handoff_editeurs_ufoathome, §2 and §4) ---- */
2835
2835
  :host {
2836
- ${Qe.TOKENS}
2836
+ ${He.TOKENS}
2837
2837
  --rr0-field-radius: 8px;
2838
2838
  --rr0-input-font-size: 15px;
2839
2839
  container-type: inline-size;
2840
2840
  font: 400 15px/1.5 var(--sans);
2841
2841
  -webkit-font-smoothing: antialiased;
2842
2842
  }
2843
- ${Qe.HEAD}
2844
- ${Qe.fields(".case")}
2843
+ ${He.HEAD}
2844
+ ${He.fields(".case")}
2845
+ /* The dialog (adding an event, a question) is outside the case's card: its fields and buttons look as the editor's do, not as the
2846
+ browser draws them bare. */
2847
+ ${He.fields("dialog")}
2848
+ dialog { background: var(--ground-raised); color: var(--ink); font: 400 15px/1.5 var(--sans); }
2845
2849
  /* A case is a card, as the observation alone is: the observation it holds draws none of its own then (see SightingEditorElement.embedded). */
2846
2850
  .case.in-case { max-width: 68rem; margin: 0 auto; background: var(--ground-raised); color: var(--ink); border: 1px solid var(--line-strong); border-radius: 12px; overflow: clip; }
2847
2851
  /* Given the width (the app on a computer), the whole of it: the recording's editor lays itself out in two columns from there. */
@@ -2849,7 +2853,7 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
2849
2853
  /* And the case's events stay beside the one open, as the reader's history does (see caseTemplate): the list on the left, kept in sight
2850
2854
  while the event scrolls, the event on the right. Narrower, it is the one or the other, the way back to the case above the event. */
2851
2855
  @container (min-width: 760px) {
2852
- #group-events.one-open { display: grid; grid-template-columns: var(${$e.PROPERTY}, clamp(15rem, 36%, 22rem)) minmax(0, 1fr); column-gap: 18px; align-items: start; }
2856
+ #group-events.one-open { display: grid; grid-template-columns: var(${We.PROPERTY}, clamp(15rem, 36%, 22rem)) minmax(0, 1fr); column-gap: 18px; align-items: start; }
2853
2857
  #group-events.one-open > * { grid-column: 2; }
2854
2858
  #group-events.one-open > #case-overview[hidden] { display: block !important; }
2855
2859
  #group-events.one-open > #case-overview { grid-column: 1; grid-row: 1 / span 6; position: sticky; top: 0; max-height: var(--rr0-editor-height, 100dvh); overflow: auto; overscroll-behavior: contain; }
@@ -2913,7 +2917,7 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
2913
2917
  .section-title { margin: 0; font: 600 12px/1.3 var(--sans); letter-spacing: .12em; text-transform: uppercase; color: var(--glow-dim); }
2914
2918
  /* The chronology is common to the case's reader (see CaseTimeline), in the editor's tokens; what follows is the editor's own. */
2915
2919
  ${Be.CSS}
2916
- ${$e.CSS}
2920
+ ${We.CSS}
2917
2921
  /* The case's column at its narrowest: its events' marks, nothing of the case's fields or of the list's head. */
2918
2922
  @container case-overview (max-width: 6rem) {
2919
2923
  #case-overview > :not(.event-list) { display: none !important; }
@@ -2929,6 +2933,10 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
2929
2933
  .event-card:has(.event-tool) .event-main { margin-right: 100px; }
2930
2934
  /* The filter over the list: a button per kind, lit while its events are shown, with how many of them the case holds. */
2931
2935
  .event-filter { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 10px; }
2936
+ .events-search { box-sizing: border-box; width: 100%; margin: 0 0 10px; padding: 5px 12px; border: 1px solid var(--line-strong);
2937
+ border-radius: 999px; background: transparent; color: inherit; font: 13px/1.4 var(--rr0-sans, system-ui, sans-serif); }
2938
+ .events-search[hidden], .events-none[hidden] { display: none; }
2939
+ .events-none { margin: 0 0 10px; font: 13px/1.4 var(--rr0-sans, system-ui, sans-serif); color: var(--ink-faint); }
2932
2940
  .event-filter[hidden] { display: none; }
2933
2941
  .filter-chip { display: inline-flex; align-items: center; gap: 6px; min-height: 0; padding: 3px 10px; border: 1px solid var(--line-strong); border-radius: 999px;
2934
2942
  background: none; color: var(--ink-dim); font: 600 12px/1.6 var(--sans); cursor: pointer; }
@@ -3031,8 +3039,8 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
3031
3039
  </header>
3032
3040
  <rr0-share-dialog id="share-dialog"></rr0-share-dialog>
3033
3041
  <div id="case-tabs" class="group-tabs">
3034
- <button class="group-tab" type="button" aria-controls="group-events" aria-expanded="true">${M.CLOCK}<span id="label-events-group"></span> <span id="events-count" class="count"></span></button>
3035
- <button class="group-tab" type="button" aria-controls="group-case-file" aria-expanded="false">${M.FILES}<span id="label-case-file-group"></span></button>
3042
+ <button class="group-tab" type="button" aria-controls="group-events" aria-expanded="true">${L.CLOCK}<span id="label-events-group"></span> <span id="events-count" class="count"></span></button>
3043
+ <button class="group-tab" type="button" aria-controls="group-case-file" aria-expanded="false">${L.FILES}<span id="label-case-file-group"></span></button>
3036
3044
  </div>
3037
3045
  </section>
3038
3046
  <section class="group-panel" id="group-events" aria-labelledby="label-events-group">
@@ -3051,6 +3059,9 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
3051
3059
  </div>
3052
3060
  <!-- What the list shows, by kind: a way of reading the chronology, never written in the case (see renderFilter). -->
3053
3061
  <div id="event-filter" class="event-filter" role="group" hidden></div>
3062
+ <!-- Only the events whose words hold what is typed here (see CaseTimeline.search), as in the case's reader. -->
3063
+ <input id="events-search" class="events-search" type="search" autocomplete="off" spellcheck="false" hidden>
3064
+ <p id="events-none" class="events-none" role="status" hidden></p>
3054
3065
  <ol id="event-list" class="event-list"></ol>
3055
3066
  <rr0-readings-comparison id="readings-comparison" class="readings-comparison"></rr0-readings-comparison>
3056
3067
  </div>
@@ -3058,7 +3069,7 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
3058
3069
  <!-- Laid out as every list of the editor is (see ElementList): the picker, 🗑, "+", then the frame of the event picked. -->
3059
3070
  <div id="events-row" class="element-list-row">
3060
3071
  <label class="element-list-picker"><select id="track"></select></label>
3061
- <button id="delete" type="button" class="icon-btn">${M.TRASH}</button>
3072
+ <button id="delete" type="button" class="icon-btn">${L.TRASH}</button>
3062
3073
  </div>
3063
3074
  <div id="event-item" class="element-list-body">
3064
3075
  <!-- The event open, in the case: the way back to it, what kind of event above which, as its card says it, and its Undo and Redo. -->
@@ -3128,10 +3139,10 @@ ${F.rules([],[".model-picker .model-picker-address p"])}
3128
3139
  <label class="check"><input id="export-recordings" type="checkbox" checked/> <span id="label-export-recordings"></span></label>
3129
3140
  </div>
3130
3141
  <div class="actions">
3131
- <button id="ok" type="submit" value="ok"></button>
3132
- <button id="cancel" type="button"></button>
3142
+ <button id="ok" type="submit" value="ok" class="pill-btn primary"></button>
3143
+ <button id="cancel" type="button" class="pill-btn"></button>
3133
3144
  </div>
3134
3145
  </form>
3135
3146
  </dialog>
3136
- `;class Le extends HTMLElement{shadow=this.attachShadow({mode:"open"});editor;session;current;listShown=!0;currentInterview;interviewElement;interviewReady;group="events";fileEditor;fileEditorLoading;fileApplied="";editorMessages;messages=je.none();ready=Promise.resolve();said=new ut(["en"]);localeToken=0;language="en";dialogMode="add";pendingLoad;dirtyTimer;caseDate;dateModeFor;constructor(){super(),Us(),Rs(),Ds.register(),this.shadow.innerHTML=ho,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 $e(this.byId("column-resize"),this.byId("group-events"),()=>this.byId("case-overview"),$e.CASE_HISTORY_KEY,$e.PROPERTY,44),this.interviewElement=this.shadow.getElementById("interview"),this.interviewElement.addEventListener(Xs,e=>this.interviewChanged(e.detail)),this.interviewElement.addEventListener(Qs,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(),Le.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?Le.rr0TimeOf(Un(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,Be.rememberGrouping(this.grouping),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"),en.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",gt]}attributeChangedCallback(e,t,i){e===gt&&(i!==null&&!this.switcher&&new Ks(s=>this.after(s),this,s=>this.dispatchEvent(new CustomEvent(Vs,{detail:s,bubbles:!0,composed:!0}))),this.refreshCaseState()),e==="src"&&i&&this.editor.setAttribute("src",i)}warnBeforeLeaving=e=>{this.leaving||!this.dirty||(e.preventDefault(),e.returnValue="")};disconnectedCallback(){document.removeEventListener("click",this.askBeforeFollowing,!0),window.removeEventListener("beforeunload",this.warnBeforeLeaving),window.clearTimeout(this.dirtyTimer)}get dirty(){return this.session?(this.commit(),this.session.dirty):this.editor.dirty}scheduleDirtyCheck(){window.clearTimeout(this.dirtyTimer),this.dirtyTimer=window.setTimeout(()=>this.refreshDirty(),600)}refreshDirty(){const e=this.session;e&&this.commit(),this.byId("dirty").hidden=!(e&&e.dirty),this.refreshCaseState();const t=e?this.current!==void 0&&e.changed(this.current):this.editor.dirty;this.byId("recording-dirty").hidden=!t}leaving=!1;askBeforeFollowing=e=>{if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const t=e.composedPath().find(s=>s instanceof HTMLAnchorElement);if(!t||!t.href||t.target&&t.target!=="_self"||t.hasAttribute("download"))return;const i=new URL(t.href,location.href);i.href===location.href||i.origin===location.origin&&i.pathname===location.pathname&&i.search===location.search&&i.hash!==""||this.dirty&&(e.preventDefault(),e.stopPropagation(),this.pendingLoad=()=>{this.leaving=!0,location.assign(i.href)},this.openDialog("discard",this.messages.discardTitle,this.messages.leaveQuestion,this.messages.leaveOk))};connectedCallback(){document.addEventListener("click",this.askBeforeFollowing,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.editor.getAttribute("src")!==e&&this.editor.setAttribute("src",e),this.ready=this.loadLocale()}get sightingData(){return this.editor.sightingData}set sightingData(e){const t=We.recording(e);this.closeCase(),this.editor.sightingData=t}get sightingEditor(){return this.editor}get caseSession(){return this.session}byId(e){return this.shadow.getElementById(e)}async loadLocale(){const e=++this.localeToken,t=ze.preferencesFor(this),i=ci(t,ui),[s,n,r]=await Promise.all([qs.load(i),ks.load(i),Mn.load(i)]);if(e!==this.localeToken)return;this.said=new ut(t),this.language=i,this.messages=s,this.readingCheck=new Qi(r),this.bestCases=new Ln(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(){Fe.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"){F.show(this.byId("case-file-note"),e,t)}fileText(){return this.session?JSON.stringify(this.session.json,null,2)+`
3137
- `:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{await this.ready,this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([L(()=>import("./SightingFileEditor-Cllslp2u.js"),__vite__mapDeps([12,13,14]),import.meta.url),L(()=>import("./caseSchema-ChUB1-9j.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,s=>this.onFileEdited(s),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid,"error");return}if(!se.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{se.check(i)}catch(s){this.showFileNote(s instanceof Rt?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 Xe.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!se.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof Rt?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){se.check(e);const s=new de(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=We.recording(await Xe.recording(e.url)),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.editor.passages=void 0,this.editor.holdForNewScene();try{const i=!e.recording;await this.loadTrack(e);const s=t.accountOf(e);s&&await this.loadTrack(s),this.layMostFavourable(e),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&s?.recording?Le.shapesOf(s.recording):void 0;const n=e.kind==="observer"?t.readingsOf(e):[];for(const r of n)await this.loadTrack(r).catch(()=>{}),this.layMostFavourable(r);this.editor.readings=n.filter(r=>r.recording?.interpretation?.bodies.length||Dt.computes(r.recording?.interpretation,At.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 L(async()=>{const{InterviewFile:o}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:o}},__vite__mapDeps([34,1]),import.meta.url),s=this.items(e),n=e.interviews.length===1,r=[];for(const o of e.interviews){const 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=hi.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=hi.strip(t.recording).recording.lighting;this.editor.setReadingBounds({...typeof o=="string"?{time:o}:{},...l?{hour:c=>Qi.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 L(async()=>{const{InterviewFile:n}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:n}},__vite__mapDeps([34,1]),import.meta.url),s=t.transcriptText(e);if(s!==void 0)return i.read(JSON.parse(s));if(e.url)return i.read(await Xe.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 L(async()=>{const{InterviewFile:a}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:a}},__vite__mapDeps([34,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??=L(async()=>{const{register:e}=await import("./InterviewEditorElement-CbTakhyi.js");return{register:e}},__vite__mapDeps([35,1,3,4,5,6,7,8,9,36,19,37,34,18,20,21,22,23,24]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,s=this.currentInterview;if(!(!i||!s)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(s,e.text);for(const n of[s.interviewOf].flat()){const r=i.tracks.find(o=>o.kind==="observer"&&(o.event.id??i.proposedId(o))===n);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}eventsInTime(e){const t=this.items(e);return Be.inTime(t,{when:i=>String((i.track?.event??i.interview)?.time??""),kind:i=>this.kindOf(i),read:i=>{const s=i.track?.kind==="reading"?e.accountOf(i.track):void 0;return s?[{track:s}]:[]}})}momentsOf(e){return(e.recording?.milestones??[]).map(t=>{const i=this.said.read(t.note);return{at:t.t/1e3,label:this.said.read(t.label)??"",...i?{note:i}:{}}})}citedFrom;showCited(e,t,i){const s=this.byId("cited");if(this.citedFrom=e,!e||!this.session){s.hidden=!0;return}const n=this.momentsOf(t).find(o=>Math.abs(o.at-i.at)<.05),r=(i.quote??"").length>120?`${i.quote.slice(0,117)}…`:i.quote??"";this.byId("cited-text").textContent=this.messages.citedMoment.replace("{k}",n?.label??`${Math.round(i.at)} s`).replace("{title}",this.optionLabel({interview:e},0)).replace("{quote}",r),s.hidden=!1}kindOf(e){return e.interview?"interview":e.track.kind==="reading"?"reading":"observation"}kindLabel(e){return Be.kindLabel(e,this.messages)}refreshOverview(){const e=this.session,t=this.byId("case-overview"),i=this.byId("event-crumbs");if(t.hidden=!e||!this.listShown,i.hidden=!e||this.listShown,this.byId("event-item").hidden=e!==void 0&&this.listShown,this.byId("group-events").classList.toggle("one-open",e!==void 0&&!this.listShown),this.byId("events-count").textContent=e?String(this.items(e).length):"",this.byId("case-heading").textContent=e&&String(e.json.title??"")||this.messages.caseHeading,!e)return;const s=this.eventsInTime(e);this.renderEvents(e,s),this.compareReadings(e);const n=s.findIndex(({item:o})=>o.interview?o.interview===this.currentInterview:o.track===this.current),r=s[n];if(r){const o=this.kindOf(r.item),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)}}authorName(e){if("people"in e)return e.people;if("org"in e)return e.org;const t=e;return this.said.read(t.title)??t.id??""}authorsText(e){return(e??[]).map(t=>this.authorName(t)).filter(t=>t!=="").join(", ")}authorsSaid(e){const t=(e??[]).map(i=>this.authorName(i)).filter(i=>i!=="");return t.length<2?t.join(""):`${t.slice(0,-1).join(", ")} ${this.messages.linkAnd} ${t[t.length-1]}`}authorsFrom(e,t){const i=e.split(",").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.map(s=>(t??[]).find(n=>this.authorName(n)===s)??{title:s})}grouping=Be.groupingRemembered();columns;folded=new Set;kindsShown=new Set(["observation","interview","reading"]);renderFilter(e){const t=this.messages,i=this.byId("event-filter"),s=["observation","reading","interview"].map(n=>({kind:n,count:e.filter(({item:r})=>this.kindOf(r)===n).length})).filter(({count:n})=>n>0);i.hidden=s.length<2,!i.hidden&&i.replaceChildren(...s.map(({kind:n,count:r})=>{const o=this.kindsShown.has(n),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:p})=>this.kindsShown.has(this.kindOf(p)));this.renderFilter(t),this.byId("events-count").textContent=String(n.length);const r=p=>{const m=[p.track?.event.interpretationOf].flat().filter(f=>f!==void 0);return n.map(({item:f})=>f).filter(f=>f.track?.kind==="observer"&&m.some(g=>f.track.event.id===g||f.track.recording?.id===g))},o=n.some(({item:p})=>this.kindOf(p)==="reading"),a=this.byId("group-readings");a.hidden=!o,a.setAttribute("aria-pressed",String(this.grouping));const d=this.grouping?Be.grouped(n,{kind:p=>this.kindOf(p),read:r}):n,l=new Map(n.map(({item:p,index:m})=>[p,m])),h=p=>!this.listShown&&(p.interview?p.interview===this.currentInterview:p.track===this.current),u=d.filter(({item:p,under:m})=>m===void 0||!this.folded.has(l.get(m))||h(p)).map(({item:p,index:m,under:f})=>{const g=this.kindOf(p),b=p.track?.event??p.interview,v={at:m,kind:g,title:this.optionLabel(p,m),meta:[b.time?String(b.time).replace("T"," "):"",b.id??""].filter(Boolean).join(" · "),by:g==="observation"?"":this.authorsSaid(b.by),open:h(p),...f?{nested:!0}:{}},I=this.grouping&&g==="observation"?d.filter(x=>x.under===p).length:0;if(I>0&&(v.readings={count:I,folded:this.folded.has(m)}),p.track?.kind==="observer"){const x=e.interviews.filter(y=>e.intervieweesOf(y).includes(p.track)).map(y=>({at:e.tracks.length+e.interviews.indexOf(y),title:this.optionLabel({interview:y},0)}));x.length>0&&(v.links={heading:i.passagesHeading,to:x})}else if(p.track){const x=[p.track.event.interpretationOf].flat().filter(y=>y!==void 0).map(y=>e.tracks.find(S=>S.kind==="observer"&&(S.event.id===y||S.recording?.id===y))).filter(y=>y!==void 0).filter(y=>y!==f?.track).map(y=>({at:e.tracks.indexOf(y),title:this.labelOf(y,e.tracks.indexOf(y))}));x.length>0&&(v.links={heading:f?i.alsoAbout:i.interpretationOf,to:x})}return v});new Be(s,p=>this.openEvent(p),p=>this.openEvent(p),void 0,p=>{this.folded.delete(p)||this.folded.add(p),this.refreshOverview()}).render(u,i,(p,{card:m,body:f,links:g})=>this.dress(e,t.find(({index:b})=>b===p.at).item,p.at,m,f,g))}dress(e,t,i,s,n,r){const o=this.messages,a=r.textContent!=="",d=t.track?.kind==="reading"?this.findingsOf(t.track):void 0,l=Dn.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&&de.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=M.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?M.LOCK:M.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=M.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=An.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||(!de.sealed(s.event)&&this.current===s&&this.commit(),t.seal(s,!de.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&&de.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&&de.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(gt)&&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(gt)){const i=this.holdForReading();if(Zs.ask(this,Ys,i))return;_e.releaseCopies()}if(e===void 0)return;const t=this.session?this.sharedTrack:void 0;window.open(`${fi.home()}/play/?file=${encodeURIComponent(e)}${t?`&events=${encodeURIComponent(Le.fileKey(t))}`:""}`,"_blank","noopener")}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}holdForReading(){const e=new Map,t=this.session;if(t){this.commit();const n=this.sourceUrl===void 0;e.set(t.url,{json:t.json,changed:t.dirty,local:n});for(const r of t.tracks)r.recording&&e.set(r.url,{json:r.recording,changed:t.changed(r),local:n});return _e.releaseCopies(),_e.hold(e),{src:t.url,...this.sharedTrack?{track:this.sharedTrack}:{}}}const i=this.editor.address,s=i??new URL("recording.json",location.href).href;return e.set(s,{json:this.editor.sightingData,changed:this.editor.dirty,local:i===void 0}),_e.releaseCopies(),_e.hold(e),{src:s}}askBeforeReplacing(e){this.guarded(()=>{this.leaving=!0,e()})}async openTrack(e){const t=this.session;if(!t)return;const i=new URL(e,location.href).href,s=t.tracks.find(n=>n.url===i);!s||s===this.current&&!this.listShown&&!this.currentInterview||(this.listShown=!1,await this.showTrack(s))}sourceUrl;shareDialog;shareMessages;get sharedTrack(){return this.currentInterview?void 0:this.current?.url}shareSubject={module:"rr0-sighting-editor",link:()=>{const e=this.sharedTrack;return`${fi.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){tn.register();const t=this.byId("readings-comparison");t.toggleAttribute("data-filtered",!this.kindsShown.has("reading"));const i=()=>e.tracks.flatMap((s,n)=>{if(s.kind!=="reading")return[];const r=e.accountOf(s);return[{title:this.labelOf(s,n),witness:r?this.labelOf(r,e.tracks.indexOf(r)):"",...s.recording?{reading:s.recording}:{},...r?.recording?{account:r.recording}:{},open:()=>this.openFromTable(e,s)}]});t.show(i(),async()=>{const s=e.tracks.filter(n=>n.kind==="reading").flatMap(n=>[n,e.accountOf(n)]).filter(n=>n!==void 0&&!n.recording);return await Promise.all([...new Set(s)].map(n=>this.loadTrack(n).catch(()=>{}))),i()})}openFromTable(e,t){const i=this.items(e).findIndex(n=>n.track===t);if(i<0)return;const s=this.byId("track");s.value=String(i),s.dispatchEvent(new Event("change"))}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const s=this.session.tracks.filter(n=>n.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(s||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time,i=typeof t=="object"?t.value:t,s=i?Le.rr0TimeOf(i):void 0,n=this.said.read(e.observer?.title),r=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=de.around(e,s,n,r,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:_n(Le.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const s=this.input("case-time");s.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&at.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&&de.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 L(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value,t=e==="interview",i=this.byId("source").value,s=e==="reading";this.byId("row-source").hidden=t,this.byId("row-of").hidden=!s,this.byId("row-witness").hidden=!t,this.byId("row-medium").hidden=!t,t&&this.fillMedia(),this.byId("row-file").hidden=t||i!=="file",this.byId("row-observer").hidden=t||s,this.byId("row-title").hidden=!(t||s),this.byId("row-author").hidden=!(t||s),this.byId("label-title").textContent=t?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=t?this.messages.interviewerField:this.messages.investigatorField;const n=this.input("date");n.disabled=s,s&&(n.value=this.today())}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const c=e.tracks[Number(this.byId("witness").value)],u=this.input("title").value.trim(),p=this.input("author").value.trim(),m=e.addInterview(c,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?p.split(",").map(f=>({people:f.trim()})).filter(f=>f.people!==""):void 0,this.byId("medium").value);return await this.showInterview(m),!0}const t=this.byId("of").value,i=this.byId("kind").value==="reading"&&t!==""?e.tracks[Number(t)]:void 0,s=this.byId("source").value;if(i&&s==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const c=this.input("title").value.trim(),u=this.input("author").value.trim(),p=e.addReading(i,this.input("date").value||this.today(),c!==""?c:void 0,u!==""?[{title:u}]:void 0);return this.showTrack(p),!0}const n=this.input("observer").value.trim(),r=this.input("date").value.trim();let o;try{if(s==="blank"){const c=(n||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";o={version:4,id:`${r?`${r}-`:""}${c}`,...n?{observer:{title:n}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const c=await this.readFile();if(se.isCase(c))return this.showError(this.messages.isACase),!1;o=c,n&&!o.observer?.title&&(o={...o,observer:{...o.observer,title:n}})}}catch{return this.showError(this.messages.loadFailed),!1}const 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 Xe.recording(new URL(e.url,location.href).href);const t=e.file,i=await new Promise((s,n)=>{const r=new FileReader;r.onload=()=>s(r.result),r.onerror=()=>n(r.error),r.readAsText(t)});return JSON.parse(i)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(o=>o.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const s=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,s&&this.showTrack(s))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const o of t.tracks)await this.loadTrack(o)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:s,strToU8:n}=await L(async()=>{const{zipSync:o,strToU8:a}=await import("./browser-CltifEM0.js");return{zipSync:o,strToU8:a}},[],import.meta.url),r={};for(const o of i)r[o.path]=n(o.content);return this.download(new Blob([s(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}}function co(){Us(),customElements.get(vi)||customElements.define(vi,Le)}const So=Object.freeze(Object.defineProperty({__proto__:null,CASE_EDITOR_ELEMENT_NAME:vi,CaseEditorElement:Le,register:co},Symbol.toStringTag,{value:"Module"}));export{So as C,De as I,fs as M};
3147
+ `;class Le extends HTMLElement{shadow=this.attachShadow({mode:"open"});editor;session;current;listShown=!0;currentInterview;interviewElement;interviewReady;group="events";fileEditor;fileEditorLoading;fileApplied="";editorMessages;messages=Ge.none();ready=Promise.resolve();said=new ut(["en"]);localeToken=0;language="en";dialogMode="add";pendingLoad;dirtyTimer;caseDate;dateModeFor;constructor(){super(),Us(),Rs(),Ds.register(),this.shadow.innerHTML=ho,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 We(this.byId("column-resize"),this.byId("group-events"),()=>this.byId("case-overview"),We.CASE_HISTORY_KEY,We.PROPERTY,44),this.interviewElement=this.shadow.getElementById("interview"),this.interviewElement.addEventListener(Xs,e=>this.interviewChanged(e.detail)),this.interviewElement.addEventListener(Qs,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(),Le.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?Le.rr0TimeOf(Un(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,Be.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"),en.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",gt]}attributeChangedCallback(e,t,i){e===gt&&(i!==null&&!this.switcher&&new Ks(s=>this.after(s),this,s=>this.dispatchEvent(new CustomEvent(Vs,{detail:s,bubbles:!0,composed:!0}))),this.refreshCaseState()),e==="src"&&i&&this.editor.setAttribute("src",i)}warnBeforeLeaving=e=>{this.leaving||!this.dirty||(e.preventDefault(),e.returnValue="")};disconnectedCallback(){document.removeEventListener("click",this.askBeforeFollowing,!0),window.removeEventListener("beforeunload",this.warnBeforeLeaving),window.clearTimeout(this.dirtyTimer)}get dirty(){return this.session?(this.commit(),this.session.dirty):this.editor.dirty}scheduleDirtyCheck(){window.clearTimeout(this.dirtyTimer),this.dirtyTimer=window.setTimeout(()=>this.refreshDirty(),600)}refreshDirty(){const e=this.session;e&&this.commit(),this.byId("dirty").hidden=!(e&&e.dirty),this.refreshCaseState();const t=e?this.current!==void 0&&e.changed(this.current):this.editor.dirty;this.byId("recording-dirty").hidden=!t}leaving=!1;askBeforeFollowing=e=>{if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const t=e.composedPath().find(s=>s instanceof HTMLAnchorElement);if(!t||!t.href||t.target&&t.target!=="_self"||t.hasAttribute("download"))return;const i=new URL(t.href,location.href);i.href===location.href||i.origin===location.origin&&i.pathname===location.pathname&&i.search===location.search&&i.hash!==""||this.dirty&&(e.preventDefault(),e.stopPropagation(),this.pendingLoad=()=>{this.leaving=!0,location.assign(i.href)},this.openDialog("discard",this.messages.discardTitle,this.messages.leaveQuestion,this.messages.leaveOk))};connectedCallback(){document.addEventListener("click",this.askBeforeFollowing,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.editor.getAttribute("src")!==e&&this.editor.setAttribute("src",e),this.ready=this.loadLocale()}get sightingData(){return this.editor.sightingData}set sightingData(e){const t=je.recording(e);this.closeCase(),this.editor.sightingData=t}get sightingEditor(){return this.editor}get caseSession(){return this.session}byId(e){return this.shadow.getElementById(e)}async loadLocale(){const e=++this.localeToken,t=ze.preferencesFor(this),i=ci(t,ui),[s,n,r]=await Promise.all([qs.load(i),ks.load(i),Mn.load(i)]);if(e!==this.localeToken)return;this.said=new ut(t),this.language=i,this.messages=s,this.readingCheck=new Qi(r),this.bestCases=new Ln(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(){Fe.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"){F.show(this.byId("case-file-note"),e,t)}fileText(){return this.session?JSON.stringify(this.session.json,null,2)+`
3148
+ `:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{await this.ready,this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([D(()=>import("./SightingFileEditor-Cllslp2u.js"),__vite__mapDeps([12,13,14]),import.meta.url),D(()=>import("./caseSchema-ChUB1-9j.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,s=>this.onFileEdited(s),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid,"error");return}if(!se.isCase(i)){this.showFileNote(this.messages.fileInvalid,"error");return}try{se.check(i)}catch(s){this.showFileNote(s instanceof Rt?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 Qe.json(t);this.guarded(()=>void this.importCase(i,t,!0))}catch{this.showFileNote(this.messages.loadFailed,"error")}}async importCase(e,t,i){if(!se.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t,i)}catch(s){this.showFileNote(s instanceof Rt?s.said(this.messages.formatVersionError):this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t,i){se.check(e);const s=new de(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=je.recording(await Qe.recording(e.url)),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.editor.passages=void 0,this.editor.holdForNewScene();try{const i=!e.recording;await this.loadTrack(e);const s=t.accountOf(e);s&&await this.loadTrack(s),this.layMostFavourable(e),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&s?.recording?Le.shapesOf(s.recording):void 0;const n=e.kind==="observer"?t.readingsOf(e):[];for(const r of n)await this.loadTrack(r).catch(()=>{}),this.layMostFavourable(r);this.editor.readings=n.filter(r=>r.recording?.interpretation?.bodies.length||Dt.computes(r.recording?.interpretation,At.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 D(async()=>{const{InterviewFile:o}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:o}},__vite__mapDeps([34,1]),import.meta.url),s=this.items(e),n=e.interviews.length===1,r=[];for(const o of e.interviews){const 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=hi.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=hi.strip(t.recording).recording.lighting;this.editor.setReadingBounds({...typeof o=="string"?{time:o}:{},...l?{hour:c=>Qi.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 D(async()=>{const{InterviewFile:n}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:n}},__vite__mapDeps([34,1]),import.meta.url),s=t.transcriptText(e);if(s!==void 0)return i.read(JSON.parse(s));if(e.url)return i.read(await Qe.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 D(async()=>{const{InterviewFile:a}=await import("./interviewJson-D-i14LTf.js");return{InterviewFile:a}},__vite__mapDeps([34,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??=D(async()=>{const{register:e}=await import("./InterviewEditorElement-DjQuGytO.js");return{register:e}},__vite__mapDeps([35,1,3,4,5,6,7,8,9,36,19,37,34,18,20,21,22,23,24]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,s=this.currentInterview;if(!(!i||!s)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(s,e.text);for(const n of[s.interviewOf].flat()){const r=i.tracks.find(o=>o.kind==="observer"&&(o.event.id??i.proposedId(o))===n);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}eventsInTime(e){const t=this.items(e);return Be.inTime(t,{when:i=>String((i.track?.event??i.interview)?.time??""),kind:i=>this.kindOf(i),read:i=>{const s=i.track?.kind==="reading"?e.accountOf(i.track):void 0;return s?[{track:s}]:[]}})}momentsOf(e){return(e.recording?.milestones??[]).map(t=>{const i=this.said.read(t.note);return{at:t.t/1e3,label:this.said.read(t.label)??"",...i?{note:i}:{}}})}citedFrom;showCited(e,t,i){const s=this.byId("cited");if(this.citedFrom=e,!e||!this.session){s.hidden=!0;return}const n=this.momentsOf(t).find(o=>Math.abs(o.at-i.at)<.05),r=(i.quote??"").length>120?`${i.quote.slice(0,117)}…`:i.quote??"";this.byId("cited-text").textContent=this.messages.citedMoment.replace("{k}",n?.label??`${Math.round(i.at)} s`).replace("{title}",this.optionLabel({interview:e},0)).replace("{quote}",r),s.hidden=!1}kindOf(e){return e.interview?"interview":e.track.kind==="reading"?"reading":"observation"}kindLabel(e){return Be.kindLabel(e,this.messages)}refreshOverview(){const e=this.session,t=this.byId("case-overview"),i=this.byId("event-crumbs");if(t.hidden=!e||!this.listShown,i.hidden=!e||this.listShown,this.byId("event-item").hidden=e!==void 0&&this.listShown,this.byId("group-events").classList.toggle("one-open",e!==void 0&&!this.listShown),this.byId("events-count").textContent=e?String(this.items(e).length):"",this.byId("case-heading").textContent=e&&String(e.json.title??"")||this.messages.caseHeading,!e)return;const s=this.eventsInTime(e);this.renderEvents(e,s),this.compareReadings(e);const n=s.findIndex(({item:o})=>o.interview?o.interview===this.currentInterview:o.track===this.current),r=s[n];if(r){const o=this.kindOf(r.item),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)}}authorName(e){if("people"in e)return e.people;if("org"in e)return e.org;const t=e;return this.said.read(t.title)??t.id??""}authorsText(e){return(e??[]).map(t=>this.authorName(t)).filter(t=>t!=="").join(", ")}authorsSaid(e){const t=(e??[]).map(i=>this.authorName(i)).filter(i=>i!=="");return t.length<2?t.join(""):`${t.slice(0,-1).join(", ")} ${this.messages.linkAnd} ${t[t.length-1]}`}authorsFrom(e,t){const i=e.split(",").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.map(s=>(t??[]).find(n=>this.authorName(n)===s)??{title:s})}grouping=Be.groupingRemembered();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(E=>E!==void 0);return n.map(({item:E})=>E).filter(E=>E.track?.kind==="observer"&&v.some(x=>E.track.event.id===x||E.track.recording?.id===x))},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?Be.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:E})=>{const x=this.kindOf(b),S=b.track?.event??b.interview,I={at:v,kind:x,title:this.optionLabel(b,v),meta:[S.time?String(S.time).replace("T"," "):"",S.id??""].filter(Boolean).join(" · "),by:x==="observation"?"":this.authorsSaid(S.by),open:h(b),...E?{nested:!0}:{}},C=this.grouping&&x==="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(T=>e.intervieweesOf(T).includes(b.track)).map(T=>({at:e.tracks.length+e.interviews.indexOf(T),title:this.optionLabel({interview:T},0)}));R.length>0&&(I.links={heading:i.passagesHeading,to:R})}else if(b.track){const R=[b.track.event.interpretationOf].flat().filter(T=>T!==void 0).map(T=>e.tracks.find(Z=>Z.kind==="observer"&&(Z.event.id===T||Z.recording?.id===T))).filter(T=>T!==void 0).filter(T=>T!==E?.track).map(T=>({at:e.tracks.indexOf(T),title:this.labelOf(T,e.tracks.indexOf(T))}));R.length>0&&(I.links={heading:E?i.alsoAbout:i.interpretationOf,to:R})}return I}),p=new Be(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:E,links:x})=>this.dress(e,t.find(({index:S})=>S===b.at).item,b.at,v,E,x));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=Dn.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&&de.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=L.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?L.LOCK:L.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=L.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=An.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||(!de.sealed(s.event)&&this.current===s&&this.commit(),t.seal(s,!de.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&&de.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&&de.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(gt)&&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(gt)){const i=this.holdForReading();if(Zs.ask(this,Ys,i))return;_e.releaseCopies()}if(e===void 0)return;const t=this.session?this.sharedTrack:void 0;window.open(`${fi.home()}/play/?file=${encodeURIComponent(e)}${t?`&events=${encodeURIComponent(Le.fileKey(t))}`:""}`,"_blank","noopener")}static fileKey(e){return new URL(e,location.href).pathname.split("/").pop().replace(/\.json$/i,"")}holdForReading(){const e=new Map,t=this.session;if(t){this.commit();const n=this.sourceUrl===void 0;e.set(t.url,{json:t.json,changed:t.dirty,local:n});for(const r of t.tracks)r.recording&&e.set(r.url,{json:r.recording,changed:t.changed(r),local:n});return _e.releaseCopies(),_e.hold(e),{src:t.url,...this.sharedTrack?{track:this.sharedTrack}:{}}}const i=this.editor.address,s=i??new URL("recording.json",location.href).href;return e.set(s,{json:this.editor.sightingData,changed:this.editor.dirty,local:i===void 0}),_e.releaseCopies(),_e.hold(e),{src:s}}askBeforeReplacing(e){this.guarded(()=>{this.leaving=!0,e()})}async openTrack(e){const t=this.session;if(!t)return;const i=new URL(e,location.href).href,s=t.tracks.find(n=>n.url===i);!s||s===this.current&&!this.listShown&&!this.currentInterview||(this.listShown=!1,await this.showTrack(s))}sourceUrl;shareDialog;shareMessages;get sharedTrack(){return this.currentInterview?void 0:this.current?.url}shareSubject={module:"rr0-sighting-editor",link:()=>{const e=this.sharedTrack;return`${fi.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){tn.register();const t=this.byId("readings-comparison");t.toggleAttribute("data-filtered",!this.kindsShown.has("reading"));const i=()=>e.tracks.flatMap((s,n)=>{if(s.kind!=="reading")return[];const r=e.accountOf(s);return[{title:this.labelOf(s,n),witness:r?this.labelOf(r,e.tracks.indexOf(r)):"",...s.recording?{reading:s.recording}:{},...r?.recording?{account:r.recording}:{},open:()=>this.openFromTable(e,s)}]});t.show(i(),async()=>{const s=e.tracks.filter(n=>n.kind==="reading").flatMap(n=>[n,e.accountOf(n)]).filter(n=>n!==void 0&&!n.recording);return await Promise.all([...new Set(s)].map(n=>this.loadTrack(n).catch(()=>{}))),i()})}openFromTable(e,t){const i=this.items(e).findIndex(n=>n.track===t);if(i<0)return;const s=this.byId("track");s.value=String(i),s.dispatchEvent(new Event("change"))}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const s=this.session.tracks.filter(n=>n.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(s||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time,i=typeof t=="object"?t.value:t,s=i?Le.rr0TimeOf(i):void 0,n=this.said.read(e.observer?.title),r=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=de.around(e,s,n,r,location.href),this.listShown=!1,this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:_n(Le.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const s=this.input("case-time");s.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&at.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&&de.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 D(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value,t=e==="interview",i=this.byId("source").value,s=e==="reading";this.byId("row-source").hidden=t,this.byId("row-of").hidden=!s,this.byId("row-witness").hidden=!t,this.byId("row-medium").hidden=!t,t&&this.fillMedia(),this.byId("row-file").hidden=t||i!=="file",this.byId("row-observer").hidden=t||s,this.byId("row-title").hidden=!(t||s),this.byId("row-author").hidden=!(t||s),this.byId("label-title").textContent=t?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=t?this.messages.interviewerField:this.messages.investigatorField;const n=this.input("date");n.disabled=s,s&&(n.value=this.today())}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const c=e.tracks[Number(this.byId("witness").value)],u=this.input("title").value.trim(),p=this.input("author").value.trim(),m=e.addInterview(c,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?p.split(",").map(f=>({people:f.trim()})).filter(f=>f.people!==""):void 0,this.byId("medium").value);return await this.showInterview(m),!0}const t=this.byId("of").value,i=this.byId("kind").value==="reading"&&t!==""?e.tracks[Number(t)]:void 0,s=this.byId("source").value;if(i&&s==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const c=this.input("title").value.trim(),u=this.input("author").value.trim(),p=e.addReading(i,this.input("date").value||this.today(),c!==""?c:void 0,u!==""?[{title:u}]:void 0);return this.showTrack(p),!0}const n=this.input("observer").value.trim(),r=this.input("date").value.trim();let o;try{if(s==="blank"){const c=(n||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";o={version:4,id:`${r?`${r}-`:""}${c}`,...n?{observer:{title:n}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const c=await this.readFile();if(se.isCase(c))return this.showError(this.messages.isACase),!1;o=c,n&&!o.observer?.title&&(o={...o,observer:{...o.observer,title:n}})}}catch{return this.showError(this.messages.loadFailed),!1}const 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 Qe.recording(new URL(e.url,location.href).href);const t=e.file,i=await new Promise((s,n)=>{const r=new FileReader;r.onload=()=>s(r.result),r.onerror=()=>n(r.error),r.readAsText(t)});return JSON.parse(i)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(o=>o.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const s=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,s&&this.showTrack(s))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const o of t.tracks)await this.loadTrack(o)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:s,strToU8:n}=await D(async()=>{const{zipSync:o,strToU8:a}=await import("./browser-CltifEM0.js");return{zipSync:o,strToU8:a}},[],import.meta.url),r={};for(const o of i)r[o.path]=n(o.content);return this.download(new Blob([s(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}}function co(){Us(),customElements.get(vi)||customElements.define(vi,Le)}const So=Object.freeze(Object.defineProperty({__proto__:null,CASE_EDITOR_ELEMENT_NAME:vi,CaseEditorElement:Le,register:co},Symbol.toStringTag,{value:"Module"}));export{So as C,De as I,fs as M};