@rr0/ufoathome 0.19.4 → 0.19.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist-embed/{UfoRecorderMessages_fr-BbT_cujZ.js → UfoRecorderMessages_fr-DU4ld1Gl.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={oval:"Ovale",polygon:"Polygone",addVertex:"Ajouter un sommet",deleteVertex:"Supprimer le sommet",notAPolygon:"Sélectionnez une seule forme polygonale",tooFewVertices:"Une forme a besoin d'au moins 3 points",color:"Couleur",transparency:"Transparence",halo:"Halo",shape:"Forme",shapeTitle:"Nom",objectSize:"Taille réelle",objectDistance:"Distance",apparentSize:"soit {deg}° — {moons}× la Lune",utcOffset:"Fuseau horaire",utcOffsetPlaceholder:"d'après la longitude",objectSizePlaceholder:"largeur rapportée",objectDistancePlaceholder:"distance rapportée",addShape:"Ajouter une forme",deleteShape:"Supprimer la forme",play:"Lecture",pause:"Pause",noDuration:"Aucune durée d'observation",autoReplay:"Lecture automatique",group:"Grouper",ungroup:"Dégrouper",bringToFront:"Placer devant",sendToBack:"Placer derrière",contextMenuDelete:"Supprimer",confirmDeleteShape:"Supprimer {name} ? Cette action est irréversible.",confirmDeleteShapes:"Supprimer {count} formes ? Cette action est irréversible.",onlyOneShape:"Il n'y a qu'une seule forme",alreadyAtFront:"Cette forme est déjà la plus en avant",alreadyAtBack:"Cette forme est déjà la plus en arrière",needTwoShapesToGroup:"Sélectionnez au moins deux formes pour les grouper",notGrouped:"Cette forme ne fait pas partie d'un groupe",multipleShapesSelected:"Plusieurs formes sélectionnées — sélectionnez-en une seule pour modifier ceci",cloudBase:"Base des nuages",elevation:"Altitude",samplingRate:"Échantillonnage",duration:"Durée",durationPlaceholder:"durée de l'observation",durationImprecise:"Ces dates ne permettent pas de déterminer précisément une durée — saisissez-la manuellement.",export:"Exporter le JSON",importFile:"Charger un fichier JSON",importUrl:"Ou charger depuis une URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Charger",importError:"Impossible de charger cet enregistrement — vérifiez le fichier ou l'URL et réessayez.",record:"Enregistrer",stop:"Arrêter",according:"selon",sourceElevation:"Relief",sourceImagery:"Imagerie",placeName:"Lieu",placeNamePlaceholder:"Valensole, France",searchPlace:"Localiser",placeMatch:"Correspondances",placeSearching:"Recherche du lieu…",placeMatchFound:"lieu trouvé",placeMatchesFound:"lieux trouvés",placeNotFound:"Aucun lieu de ce nom",placeSearchFailed:"Recherche de lieu momentanément indisponible",utcOffsetImplausible:"Ce fuseau ne correspond pas à la longitude saisie, dont l'heure solaire est UTC{solar} — la scène et le relevé météo obéissent pourtant à ce qui est déclaré ici. Videz le champ pour le déduire de la longitude.",timeZoneManual:"décalage saisi",altitudeAboveSeaLevel:"Altitude du témoin au-dessus du niveau de la mer — le sol du lieu saisi en fixe le minimum : un témoin dans les Alpes n'est pas à 0 m.",groundAt:"sol à {m} m",latitude:"Latitude",longitude:"Longitude",heading:"Orientation",headingPlaceholder:"inconnu",pitch:"Inclinaison",observationTime:"Début de l'observation",observationEndTime:"Fin de l'observation",edtfInvalid:"Date/heure EDTF invalide (ex. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"AAAA-MM-JJThh:mm[?~%] ou hh:mm",observationTimeHint:"EDTF — ex. 1965-07-01T05:00, 2025-06? (incertain), 2025~ (approximatif), ou juste 05:00 si la date est inconnue",observationEndTimeHint:"EDTF — ex. 1965-07-01T05:10, 2025-06? (incertain), 2025~ (approximatif), ou juste 05:10 si la date est inconnue",presetsGroupLabel:"Forme de l'ovni",witnessId:"ID témoin",witnessDirName:"Répertoire du témoin",witnessTitle:"Titre du témoin",witnessLastName:"Nom de famille du témoin",witnessFirstNames:"Prénoms du témoin",caseId:"ID de l'affaire",description:"Description",tags:"Mots-clés",tagsPlaceholder:"séparés par des virgules",weather:"Météo",shapeGroup:"Forme",soundGroup:"Son",temporalGroup:"Date et heure",locationGroup:"Lieu",observationGroup:"Observation",witnessGroup:"Témoin",circumstancesGroup:"Circonstances",weatherInferred:"D'après les relevés",weatherInferredTitle:"La météo n'est pas un témoignage : c'est un fait mesurable, relevé pour la date, l'heure et le lieu de l'observation. Décochez pour saisir les conditions rapportées par le témoin, qui priment alors sur le relevé.",
|
|
1
|
+
const e={oval:"Ovale",polygon:"Polygone",addVertex:"Ajouter un sommet",deleteVertex:"Supprimer le sommet",notAPolygon:"Sélectionnez une seule forme polygonale",tooFewVertices:"Une forme a besoin d'au moins 3 points",color:"Couleur",transparency:"Transparence",halo:"Halo",shape:"Forme",shapeTitle:"Nom",objectSize:"Taille réelle",objectDistance:"Distance",apparentSize:"soit {deg}° — {moons}× la Lune",utcOffset:"Fuseau horaire",utcOffsetPlaceholder:"d'après la longitude",objectSizePlaceholder:"largeur rapportée",objectDistancePlaceholder:"distance rapportée",addShape:"Ajouter une forme",deleteShape:"Supprimer la forme",play:"Lecture",pause:"Pause",noDuration:"Aucune durée d'observation",autoReplay:"Lecture automatique",group:"Grouper",ungroup:"Dégrouper",bringToFront:"Placer devant",sendToBack:"Placer derrière",contextMenuDelete:"Supprimer",confirmDeleteShape:"Supprimer {name} ? Cette action est irréversible.",confirmDeleteShapes:"Supprimer {count} formes ? Cette action est irréversible.",onlyOneShape:"Il n'y a qu'une seule forme",alreadyAtFront:"Cette forme est déjà la plus en avant",alreadyAtBack:"Cette forme est déjà la plus en arrière",needTwoShapesToGroup:"Sélectionnez au moins deux formes pour les grouper",notGrouped:"Cette forme ne fait pas partie d'un groupe",multipleShapesSelected:"Plusieurs formes sélectionnées — sélectionnez-en une seule pour modifier ceci",cloudBase:"Base des nuages",elevation:"Altitude",samplingRate:"Échantillonnage",duration:"Durée",durationPlaceholder:"durée de l'observation",durationImprecise:"Ces dates ne permettent pas de déterminer précisément une durée — saisissez-la manuellement.",export:"Exporter le JSON",importFile:"Charger un fichier JSON",importUrl:"Ou charger depuis une URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Charger",importError:"Impossible de charger cet enregistrement — vérifiez le fichier ou l'URL et réessayez.",record:"Enregistrer",stop:"Arrêter",according:"selon",sourceElevation:"Relief",sourceImagery:"Imagerie",placeName:"Lieu",placeNamePlaceholder:"Valensole, France",searchPlace:"Localiser",placeMatch:"Correspondances",placeSearching:"Recherche du lieu…",placeMatchFound:"lieu trouvé",placeMatchesFound:"lieux trouvés",placeNotFound:"Aucun lieu de ce nom",placeSearchFailed:"Recherche de lieu momentanément indisponible",utcOffsetImplausible:"Ce fuseau ne correspond pas à la longitude saisie, dont l'heure solaire est UTC{solar} — la scène et le relevé météo obéissent pourtant à ce qui est déclaré ici. Videz le champ pour le déduire de la longitude.",timeZoneManual:"décalage saisi",altitudeAboveSeaLevel:"Altitude du témoin au-dessus du niveau de la mer — le sol du lieu saisi en fixe le minimum : un témoin dans les Alpes n'est pas à 0 m.",groundAt:"sol à {m} m",latitude:"Latitude",longitude:"Longitude",heading:"Orientation",headingPlaceholder:"inconnu",pitch:"Inclinaison",observationTime:"Début de l'observation",observationEndTime:"Fin de l'observation",edtfInvalid:"Date/heure EDTF invalide (ex. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"AAAA-MM-JJThh:mm[?~%] ou hh:mm",observationTimeHint:"EDTF — ex. 1965-07-01T05:00, 2025-06? (incertain), 2025~ (approximatif), ou juste 05:00 si la date est inconnue",observationEndTimeHint:"EDTF — ex. 1965-07-01T05:10, 2025-06? (incertain), 2025~ (approximatif), ou juste 05:10 si la date est inconnue",presetsGroupLabel:"Forme de l'ovni",witnessId:"ID témoin",witnessDirName:"Répertoire du témoin",witnessTitle:"Titre du témoin",witnessLastName:"Nom de famille du témoin",witnessFirstNames:"Prénoms du témoin",caseId:"ID de l'affaire",description:"Description",tags:"Mots-clés",tagsPlaceholder:"séparés par des virgules",weather:"Météo",shapeGroup:"Forme",soundGroup:"Son",temporalGroup:"Date et heure",locationGroup:"Lieu",observationGroup:"Observation",witnessGroup:"Témoin",circumstancesGroup:"Circonstances",weatherInferred:"D'après les relevés",weatherInferredTitle:"La météo n'est pas un témoignage : c'est un fait mesurable, relevé pour la date, l'heure et le lieu de l'observation. Décochez pour saisir les conditions rapportées par le témoin, qui priment alors sur le relevé.",weatherLookingUp:"Recherche du relevé…",weatherNeedsDateAndPlace:"Date complète et lieu requis pour retrouver le relevé",weatherNoRecord:"Aucun relevé pour cette date et ce lieu",weatherLookupFailed:"Relevés météo momentanément inaccessibles",cloudCover:"Couverture nuageuse",cloudDarkness:"Obscurité des nuages",precipitationType:"Précipitations",precipitationNone:"Aucune",precipitationRain:"Pluie",precipitationSnow:"Neige",precipitationHail:"Grêle",precipitationIntensity:"Intensité",windDirection:"Direction du vent",windSpeed:"Force du vent",storm:"Orage",soundKind:"Son",soundNone:"Aucun (silencieux)",soundHum:"Bourdonnement",soundWhistle:"Sifflement",soundRumble:"Grondement",soundCrackle:"Crépitement",soundVolume:"Intensité sonore",soundPitch:"Hauteur",soundSrc:"Enregistrement",soundSrcPlaceholder:"URL d'un enregistrement réel",lensFlareBrightness:"Intensité lumineuse",cameraDevice:"Appareil photo/vidéo",decor:"Décor",decorBuilding:"Bâtiment",decorTree:"Arbre",decorStreetlight:"Lampadaire",decorVehicle:"Véhicule",decorWitness:"Autre témoin",addDecor:"Ajouter",deleteDecor:"Supprimer l'élément de décor",decorEast:"Distance à l'est",decorNorth:"Distance au nord",decorHeading:"Orientation",decorLit:"Allumé",decorTitle:"Nom",decorSightingUrl:"URL de l'enregistrement du témoin",viewTestimony:"Voir le témoignage",noWitnessRecording:"Aucune URL d'enregistrement définie pour ce témoin",masks:"Masque",addWitness:"Ajouter un témoin",decorFloors:"Étages",decorOccupiedFloor:"Étage occupé",decorWitnessSide:"Emplacement du témoin",decorWitnessSideNone:"Non présent",decorWindows:"Fenêtres",decorSideFront:"Avant",decorSideBehind:"Arrière",decorSideLeft:"Gauche",decorSideRight:"Droite",decorSideFrontLeft:"Avant-gauche",decorSideFrontRight:"Avant-droit",decorSideBehindLeft:"Arrière-gauche",decorSideBehindRight:"Arrière-droit"};export{e as ufoRecorderMessages_fr};
|
|
@@ -865,7 +865,7 @@ input[type=range] {
|
|
|
865
865
|
pointer-events: none;
|
|
866
866
|
white-space: nowrap;
|
|
867
867
|
}
|
|
868
|
-
`;class ps{static MOON_ANGULAR_WIDTH_DEG=.5237;static angularWidthDeg(e){return 2*Math.atan(e.sizeM/(2*e.distanceM))*180/Math.PI}static widthPx(e,t,n){return t*e.sizeM/(2*e.distanceM*Math.tan(n*Math.PI/360))}static pxToDeg(e,t,n){return 2*Math.atan(e*Math.tan(n*Math.PI/360)/t)*180/Math.PI}static inMoons(e){return e/ps.MOON_ANGULAR_WIDTH_DEG}static lerp(e,t,n){if(!(!e||!t))return{sizeM:e.sizeM+(t.sizeM-e.sizeM)*n,distanceM:e.distanceM+(t.distanceM-e.distanceM)*n}}}function rf(i,e="#39ff14"){return{kind:"oval",bounds:i,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function af(i,e,t="#39ff14"){return{kind:"polygon",bounds:i,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function of(i,e="#39ff14"){const{width:t,height:n}=i;return af(i,[{x:0,y:0},{x:t,y:0},{x:t,y:n},{x:0,y:n}],e)}const lf={oval:rf,polygon:of};function eh(i,e){return{...lf[e.presetId](i,e.color),transparency:e.transparency,haloScale:e.haloScale}}function cf(i,e,t){const{bounds:n}=i;return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function mu(i,e,t){const n=i.bounds.width,s=i.bounds.height;return{...i,bounds:{x:e-n/2,y:t-s/2,width:n,height:s}}}function jt(i,e,t){return i+(e-i)*t}function th(i){const e=/^#([0-9a-f]{6})$/i.exec(i);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function hf(i){return`#${i.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function df(i,e,t){const n=th(i),s=th(e);return!n||!s?t<1?i:e:hf([jt(n[0],s[0],t),jt(n[1],s[1],t),jt(n[2],s[2],t)])}function uf(i,e,t){const n={x:jt(i.bounds.x,e.bounds.x,t),y:jt(i.bounds.y,e.bounds.y,t),width:jt(i.bounds.width,e.bounds.width,t),height:jt(i.bounds.height,e.bounds.height,t)},s=jt(i.angle,e.angle,t),r=jt(i.transparency,e.transparency,t),a=jt(i.haloScale,e.haloScale,t),o=df(i.color,e.color,t),l=ps.lerp(i.physical,e.physical,t);return i.kind==="polygon"&&e.kind==="polygon"&&i.points.length===e.points.length?{...i,bounds:n,angle:s,transparency:r,haloScale:a,color:o,physical:l,behindCloud:t<1?i.behindCloud:e.behindCloud,points:i.points.map((c,h)=>({x:jt(c.x,e.points[h].x,t),y:jt(c.y,e.points[h].y,t)}))}:{...t<1?i:e,bounds:n,angle:s,transparency:r,haloScale:a,color:o,physical:l}}class Pa{keyframes=[];order=[];groups=[];addKeyframe(e,t){const n=this.findInsertIndex(e);if(this.keyframes[n]?.t===e){const s=new Set(t.map(r=>r.sourceId));this.keyframes[n]={t:e,shapes:[...this.keyframes[n].shapes.filter(r=>!s.has(r.sourceId)),...t]}}else this.keyframes.splice(n,0,{t:e,shapes:[...t]});for(const s of t)this.order.includes(s.sourceId)||this.order.push(s.sourceId)}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}getKeyframeAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t];return n?.t===e?n:void 0}getShapeAt(e,t){return this.getKeyframeAt(e)?.shapes.find(n=>n.sourceId===t)?.shape}getLatestShapeAt(e,t){let n=this.findInsertIndex(e);for(this.keyframes[n]?.t!==e&&(n-=1);n>=0;n--){const s=this.keyframes[n].shapes.find(r=>r.sourceId===t);if(s)return s.shape}}getInterpolatedShapeAt(e,t){const n=this.findShapeAtOrBefore(e,t);if(n?.t===e)return n.shape;const s=this.findShapeAtOrAfter(e,t);return n?s?uf(n.shape,s.shape,(e-n.t)/(s.t-n.t)):n.shape:s?.shape}findShapeAtOrBefore(e,t){let n=this.findInsertIndex(e);for(this.keyframes[n]?.t!==e&&(n-=1);n>=0;n--){const s=this.keyframes[n].shapes.find(r=>r.sourceId===t);if(s)return{t:this.keyframes[n].t,shape:s.shape}}}findShapeAtOrAfter(e,t){for(let n=this.findInsertIndex(e);n<this.keyframes.length;n++){const s=this.keyframes[n].shapes.find(r=>r.sourceId===t);if(s)return{t:this.keyframes[n].t,shape:s.shape}}}hitTest(e,t,n,s){const r=this.sourceIds;for(let a=r.length-1;a>=0;a--){if(s?.has(r[a]))continue;const o=this.getInterpolatedShapeAt(e,r[a]);if(o&&cf(o,t,n))return{sourceId:r[a],shape:o}}}removeSource(e){for(let t=this.keyframes.length-1;t>=0;t--){const n=this.keyframes[t].shapes.filter(s=>s.sourceId!==e);n.length===0?this.keyframes.splice(t,1):n.length!==this.keyframes[t].shapes.length&&(this.keyframes[t]={t:this.keyframes[t].t,shapes:n})}this.order=this.order.filter(t=>t!==e),this.removeFromGroup(e)}group(e){if(!(e.length<2)){for(const t of e)this.removeFromGroup(t);this.groups.push([...e])}}ungroup(e){const t=this.groups.findIndex(n=>n.includes(e));t!==-1&&this.groups.splice(t,1)}groupMembers(e){return this.groups.find(t=>t.includes(e))}removeFromGroup(e){const t=this.groups.findIndex(s=>s.includes(e));if(t===-1)return;const n=this.groups[t].filter(s=>s!==e);n.length<2?this.groups.splice(t,1):this.groups[t]=n}bringToFront(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.push(e))}sendToBack(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.unshift(e))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e){const t=new Pa;for(const n of e.keyframes)t.addKeyframe(n.t,n.shapes);if(e.order){const n=t.order.filter(s=>!e.order.includes(s));t.order=[...e.order,...n]}return e.groups&&(t.groups=e.groups.map(n=>n.filter(s=>t.order.includes(s))).filter(n=>n.length>=2)),t}}function ff(i,e,t){return Math.max(e,Math.min(t,i))}function pf(i,e,t){const n=((e-i)%360+540)%360-180;return((i+n*t)%360+360)%360}function Is(i,e,t){return i+(e-i)*t}function mf(i,e,t){return{lat:i.lat===void 0||e.lat===void 0?void 0:Is(i.lat,e.lat,t),lng:i.lng===void 0||e.lng===void 0?void 0:Is(i.lng,e.lng,t),elevationM:Is(i.elevationM,e.elevationM,t),headingDeg:i.headingDeg===void 0||e.headingDeg===void 0?void 0:pf(i.headingDeg,e.headingDeg,t),pitchDeg:Is(i.pitchDeg,e.pitchDeg,t),fovDeg:Is(i.fovDeg,e.fovDeg,t)}}class nr{keyframes=[];addKeyframe(e,t){const n=this.findInsertIndex(e);this.keyframes[n]?.t===e?this.keyframes[n]={t:e,pose:t}:this.keyframes.splice(n,0,{t:e,pose:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}getLatestPoseAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].pose:void 0}getInterpolatedPoseAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(n?.t===e)return n.pose;const s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return n?s?mf(n.pose,s.pose,ff((e-n.t)/(s.t-n.t),0,1)):n.pose:s?.pose}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new nr;for(const n of e.keyframes)t.addKeyframe(n.t,n.pose);return t}}function Rs(i,e,t){return i+(e-i)*t}function gf(i,e,t){const n=((e-i)%360+540)%360-180;return((i+n*t)%360+360)%360}function vf(i,e,t){return Math.max(e,Math.min(t,i))}function _f(i,e,t){return{cloudCover:Rs(i.cloudCover,e.cloudCover,t),cloudDarkness:Rs(i.cloudDarkness,e.cloudDarkness,t),cloudBaseM:i.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:Rs(i.cloudBaseM,e.cloudBaseM,t),precipitationType:t<1?i.precipitationType:e.precipitationType,precipitationIntensity:Rs(i.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:gf(i.windDirectionDeg,e.windDirectionDeg,t),windSpeed:Rs(i.windSpeed,e.windSpeed,t),storm:t<1?i.storm:e.storm}}class ir{keyframes=[];addKeyframe(e,t){const n=this.findInsertIndex(e);this.keyframes[n]?.t===e?this.keyframes[n]={t:e,weather:t}:this.keyframes.splice(n,0,{t:e,weather:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}getLatestWeatherAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].weather:void 0}getInterpolatedWeatherAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(n?.t===e)return n.weather;const s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return n?s?_f(n.weather,s.weather,vf((e-n.t)/(s.t-n.t),0,1)):n.weather:s?.weather}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new ir;for(const n of e.keyframes)t.addKeyframe(n.t,n.weather);return t}}class sr{keyframes=[];addKeyframe(e,t){const n=this.findInsertIndex(e);this.keyframes[n]?.t===e?this.keyframes[n]={t:e,sound:t}:this.keyframes.splice(n,0,{t:e,sound:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}getLatestSoundAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].sound:void 0}getInterpolatedSoundAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(n?.t===e)return n.sound;const s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!n)return s?.sound;if(!s)return n.sound;const r=(e-n.t)/(s.t-n.t);return this.lerp(n.sound,s.sound,Math.max(0,Math.min(1,r)))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new sr;for(const n of e.keyframes)t.addKeyframe(n.t,n.sound);return t}lerp(e,t,n){return{kind:n<1?e.kind:t.kind,volume:e.volume+(t.volume-e.volume)*n,pitchHz:e.pitchHz+(t.pitchHz-e.pitchHz)*n,src:n<1?e.src:t.src}}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}}const $o=1e3,gu={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1},xf=["none","hum","whistle","rumble","crackle"],Sf=100,yf={kind:"none",volume:0,pitchHz:Sf},bf=/^(?:(?<year>\d{4}|\d{3}X|\d{2}XX)(-(?<month>0[1-9]|1[0-2]))?(-(?<day>0[1-9]|[12]\d|3[01]))?(?:[T ](?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?)?|(?<timeOnlyHour>[01]?\d|2[0-3]):(?<timeOnlyMinute>[0-5]\d)(?::(?<timeOnlySecond>[0-5]\d))?)[?~%]?$/;function nh(i){const e=bf.exec(i.trim());if(!e?.groups)return;const{year:t,month:n,day:s,hour:r,minute:a,second:o,timeOnlyHour:l,timeOnlyMinute:c,timeOnlySecond:h}=e.groups,u=r??l,d=a??c,f=o??h;return{year:t&&!t.includes("X")?Number(t):void 0,month:n?Number(n):void 0,day:s?Number(s):void 0,hour:u?Number(u):void 0,minute:d?Number(d):void 0,second:f?Number(f):void 0,raw:i.trim()}}function ih(i){if(i.raw!==void 0)return i.raw;if(i.year===void 0){if(i.hour===void 0)return"";let t=`${String(i.hour).padStart(2,"0")}:${String(i.minute??0).padStart(2,"0")}`;return i.second!==void 0&&(t+=`:${String(i.second).padStart(2,"0")}`),t}let e=String(i.year).padStart(4,"0");return i.month===void 0||(e+=`-${String(i.month).padStart(2,"0")}`,i.day===void 0)||(e+=`-${String(i.day).padStart(2,"0")}`,i.hour===void 0)||(e+=`T${String(i.hour).padStart(2,"0")}:${String(i.minute??0).padStart(2,"0")}`,i.second!==void 0&&(e+=`:${String(i.second).padStart(2,"0")}`)),e}function Zo(i){if(i.year!==void 0)return Date.UTC(i.year,(i.month??1)-1,i.day??1,i.hour??0,i.minute??0,i.second??0)}function sh(i){return(((i.day??0)*24+(i.hour??0))*60+(i.minute??0))*6e4+(i.second??0)*1e3}const Mf=["year","month","day","hour","minute"],Ef=["day","hour","minute"];function rh(i,e){return e.filter(t=>i[t]!==void 0).join(",")}function rr(i){if(i.durationSeconds!==void 0)return i.durationSeconds*1e3;if(!i.time||!i.endTime)return;const e=i.time.year!==void 0&&i.endTime.year!==void 0,t=e?Mf:Ef,n=rh(i.time,t);if(!(n===""||n!==rh(i.endTime,t)))return e?Zo(i.endTime)-Zo(i.time):sh(i.endTime)-sh(i.time)}function wf(i){if(i.durationSeconds===void 0&&!(!i.time||!i.endTime))return rr(i)===void 0?"imprecise":void 0}class La{constructor(e,t,n,s,r,a,o,l,c=[],h){this.event=e,this.timeline=t,this.witnessTrack=n,this.weatherTrack=s,this.soundTrack=r,this.witness=a,this.caseId=o,this.weather=l,this.decor=c,this.weatherSource=h}static create(e,t,n){return new La({eventType:"sighting",time:e,place:t},new Pa,new nr,new ir,new sr,n)}}const Tf=0,Af=0,If=60;function Ss(i,e){const t=i.witnessTrack.getInterpolatedPoseAt(e);if(t)return t;const n=i.event.place?.[0];if(n)return{lat:n.lat,lng:n.lng,elevationM:Tf,headingDeg:void 0,pitchDeg:Af,fovDeg:If}}function Jo(i,e){return i.weatherTrack.getInterpolatedWeatherAt(e)??i.weather??gu}function vu(i,e){return i.soundTrack.getInterpolatedSoundAt(e)??yf}class Rf{constructor(e,t){this.timeline=e,this.onFrame=t}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT);return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const n of this.timeline.sourceIds){const s=this.timeline.getInterpolatedShapeAt(e,n);s&&t.set(n,s)}this.onFrame(e,t)}}const _u=["nw","n","ne","e","se","s","sw","w"],Cf=24,ai=8,xu=3,Df=8;function qs(i,e,t){const n=i.x-e.x,s=i.y-e.y,r=Math.cos(t),a=Math.sin(t);return{x:e.x+n*r-s*a,y:e.y+n*a+s*r}}function yi(i){return{x:i.x+i.width/2,y:i.y+i.height/2}}const Pf={nw:{left:!0,top:!0},n:{top:!0},ne:{right:!0,top:!0},e:{right:!0},se:{right:!0,bottom:!0},s:{bottom:!0},sw:{left:!0,bottom:!0},w:{left:!0}};class $e{static handlePointsFor(e){const{x:t,y:n,width:s,height:r}=e.bounds,a={nw:{x:t,y:n},n:{x:t+s/2,y:n},ne:{x:t+s,y:n},e:{x:t+s,y:n+r/2},se:{x:t+s,y:n+r},s:{x:t+s/2,y:n+r},sw:{x:t,y:n+r},w:{x:t,y:n+r/2},rotate:{x:t+s/2,y:n-Cf}},o=yi(e.bounds),l={};for(const c of Object.keys(a))l[c]=qs(a[c],o,e.angle);return l}static hitTestHandle(e,t,n=8,s=[..._u,"rotate"]){const r=$e.handlePointsFor(e);for(const a of s)if(Math.hypot(t.x-r[a].x,t.y-r[a].y)<=n)return a}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(e,t){const s=(($e.HANDLE_DIRECTION_DEG[e]+t*180/Math.PI)%180+180)%180/45,r=["ew","nwse","ns","nesw"];return r[Math.round(s)%r.length]}static resizeBounds(e,t,n,s){const r=yi(e),a=qs(s,r,-t),{x:o,y:l,width:c,height:h}=e,u=Pf[n];let d=o,f=l,g=o+c,x=l+h;return u.left&&(d=Math.min(a.x,g-ai)),u.right&&(g=Math.max(a.x,d+ai)),u.top&&(f=Math.min(a.y,x-ai)),u.bottom&&(x=Math.max(a.y,f+ai)),{x:d,y:f,width:g-d,height:x-f}}static resizeShape(e,t,n){if(t==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:s,height:r}=e.bounds,a=$e.resizeBounds(e.bounds,e.angle,t,n);if(e.kind==="oval")return{...e,bounds:a};const o=s===0?1:a.width/s,l=r===0?1:a.height/r;return{...e,bounds:a,points:e.points.map(c=>({x:c.x*o,y:c.y*l}))}}static rotateShape(e,t){const n=yi(e.bounds),s=Math.atan2(t.y-n.y,t.x-n.x)+Math.PI/2;return{...e,angle:s}}static groupBoundsFor(e){const t=Math.min(...e.map(a=>a.x)),n=Math.min(...e.map(a=>a.y)),s=Math.max(...e.map(a=>a.x+a.width)),r=Math.max(...e.map(a=>a.y+a.height));return{x:t,y:n,width:s-t,height:r-n}}static vertexPointsFor(e){const t=yi(e.bounds);return e.points.map(n=>qs({x:e.bounds.x+n.x,y:e.bounds.y+n.y},t,e.angle))}static hitTestVertex(e,t,n=Df){const s=$e.vertexPointsFor(e);let r,a=n;return s.forEach((o,l)=>{const c=Math.hypot(t.x-o.x,t.y-o.y);c<=a&&(a=c,r=l)}),r}static toLocalPoint(e,t){const n=yi(e.bounds),s=qs(t,n,-e.angle);return{x:s.x-e.bounds.x,y:s.y-e.bounds.y}}static moveVertex(e,t,n){const s=e.points.map((u,d)=>d===t?$e.toLocalPoint(e,n):u),r=Math.min(...s.map(u=>u.x)),a=Math.min(...s.map(u=>u.y)),o=Math.max(...s.map(u=>u.x)),l=Math.max(...s.map(u=>u.y)),c={x:e.bounds.x+r,y:e.bounds.y+a,width:o-r,height:l-a},h=s.map(u=>({x:u.x-r,y:u.y-a}));return{...e,bounds:c,points:h}}static insertVertexNear(e,t){const n=$e.toLocalPoint(e,t),{points:s}=e;let r=s.length-1,a=1/0;for(let l=0;l<s.length;l++){const c=s[l],h=s[(l+1)%s.length],u=$e.distanceToSegment(n,c,h);u<a&&(a=u,r=l)}const o=[...s.slice(0,r+1),n,...s.slice(r+1)];return{...e,points:o}}static distanceToSegment(e,t,n){const s=n.x-t.x,r=n.y-t.y,a=s*s+r*r,o=a===0?0:Math.max(0,Math.min(1,((e.x-t.x)*s+(e.y-t.y)*r)/a)),l=t.x+o*s,c=t.y+o*r;return Math.hypot(e.x-l,e.y-c)}static deleteVertex(e,t){return e.points.length<=xu?e:{...e,points:e.points.filter((n,s)=>s!==t)}}}class Xa{constructor(e){this.members=e}bounds(){return $e.groupBoundsFor(this.members.map(e=>e.shape.bounds))}scaleTo(e){const t=this.bounds(),n=t.width===0?1:e.width/t.width,s=t.height===0?1:e.height/t.height;return this.members.map(({sourceId:r,shape:a})=>{const o=Math.max(a.bounds.width*n,ai),l=Math.max(a.bounds.height*s,ai),c=e.x+(a.bounds.x-t.x)*n,h=e.y+(a.bounds.y-t.y)*s,u={x:c,y:h,width:o,height:l};return a.kind==="oval"?{sourceId:r,shape:{...a,bounds:u}}:{sourceId:r,shape:{...a,bounds:u,points:a.points.map(d=>({x:d.x*n,y:d.y*s}))}}})}resize(e,t){return this.scaleTo($e.resizeBounds(this.bounds(),0,e,t))}rotate(e,t){const n=yi(this.bounds()),s=a=>Math.atan2(a.y-n.y,a.x-n.x),r=s(e)-s(t);return this.members.map(({sourceId:a,shape:o})=>{const l=yi(o.bounds),c=qs(l,n,r),h={x:c.x-o.bounds.width/2,y:c.y-o.bounds.height/2,width:o.bounds.width,height:o.bounds.height};return{sourceId:a,shape:{...o,bounds:h,angle:o.angle+r}}})}}const Qo=6,gr=Qo/2,Lf=20,ah=4;class Nf{constructor(e){this.ctx=e}clear(e,t){this.ctx.clearRect(0,0,e,t)}paintShape(e){this.ctx.save(),this.ctx.globalAlpha=1-e.transparency,e.haloScale>0&&this.paintHalo(e),this.paintBase(e),this.ctx.restore(),e.selected&&this.paintSelectionHandles(e)}paintBase(e){if(this.ctx.fillStyle=e.color,this.ctx.beginPath(),e.kind==="oval"){const{x:t,y:n,width:s,height:r}=e.bounds,a=s/2,o=r/2;this.ctx.ellipse(t+a,n+o,a,o,e.angle,0,2*Math.PI)}else{const{x:t,y:n,width:s,height:r}=e.bounds;this.ctx.save(),this.ctx.translate(t+s/2,n+r/2),this.ctx.rotate(e.angle),this.ctx.translate(-s/2,-r/2),e.points.forEach((a,o)=>{o===0?this.ctx.moveTo(a.x,a.y):this.ctx.lineTo(a.x,a.y)}),this.ctx.closePath(),this.ctx.restore()}this.ctx.fill()}paintHalo(e){this.ctx.save(),this.ctx.shadowColor=e.color,this.ctx.shadowBlur=Lf*e.haloScale,this.paintBase(e),this.ctx.restore()}paintSelectionHandles(e){this.paintHandleFrame($e.handlePointsFor(e),{includeRotate:!0}),e.kind==="polygon"&&this.paintVertexHandles(e)}paintVertexHandles(e){this.ctx.fillStyle="#39f";for(const t of $e.vertexPointsFor(e))this.ctx.beginPath(),this.ctx.ellipse(t.x,t.y,ah,ah,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(e){this.paintOutline($e.handlePointsFor(e))}paintGroupHandles(e){this.paintHandleFrame($e.handlePointsFor({bounds:e,angle:0}),{includeRotate:!0})}paintOutline(e){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(e.nw.x,e.nw.y),this.ctx.lineTo(e.ne.x,e.ne.y),this.ctx.lineTo(e.se.x,e.se.y),this.ctx.lineTo(e.sw.x,e.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(e,{includeRotate:t}){this.paintOutline(e),this.ctx.fillStyle="lightgray";for(const n of _u){const s=e[n];this.ctx.fillRect(s.x-gr,s.y-gr,Qo,Qo)}t&&(this.ctx.beginPath(),this.ctx.moveTo(e.n.x,e.n.y),this.ctx.lineTo(e.rotate.x,e.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(e.rotate.x,e.rotate.y,gr+1,gr+1,0,0,2*Math.PI),this.ctx.fill())}}const oh=.05,lh=.08,ch=2,hh=3,Uf=14,Ff=.02;class Of{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}this.context.state==="suspended"&&this.context.resume()}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const n=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,n):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const n=this.context;if(!e||!n)return;const s=n.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,s,oh);for(const{param:r,ratio:a}of e.pitch)r.setTargetAtTime(Math.min(t.pitchHz*a,n.sampleRate/2-1),s,oh)}buildSynthesizedVoice(e,t){const n=this.context;if(n)switch(e.kind){case"hum":return this.buildHum(n,t);case"whistle":return this.buildWhistle(n,t);case"rumble":return this.buildRumble(n,t);case"crackle":return this.buildCrackle(n,t);default:return}}buildHum(e,t){const n=e.createOscillator();n.type="sawtooth";const s=e.createOscillator();s.type="sawtooth";const r=e.createBiquadFilter();r.type="lowpass",r.Q.value=1;const a=e.createGain();return a.gain.value=0,n.connect(r),s.connect(r),r.connect(a).connect(e.destination),n.start(),s.start(),{key:t,nodes:[r,a],sources:[n,s],volumeParam:a.gain,gainScale:.16,pitch:[{param:n.frequency,ratio:1},{param:s.frequency,ratio:1.006},{param:r.frequency,ratio:6}]}}buildWhistle(e,t){const n=e.createOscillator();n.type="sine";const s=e.createOscillator();s.type="sine",s.frequency.value=5;const r=e.createGain(),a=e.createGain();return a.gain.value=0,s.connect(r).connect(n.frequency),n.connect(a).connect(e.destination),n.start(),s.start(),{key:t,nodes:[r,a],sources:[n,s],volumeParam:a.gain,gainScale:.22,pitch:[{param:n.frequency,ratio:1},{param:r.gain,ratio:.012}]}}buildRumble(e,t){const n=e.createBufferSource();n.buffer=this.brownNoise(e),n.loop=!0;const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=.8;const r=e.createGain();return r.gain.value=0,n.connect(s).connect(r).connect(e.destination),n.start(),{key:t,nodes:[s,r],sources:[n],volumeParam:r.gain,gainScale:1.4,pitch:[{param:s.frequency,ratio:1}]}}buildCrackle(e,t){const n=e.createBufferSource();n.buffer=this.whiteNoise(e),n.loop=!0;const s=e.createBiquadFilter();s.type="bandpass",s.Q.value=1.2;const r=e.createGain();r.gain.value=0;const a=e.createBufferSource();a.buffer=this.crackleEnvelope(e),a.loop=!0;const o=e.createGain();return o.gain.value=0,a.connect(o).connect(r.gain),n.connect(s).connect(r).connect(e.destination),n.start(),a.start(),{key:t,nodes:[s,r,o],sources:[n,a],volumeParam:o.gain,gainScale:.9,pitch:[{param:s.frequency,ratio:4}]}}async buildRecordedVoice(e,t,n){const s=this.context;if(!s)return;let r;try{r=await this.getBuffer(e)}catch(l){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",l);return}if(n!==this.voiceToken||!this.context)return;const a=s.createBufferSource();a.buffer=r,a.loop=!0;const o=s.createGain();o.gain.value=0,a.connect(o).connect(s.destination),a.start(),this.voice={key:t,nodes:[o],sources:[a],volumeParam:o.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let n=this.buffers.get(e);return n||(n=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,n)),n}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*ch),e.sampleRate),n=t.getChannelData(0);for(let s=0;s<n.length;s++)n[s]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*ch),e.sampleRate),n=t.getChannelData(0);let s=0,r=0;for(let a=0;a<n.length;a++)s=(s+.02*(Math.random()*2-1))/1.02,n[a]=s,r=Math.max(r,Math.abs(s));if(r>0)for(let a=0;a<n.length;a++)n[a]/=r;return t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*hh),e.sampleRate),n=t.getChannelData(0),s=Math.max(1,Math.floor(Ff*e.sampleRate)),r=Math.round(hh*Uf);for(let a=0;a<r;a++){const o=Math.floor(Math.random()*n.length),l=.4+Math.random()*.6;for(let c=0;c<s&&o+c<n.length;c++)n[o+c]=Math.max(n[o+c],l*(1-c/s))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const n=t.currentTime;e.volumeParam.cancelScheduledValues(n),e.volumeParam.setTargetAtTime(0,n,lh/3);const s=n+lh;for(const r of e.sources){r.onended=()=>{r.disconnect();for(const a of e.nodes)a.disconnect()};try{r.stop(s)}catch{r.disconnect();for(const a of e.nodes)a.disconnect()}}}}function Bf(i){return{version:1,time:i.event.time,endTime:i.event.endTime,durationSeconds:i.event.durationSeconds,utcOffsetHours:i.event.utcOffsetHours,timeZone:i.event.timeZone,place:i.event.place,witness:i.witness,caseId:i.caseId,description:i.event.description,tags:i.event.tags,timeline:i.timeline.toJSON(),witnessTrack:i.witnessTrack.toJSON(),weatherTrack:i.weatherTrack.toJSON(),soundTrack:i.soundTrack.toJSON(),weather:i.weather,decor:i.decor,weatherSource:i.weatherSource}}function kf(i){return new La({eventType:"sighting",time:i.time,endTime:i.endTime,durationSeconds:i.durationSeconds,utcOffsetHours:i.utcOffsetHours,timeZone:i.timeZone,place:i.place,description:i.description,tags:i.tags},Pa.fromJSON(i.timeline),i.witnessTrack?nr.fromJSON(i.witnessTrack):new nr,i.weatherTrack?ir.fromJSON(i.weatherTrack):new ir,i.soundTrack?sr.fromJSON(i.soundTrack):new sr,i.witness,i.caseId,i.weather,i.decor??[],i.weatherSource)}function Na(i,e){for(const t of i){const n=t.toLowerCase().split("-")[0];if(e.includes(n))return n}return"en"}const zf="modulepreload",Gf=function(i,e){return new URL(i,e).href},dh={},va=function(e,t,n){let s=Promise.resolve();if(t&&t.length>0){let a=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");s=a(t.map(h=>{if(h=Gf(h,n),h in dh)return;dh[h]=!0;const u=h.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(!!n)for(let x=o.length-1;x>=0;x--){const m=o[x];if(m.href===h&&(!u||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${d}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":zf,u||(g.as="script"),g.crossOrigin="",g.href=h,c&&g.setAttribute("nonce",c),document.head.appendChild(g),u)return new Promise((x,m)=>{g.addEventListener("load",x),g.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function r(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return s.then(a=>{for(const o of a||[])o.status==="rejected"&&r(o.reason);return e().catch(r)})},Su=["en","fr"],Hf={en:()=>va(()=>Promise.resolve().then(()=>qf),void 0,import.meta.url).then(i=>i.ufoMessages_en),fr:()=>va(()=>import("./UfoMessages_fr-NZrwNFCQ.js"),[],import.meta.url).then(i=>i.ufoMessages_fr)};function Vf(i){return Hf[i]()}const Wf={en:()=>va(()=>Promise.resolve().then(()=>pb),void 0,import.meta.url).then(i=>i.ufoRecorderMessages_en),fr:()=>va(()=>import("./UfoRecorderMessages_fr-BbT_cujZ.js"),[],import.meta.url).then(i=>i.ufoRecorderMessages_fr)};function Xf(i){return Wf[i]()}const yu={play:"Play",pause:"Pause",noDuration:"No observation duration",autoReplay:"Auto-replay",currentPosition:"Current position",duration:"Duration",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen"},qf=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:yu},Symbol.toStringTag,{value:"Module"})),uh=new Set;class Yf extends HTMLElement{static get observedAttributes(){return["src"]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;playPauseButton;loopButton;fullscreenButton;seekInput;timeStartLabel;timeEndLabel;currentSighting=La.create();sightingAudio=new Of;soundPreview;player;loopEnabled=!0;highlightedSourceIds=new Set;occludedSourceIds=uh;enableClickToPlay=!0;fullscreenTarget;messages=yu;realDurationMs;realStartMs;handleFullscreenChange=()=>this.updateFullscreenButton();handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),n=t&&this.currentSighting.timeline.hitTest(this.currentTime,t.x,t.y,this.occludedSourceIds);if(!n?.shape.title){this.tooltip.hidden=!0;return}this.tooltip.textContent=n.shape.title,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-s.left+12}px`,this.tooltip.style.top=`${e.clientY-s.top+12}px`};handlePointerLeave=()=>{this.tooltip.hidden=!0};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${sf}</style>${nf}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Nf(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.loopButton=this.shadow.getElementById("loop"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.seekInput=this.shadow.getElementById("seek"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.loopButton.addEventListener("click",()=>this.toggleLoop()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.seekInput.addEventListener("input",()=>this.player.seek(Number(this.seekInput.value))),this.canvas.addEventListener("click",()=>{this.enableClickToPlay&&this.togglePlayPause()}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.refresh(),this.loadLocaleMessages()}connectedCallback(){const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sightingAudio.dispose()}attributeChangedCallback(e,t,n){e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n)}async loadFromSrc(e){const t=await fetch(e);this.sightingData=await t.json()}get sightingData(){return Bf(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=kf(e),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh()}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}setOccludedSourceIds(e){e.size===this.occludedSourceIds.size&&[...e].every(n=>this.occludedSourceIds.has(n))||(this.occludedSourceIds=e,this.refresh())}hasVisibleShapeAt(e,t){return this.currentSighting.timeline.hitTest(this.currentTime,e,t,this.occludedSourceIds)!==void 0}refresh(){this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.player.seek(this.player.time)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const n=this.playbackState!=="playing"?this.highlightedSourceIds:uh;for(const[s,r]of t){if(this.occludedSourceIds.has(s))continue;const a=n.has(s);a&&n.size===1?this.canvasRenderer.paintShape({...r,selected:!0}):(this.canvasRenderer.paintShape(r),a&&this.canvasRenderer.paintMemberOutline(r))}if(n.size>1){const s=$e.groupBoundsFor([...t].filter(([r])=>n.has(r)).map(([,r])=>r.bounds));this.canvasRenderer.paintGroupHandles(s)}this.seekInput.value=String(e),this.timeStartLabel.textContent=this.formatPosition(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(vu(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}createPlayer(){const e=new Rf(this.currentSighting.timeline,(t,n)=>this.onFrame(t,n));return e.loop=this.loopEnabled,e}togglePlayPause(){this.player.seekableDuration<=0||(this.player.playbackState==="playing"?(this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh()):(this.sightingAudio.resume(),this.player.play()),this.updatePlayPauseButton())}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.playPauseButton.textContent=e?"⏸":"▶";const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const n=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=n,this.playPauseButton.setAttribute("aria-label",n),this.toolbar.classList.toggle("auto-hide",e),this.fullscreenButton.classList.toggle("auto-hide",e)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.loopButton.setAttribute("aria-pressed",String(this.loopEnabled)),this.player.loop=this.loopEnabled}toggleFullscreen(){document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}updateFullscreenButton(){const e=document.fullscreenElement===this.fullscreenTarget;this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}async loadLocaleMessages(){const e=Na(navigator.languages,Su);e!=="en"&&this.applyMessages(await Vf(e))}applyMessages(e){this.messages=e,this.timeStartLabel.title=e.currentPosition,this.timeEndLabel.title=e.duration,this.loopButton.title=e.autoReplay,this.loopButton.setAttribute("aria-label",e.autoReplay),this.updatePlayPauseButton(),this.updateFullscreenButton()}updateTimeLabels(){const e=this.currentSighting.event,t=rr(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Zo(e.time):void 0;const n=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&n>0?n/this.realDurationMs:1,this.player.durationOverrideMs=n>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time)}formatPosition(e){if(this.realDurationMs===void 0)return vr(e);const t=this.currentSighting.timeline.duration,n=t>0&&e<=t?e/t*this.realDurationMs:e;return this.realStartMs!==void 0?ph(fh(this.realStartMs+n)):vr(n)}formatEndOfTimeline(){return this.realDurationMs===void 0?vr(this.currentSighting.timeline.duration):this.realStartMs!==void 0?ph(fh(this.realStartMs+this.realDurationMs)):vr(this.realDurationMs)}}function fh(i){const e=new Date(i);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function ph(i){if(i.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return i.second?`${e(i.hour)}:${e(i.minute??0)}:${e(i.second)}`:`${e(i.hour)}:${e(i.minute??0)}`}function vr(i){const e=Math.round(i/1e3),t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,"0")}`}const jo="rr0-ufo";function Ua(){customElements.get(jo)||customElements.define(jo,Yf)}const Kf=`
|
|
868
|
+
`;class ps{static MOON_ANGULAR_WIDTH_DEG=.5237;static angularWidthDeg(e){return 2*Math.atan(e.sizeM/(2*e.distanceM))*180/Math.PI}static widthPx(e,t,n){return t*e.sizeM/(2*e.distanceM*Math.tan(n*Math.PI/360))}static pxToDeg(e,t,n){return 2*Math.atan(e*Math.tan(n*Math.PI/360)/t)*180/Math.PI}static inMoons(e){return e/ps.MOON_ANGULAR_WIDTH_DEG}static lerp(e,t,n){if(!(!e||!t))return{sizeM:e.sizeM+(t.sizeM-e.sizeM)*n,distanceM:e.distanceM+(t.distanceM-e.distanceM)*n}}}function rf(i,e="#39ff14"){return{kind:"oval",bounds:i,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function af(i,e,t="#39ff14"){return{kind:"polygon",bounds:i,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function of(i,e="#39ff14"){const{width:t,height:n}=i;return af(i,[{x:0,y:0},{x:t,y:0},{x:t,y:n},{x:0,y:n}],e)}const lf={oval:rf,polygon:of};function eh(i,e){return{...lf[e.presetId](i,e.color),transparency:e.transparency,haloScale:e.haloScale}}function cf(i,e,t){const{bounds:n}=i;return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function mu(i,e,t){const n=i.bounds.width,s=i.bounds.height;return{...i,bounds:{x:e-n/2,y:t-s/2,width:n,height:s}}}function jt(i,e,t){return i+(e-i)*t}function th(i){const e=/^#([0-9a-f]{6})$/i.exec(i);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function hf(i){return`#${i.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function df(i,e,t){const n=th(i),s=th(e);return!n||!s?t<1?i:e:hf([jt(n[0],s[0],t),jt(n[1],s[1],t),jt(n[2],s[2],t)])}function uf(i,e,t){const n={x:jt(i.bounds.x,e.bounds.x,t),y:jt(i.bounds.y,e.bounds.y,t),width:jt(i.bounds.width,e.bounds.width,t),height:jt(i.bounds.height,e.bounds.height,t)},s=jt(i.angle,e.angle,t),r=jt(i.transparency,e.transparency,t),a=jt(i.haloScale,e.haloScale,t),o=df(i.color,e.color,t),l=ps.lerp(i.physical,e.physical,t);return i.kind==="polygon"&&e.kind==="polygon"&&i.points.length===e.points.length?{...i,bounds:n,angle:s,transparency:r,haloScale:a,color:o,physical:l,behindCloud:t<1?i.behindCloud:e.behindCloud,points:i.points.map((c,h)=>({x:jt(c.x,e.points[h].x,t),y:jt(c.y,e.points[h].y,t)}))}:{...t<1?i:e,bounds:n,angle:s,transparency:r,haloScale:a,color:o,physical:l}}class Pa{keyframes=[];order=[];groups=[];addKeyframe(e,t){const n=this.findInsertIndex(e);if(this.keyframes[n]?.t===e){const s=new Set(t.map(r=>r.sourceId));this.keyframes[n]={t:e,shapes:[...this.keyframes[n].shapes.filter(r=>!s.has(r.sourceId)),...t]}}else this.keyframes.splice(n,0,{t:e,shapes:[...t]});for(const s of t)this.order.includes(s.sourceId)||this.order.push(s.sourceId)}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}getKeyframeAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t];return n?.t===e?n:void 0}getShapeAt(e,t){return this.getKeyframeAt(e)?.shapes.find(n=>n.sourceId===t)?.shape}getLatestShapeAt(e,t){let n=this.findInsertIndex(e);for(this.keyframes[n]?.t!==e&&(n-=1);n>=0;n--){const s=this.keyframes[n].shapes.find(r=>r.sourceId===t);if(s)return s.shape}}getInterpolatedShapeAt(e,t){const n=this.findShapeAtOrBefore(e,t);if(n?.t===e)return n.shape;const s=this.findShapeAtOrAfter(e,t);return n?s?uf(n.shape,s.shape,(e-n.t)/(s.t-n.t)):n.shape:s?.shape}findShapeAtOrBefore(e,t){let n=this.findInsertIndex(e);for(this.keyframes[n]?.t!==e&&(n-=1);n>=0;n--){const s=this.keyframes[n].shapes.find(r=>r.sourceId===t);if(s)return{t:this.keyframes[n].t,shape:s.shape}}}findShapeAtOrAfter(e,t){for(let n=this.findInsertIndex(e);n<this.keyframes.length;n++){const s=this.keyframes[n].shapes.find(r=>r.sourceId===t);if(s)return{t:this.keyframes[n].t,shape:s.shape}}}hitTest(e,t,n,s){const r=this.sourceIds;for(let a=r.length-1;a>=0;a--){if(s?.has(r[a]))continue;const o=this.getInterpolatedShapeAt(e,r[a]);if(o&&cf(o,t,n))return{sourceId:r[a],shape:o}}}removeSource(e){for(let t=this.keyframes.length-1;t>=0;t--){const n=this.keyframes[t].shapes.filter(s=>s.sourceId!==e);n.length===0?this.keyframes.splice(t,1):n.length!==this.keyframes[t].shapes.length&&(this.keyframes[t]={t:this.keyframes[t].t,shapes:n})}this.order=this.order.filter(t=>t!==e),this.removeFromGroup(e)}group(e){if(!(e.length<2)){for(const t of e)this.removeFromGroup(t);this.groups.push([...e])}}ungroup(e){const t=this.groups.findIndex(n=>n.includes(e));t!==-1&&this.groups.splice(t,1)}groupMembers(e){return this.groups.find(t=>t.includes(e))}removeFromGroup(e){const t=this.groups.findIndex(s=>s.includes(e));if(t===-1)return;const n=this.groups[t].filter(s=>s!==e);n.length<2?this.groups.splice(t,1):this.groups[t]=n}bringToFront(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.push(e))}sendToBack(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.unshift(e))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e){const t=new Pa;for(const n of e.keyframes)t.addKeyframe(n.t,n.shapes);if(e.order){const n=t.order.filter(s=>!e.order.includes(s));t.order=[...e.order,...n]}return e.groups&&(t.groups=e.groups.map(n=>n.filter(s=>t.order.includes(s))).filter(n=>n.length>=2)),t}}function ff(i,e,t){return Math.max(e,Math.min(t,i))}function pf(i,e,t){const n=((e-i)%360+540)%360-180;return((i+n*t)%360+360)%360}function Is(i,e,t){return i+(e-i)*t}function mf(i,e,t){return{lat:i.lat===void 0||e.lat===void 0?void 0:Is(i.lat,e.lat,t),lng:i.lng===void 0||e.lng===void 0?void 0:Is(i.lng,e.lng,t),elevationM:Is(i.elevationM,e.elevationM,t),headingDeg:i.headingDeg===void 0||e.headingDeg===void 0?void 0:pf(i.headingDeg,e.headingDeg,t),pitchDeg:Is(i.pitchDeg,e.pitchDeg,t),fovDeg:Is(i.fovDeg,e.fovDeg,t)}}class nr{keyframes=[];addKeyframe(e,t){const n=this.findInsertIndex(e);this.keyframes[n]?.t===e?this.keyframes[n]={t:e,pose:t}:this.keyframes.splice(n,0,{t:e,pose:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}getLatestPoseAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].pose:void 0}getInterpolatedPoseAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(n?.t===e)return n.pose;const s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return n?s?mf(n.pose,s.pose,ff((e-n.t)/(s.t-n.t),0,1)):n.pose:s?.pose}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new nr;for(const n of e.keyframes)t.addKeyframe(n.t,n.pose);return t}}function Rs(i,e,t){return i+(e-i)*t}function gf(i,e,t){const n=((e-i)%360+540)%360-180;return((i+n*t)%360+360)%360}function vf(i,e,t){return Math.max(e,Math.min(t,i))}function _f(i,e,t){return{cloudCover:Rs(i.cloudCover,e.cloudCover,t),cloudDarkness:Rs(i.cloudDarkness,e.cloudDarkness,t),cloudBaseM:i.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:Rs(i.cloudBaseM,e.cloudBaseM,t),precipitationType:t<1?i.precipitationType:e.precipitationType,precipitationIntensity:Rs(i.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:gf(i.windDirectionDeg,e.windDirectionDeg,t),windSpeed:Rs(i.windSpeed,e.windSpeed,t),storm:t<1?i.storm:e.storm}}class ir{keyframes=[];addKeyframe(e,t){const n=this.findInsertIndex(e);this.keyframes[n]?.t===e?this.keyframes[n]={t:e,weather:t}:this.keyframes.splice(n,0,{t:e,weather:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}getLatestWeatherAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].weather:void 0}getInterpolatedWeatherAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(n?.t===e)return n.weather;const s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return n?s?_f(n.weather,s.weather,vf((e-n.t)/(s.t-n.t),0,1)):n.weather:s?.weather}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new ir;for(const n of e.keyframes)t.addKeyframe(n.t,n.weather);return t}}class sr{keyframes=[];addKeyframe(e,t){const n=this.findInsertIndex(e);this.keyframes[n]?.t===e?this.keyframes[n]={t:e,sound:t}:this.keyframes.splice(n,0,{t:e,sound:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}getLatestSoundAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].sound:void 0}getInterpolatedSoundAt(e){const t=this.findInsertIndex(e),n=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(n?.t===e)return n.sound;const s=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!n)return s?.sound;if(!s)return n.sound;const r=(e-n.t)/(s.t-n.t);return this.lerp(n.sound,s.sound,Math.max(0,Math.min(1,r)))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new sr;for(const n of e.keyframes)t.addKeyframe(n.t,n.sound);return t}lerp(e,t,n){return{kind:n<1?e.kind:t.kind,volume:e.volume+(t.volume-e.volume)*n,pitchHz:e.pitchHz+(t.pitchHz-e.pitchHz)*n,src:n<1?e.src:t.src}}findInsertIndex(e){let t=0,n=this.keyframes.length;for(;t<n;){const s=t+n>>>1;this.keyframes[s].t<e?t=s+1:n=s}return t}}const $o=1e3,gu={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1},xf=["none","hum","whistle","rumble","crackle"],Sf=100,yf={kind:"none",volume:0,pitchHz:Sf},bf=/^(?:(?<year>\d{4}|\d{3}X|\d{2}XX)(-(?<month>0[1-9]|1[0-2]))?(-(?<day>0[1-9]|[12]\d|3[01]))?(?:[T ](?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?)?|(?<timeOnlyHour>[01]?\d|2[0-3]):(?<timeOnlyMinute>[0-5]\d)(?::(?<timeOnlySecond>[0-5]\d))?)[?~%]?$/;function nh(i){const e=bf.exec(i.trim());if(!e?.groups)return;const{year:t,month:n,day:s,hour:r,minute:a,second:o,timeOnlyHour:l,timeOnlyMinute:c,timeOnlySecond:h}=e.groups,u=r??l,d=a??c,f=o??h;return{year:t&&!t.includes("X")?Number(t):void 0,month:n?Number(n):void 0,day:s?Number(s):void 0,hour:u?Number(u):void 0,minute:d?Number(d):void 0,second:f?Number(f):void 0,raw:i.trim()}}function ih(i){if(i.raw!==void 0)return i.raw;if(i.year===void 0){if(i.hour===void 0)return"";let t=`${String(i.hour).padStart(2,"0")}:${String(i.minute??0).padStart(2,"0")}`;return i.second!==void 0&&(t+=`:${String(i.second).padStart(2,"0")}`),t}let e=String(i.year).padStart(4,"0");return i.month===void 0||(e+=`-${String(i.month).padStart(2,"0")}`,i.day===void 0)||(e+=`-${String(i.day).padStart(2,"0")}`,i.hour===void 0)||(e+=`T${String(i.hour).padStart(2,"0")}:${String(i.minute??0).padStart(2,"0")}`,i.second!==void 0&&(e+=`:${String(i.second).padStart(2,"0")}`)),e}function Zo(i){if(i.year!==void 0)return Date.UTC(i.year,(i.month??1)-1,i.day??1,i.hour??0,i.minute??0,i.second??0)}function sh(i){return(((i.day??0)*24+(i.hour??0))*60+(i.minute??0))*6e4+(i.second??0)*1e3}const Mf=["year","month","day","hour","minute"],Ef=["day","hour","minute"];function rh(i,e){return e.filter(t=>i[t]!==void 0).join(",")}function rr(i){if(i.durationSeconds!==void 0)return i.durationSeconds*1e3;if(!i.time||!i.endTime)return;const e=i.time.year!==void 0&&i.endTime.year!==void 0,t=e?Mf:Ef,n=rh(i.time,t);if(!(n===""||n!==rh(i.endTime,t)))return e?Zo(i.endTime)-Zo(i.time):sh(i.endTime)-sh(i.time)}function wf(i){if(i.durationSeconds===void 0&&!(!i.time||!i.endTime))return rr(i)===void 0?"imprecise":void 0}class La{constructor(e,t,n,s,r,a,o,l,c=[],h){this.event=e,this.timeline=t,this.witnessTrack=n,this.weatherTrack=s,this.soundTrack=r,this.witness=a,this.caseId=o,this.weather=l,this.decor=c,this.weatherSource=h}static create(e,t,n){return new La({eventType:"sighting",time:e,place:t},new Pa,new nr,new ir,new sr,n)}}const Tf=0,Af=0,If=60;function Ss(i,e){const t=i.witnessTrack.getInterpolatedPoseAt(e);if(t)return t;const n=i.event.place?.[0];if(n)return{lat:n.lat,lng:n.lng,elevationM:Tf,headingDeg:void 0,pitchDeg:Af,fovDeg:If}}function Jo(i,e){return i.weatherTrack.getInterpolatedWeatherAt(e)??i.weather??gu}function vu(i,e){return i.soundTrack.getInterpolatedSoundAt(e)??yf}class Rf{constructor(e,t){this.timeline=e,this.onFrame=t}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT);return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const n of this.timeline.sourceIds){const s=this.timeline.getInterpolatedShapeAt(e,n);s&&t.set(n,s)}this.onFrame(e,t)}}const _u=["nw","n","ne","e","se","s","sw","w"],Cf=24,ai=8,xu=3,Df=8;function qs(i,e,t){const n=i.x-e.x,s=i.y-e.y,r=Math.cos(t),a=Math.sin(t);return{x:e.x+n*r-s*a,y:e.y+n*a+s*r}}function yi(i){return{x:i.x+i.width/2,y:i.y+i.height/2}}const Pf={nw:{left:!0,top:!0},n:{top:!0},ne:{right:!0,top:!0},e:{right:!0},se:{right:!0,bottom:!0},s:{bottom:!0},sw:{left:!0,bottom:!0},w:{left:!0}};class $e{static handlePointsFor(e){const{x:t,y:n,width:s,height:r}=e.bounds,a={nw:{x:t,y:n},n:{x:t+s/2,y:n},ne:{x:t+s,y:n},e:{x:t+s,y:n+r/2},se:{x:t+s,y:n+r},s:{x:t+s/2,y:n+r},sw:{x:t,y:n+r},w:{x:t,y:n+r/2},rotate:{x:t+s/2,y:n-Cf}},o=yi(e.bounds),l={};for(const c of Object.keys(a))l[c]=qs(a[c],o,e.angle);return l}static hitTestHandle(e,t,n=8,s=[..._u,"rotate"]){const r=$e.handlePointsFor(e);for(const a of s)if(Math.hypot(t.x-r[a].x,t.y-r[a].y)<=n)return a}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(e,t){const s=(($e.HANDLE_DIRECTION_DEG[e]+t*180/Math.PI)%180+180)%180/45,r=["ew","nwse","ns","nesw"];return r[Math.round(s)%r.length]}static resizeBounds(e,t,n,s){const r=yi(e),a=qs(s,r,-t),{x:o,y:l,width:c,height:h}=e,u=Pf[n];let d=o,f=l,g=o+c,x=l+h;return u.left&&(d=Math.min(a.x,g-ai)),u.right&&(g=Math.max(a.x,d+ai)),u.top&&(f=Math.min(a.y,x-ai)),u.bottom&&(x=Math.max(a.y,f+ai)),{x:d,y:f,width:g-d,height:x-f}}static resizeShape(e,t,n){if(t==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:s,height:r}=e.bounds,a=$e.resizeBounds(e.bounds,e.angle,t,n);if(e.kind==="oval")return{...e,bounds:a};const o=s===0?1:a.width/s,l=r===0?1:a.height/r;return{...e,bounds:a,points:e.points.map(c=>({x:c.x*o,y:c.y*l}))}}static rotateShape(e,t){const n=yi(e.bounds),s=Math.atan2(t.y-n.y,t.x-n.x)+Math.PI/2;return{...e,angle:s}}static groupBoundsFor(e){const t=Math.min(...e.map(a=>a.x)),n=Math.min(...e.map(a=>a.y)),s=Math.max(...e.map(a=>a.x+a.width)),r=Math.max(...e.map(a=>a.y+a.height));return{x:t,y:n,width:s-t,height:r-n}}static vertexPointsFor(e){const t=yi(e.bounds);return e.points.map(n=>qs({x:e.bounds.x+n.x,y:e.bounds.y+n.y},t,e.angle))}static hitTestVertex(e,t,n=Df){const s=$e.vertexPointsFor(e);let r,a=n;return s.forEach((o,l)=>{const c=Math.hypot(t.x-o.x,t.y-o.y);c<=a&&(a=c,r=l)}),r}static toLocalPoint(e,t){const n=yi(e.bounds),s=qs(t,n,-e.angle);return{x:s.x-e.bounds.x,y:s.y-e.bounds.y}}static moveVertex(e,t,n){const s=e.points.map((u,d)=>d===t?$e.toLocalPoint(e,n):u),r=Math.min(...s.map(u=>u.x)),a=Math.min(...s.map(u=>u.y)),o=Math.max(...s.map(u=>u.x)),l=Math.max(...s.map(u=>u.y)),c={x:e.bounds.x+r,y:e.bounds.y+a,width:o-r,height:l-a},h=s.map(u=>({x:u.x-r,y:u.y-a}));return{...e,bounds:c,points:h}}static insertVertexNear(e,t){const n=$e.toLocalPoint(e,t),{points:s}=e;let r=s.length-1,a=1/0;for(let l=0;l<s.length;l++){const c=s[l],h=s[(l+1)%s.length],u=$e.distanceToSegment(n,c,h);u<a&&(a=u,r=l)}const o=[...s.slice(0,r+1),n,...s.slice(r+1)];return{...e,points:o}}static distanceToSegment(e,t,n){const s=n.x-t.x,r=n.y-t.y,a=s*s+r*r,o=a===0?0:Math.max(0,Math.min(1,((e.x-t.x)*s+(e.y-t.y)*r)/a)),l=t.x+o*s,c=t.y+o*r;return Math.hypot(e.x-l,e.y-c)}static deleteVertex(e,t){return e.points.length<=xu?e:{...e,points:e.points.filter((n,s)=>s!==t)}}}class Xa{constructor(e){this.members=e}bounds(){return $e.groupBoundsFor(this.members.map(e=>e.shape.bounds))}scaleTo(e){const t=this.bounds(),n=t.width===0?1:e.width/t.width,s=t.height===0?1:e.height/t.height;return this.members.map(({sourceId:r,shape:a})=>{const o=Math.max(a.bounds.width*n,ai),l=Math.max(a.bounds.height*s,ai),c=e.x+(a.bounds.x-t.x)*n,h=e.y+(a.bounds.y-t.y)*s,u={x:c,y:h,width:o,height:l};return a.kind==="oval"?{sourceId:r,shape:{...a,bounds:u}}:{sourceId:r,shape:{...a,bounds:u,points:a.points.map(d=>({x:d.x*n,y:d.y*s}))}}})}resize(e,t){return this.scaleTo($e.resizeBounds(this.bounds(),0,e,t))}rotate(e,t){const n=yi(this.bounds()),s=a=>Math.atan2(a.y-n.y,a.x-n.x),r=s(e)-s(t);return this.members.map(({sourceId:a,shape:o})=>{const l=yi(o.bounds),c=qs(l,n,r),h={x:c.x-o.bounds.width/2,y:c.y-o.bounds.height/2,width:o.bounds.width,height:o.bounds.height};return{sourceId:a,shape:{...o,bounds:h,angle:o.angle+r}}})}}const Qo=6,gr=Qo/2,Lf=20,ah=4;class Nf{constructor(e){this.ctx=e}clear(e,t){this.ctx.clearRect(0,0,e,t)}paintShape(e){this.ctx.save(),this.ctx.globalAlpha=1-e.transparency,e.haloScale>0&&this.paintHalo(e),this.paintBase(e),this.ctx.restore(),e.selected&&this.paintSelectionHandles(e)}paintBase(e){if(this.ctx.fillStyle=e.color,this.ctx.beginPath(),e.kind==="oval"){const{x:t,y:n,width:s,height:r}=e.bounds,a=s/2,o=r/2;this.ctx.ellipse(t+a,n+o,a,o,e.angle,0,2*Math.PI)}else{const{x:t,y:n,width:s,height:r}=e.bounds;this.ctx.save(),this.ctx.translate(t+s/2,n+r/2),this.ctx.rotate(e.angle),this.ctx.translate(-s/2,-r/2),e.points.forEach((a,o)=>{o===0?this.ctx.moveTo(a.x,a.y):this.ctx.lineTo(a.x,a.y)}),this.ctx.closePath(),this.ctx.restore()}this.ctx.fill()}paintHalo(e){this.ctx.save(),this.ctx.shadowColor=e.color,this.ctx.shadowBlur=Lf*e.haloScale,this.paintBase(e),this.ctx.restore()}paintSelectionHandles(e){this.paintHandleFrame($e.handlePointsFor(e),{includeRotate:!0}),e.kind==="polygon"&&this.paintVertexHandles(e)}paintVertexHandles(e){this.ctx.fillStyle="#39f";for(const t of $e.vertexPointsFor(e))this.ctx.beginPath(),this.ctx.ellipse(t.x,t.y,ah,ah,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(e){this.paintOutline($e.handlePointsFor(e))}paintGroupHandles(e){this.paintHandleFrame($e.handlePointsFor({bounds:e,angle:0}),{includeRotate:!0})}paintOutline(e){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(e.nw.x,e.nw.y),this.ctx.lineTo(e.ne.x,e.ne.y),this.ctx.lineTo(e.se.x,e.se.y),this.ctx.lineTo(e.sw.x,e.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(e,{includeRotate:t}){this.paintOutline(e),this.ctx.fillStyle="lightgray";for(const n of _u){const s=e[n];this.ctx.fillRect(s.x-gr,s.y-gr,Qo,Qo)}t&&(this.ctx.beginPath(),this.ctx.moveTo(e.n.x,e.n.y),this.ctx.lineTo(e.rotate.x,e.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(e.rotate.x,e.rotate.y,gr+1,gr+1,0,0,2*Math.PI),this.ctx.fill())}}const oh=.05,lh=.08,ch=2,hh=3,Uf=14,Ff=.02;class Of{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}this.context.state==="suspended"&&this.context.resume()}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const n=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,n):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const n=this.context;if(!e||!n)return;const s=n.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,s,oh);for(const{param:r,ratio:a}of e.pitch)r.setTargetAtTime(Math.min(t.pitchHz*a,n.sampleRate/2-1),s,oh)}buildSynthesizedVoice(e,t){const n=this.context;if(n)switch(e.kind){case"hum":return this.buildHum(n,t);case"whistle":return this.buildWhistle(n,t);case"rumble":return this.buildRumble(n,t);case"crackle":return this.buildCrackle(n,t);default:return}}buildHum(e,t){const n=e.createOscillator();n.type="sawtooth";const s=e.createOscillator();s.type="sawtooth";const r=e.createBiquadFilter();r.type="lowpass",r.Q.value=1;const a=e.createGain();return a.gain.value=0,n.connect(r),s.connect(r),r.connect(a).connect(e.destination),n.start(),s.start(),{key:t,nodes:[r,a],sources:[n,s],volumeParam:a.gain,gainScale:.16,pitch:[{param:n.frequency,ratio:1},{param:s.frequency,ratio:1.006},{param:r.frequency,ratio:6}]}}buildWhistle(e,t){const n=e.createOscillator();n.type="sine";const s=e.createOscillator();s.type="sine",s.frequency.value=5;const r=e.createGain(),a=e.createGain();return a.gain.value=0,s.connect(r).connect(n.frequency),n.connect(a).connect(e.destination),n.start(),s.start(),{key:t,nodes:[r,a],sources:[n,s],volumeParam:a.gain,gainScale:.22,pitch:[{param:n.frequency,ratio:1},{param:r.gain,ratio:.012}]}}buildRumble(e,t){const n=e.createBufferSource();n.buffer=this.brownNoise(e),n.loop=!0;const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=.8;const r=e.createGain();return r.gain.value=0,n.connect(s).connect(r).connect(e.destination),n.start(),{key:t,nodes:[s,r],sources:[n],volumeParam:r.gain,gainScale:1.4,pitch:[{param:s.frequency,ratio:1}]}}buildCrackle(e,t){const n=e.createBufferSource();n.buffer=this.whiteNoise(e),n.loop=!0;const s=e.createBiquadFilter();s.type="bandpass",s.Q.value=1.2;const r=e.createGain();r.gain.value=0;const a=e.createBufferSource();a.buffer=this.crackleEnvelope(e),a.loop=!0;const o=e.createGain();return o.gain.value=0,a.connect(o).connect(r.gain),n.connect(s).connect(r).connect(e.destination),n.start(),a.start(),{key:t,nodes:[s,r,o],sources:[n,a],volumeParam:o.gain,gainScale:.9,pitch:[{param:s.frequency,ratio:4}]}}async buildRecordedVoice(e,t,n){const s=this.context;if(!s)return;let r;try{r=await this.getBuffer(e)}catch(l){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",l);return}if(n!==this.voiceToken||!this.context)return;const a=s.createBufferSource();a.buffer=r,a.loop=!0;const o=s.createGain();o.gain.value=0,a.connect(o).connect(s.destination),a.start(),this.voice={key:t,nodes:[o],sources:[a],volumeParam:o.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let n=this.buffers.get(e);return n||(n=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,n)),n}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*ch),e.sampleRate),n=t.getChannelData(0);for(let s=0;s<n.length;s++)n[s]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*ch),e.sampleRate),n=t.getChannelData(0);let s=0,r=0;for(let a=0;a<n.length;a++)s=(s+.02*(Math.random()*2-1))/1.02,n[a]=s,r=Math.max(r,Math.abs(s));if(r>0)for(let a=0;a<n.length;a++)n[a]/=r;return t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*hh),e.sampleRate),n=t.getChannelData(0),s=Math.max(1,Math.floor(Ff*e.sampleRate)),r=Math.round(hh*Uf);for(let a=0;a<r;a++){const o=Math.floor(Math.random()*n.length),l=.4+Math.random()*.6;for(let c=0;c<s&&o+c<n.length;c++)n[o+c]=Math.max(n[o+c],l*(1-c/s))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const n=t.currentTime;e.volumeParam.cancelScheduledValues(n),e.volumeParam.setTargetAtTime(0,n,lh/3);const s=n+lh;for(const r of e.sources){r.onended=()=>{r.disconnect();for(const a of e.nodes)a.disconnect()};try{r.stop(s)}catch{r.disconnect();for(const a of e.nodes)a.disconnect()}}}}function Bf(i){return{version:1,time:i.event.time,endTime:i.event.endTime,durationSeconds:i.event.durationSeconds,utcOffsetHours:i.event.utcOffsetHours,timeZone:i.event.timeZone,place:i.event.place,witness:i.witness,caseId:i.caseId,description:i.event.description,tags:i.event.tags,timeline:i.timeline.toJSON(),witnessTrack:i.witnessTrack.toJSON(),weatherTrack:i.weatherTrack.toJSON(),soundTrack:i.soundTrack.toJSON(),weather:i.weather,decor:i.decor,weatherSource:i.weatherSource}}function kf(i){return new La({eventType:"sighting",time:i.time,endTime:i.endTime,durationSeconds:i.durationSeconds,utcOffsetHours:i.utcOffsetHours,timeZone:i.timeZone,place:i.place,description:i.description,tags:i.tags},Pa.fromJSON(i.timeline),i.witnessTrack?nr.fromJSON(i.witnessTrack):new nr,i.weatherTrack?ir.fromJSON(i.weatherTrack):new ir,i.soundTrack?sr.fromJSON(i.soundTrack):new sr,i.witness,i.caseId,i.weather,i.decor??[],i.weatherSource)}function Na(i,e){for(const t of i){const n=t.toLowerCase().split("-")[0];if(e.includes(n))return n}return"en"}const zf="modulepreload",Gf=function(i,e){return new URL(i,e).href},dh={},va=function(e,t,n){let s=Promise.resolve();if(t&&t.length>0){let a=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");s=a(t.map(h=>{if(h=Gf(h,n),h in dh)return;dh[h]=!0;const u=h.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(!!n)for(let x=o.length-1;x>=0;x--){const m=o[x];if(m.href===h&&(!u||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${d}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":zf,u||(g.as="script"),g.crossOrigin="",g.href=h,c&&g.setAttribute("nonce",c),document.head.appendChild(g),u)return new Promise((x,m)=>{g.addEventListener("load",x),g.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function r(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return s.then(a=>{for(const o of a||[])o.status==="rejected"&&r(o.reason);return e().catch(r)})},Su=["en","fr"],Hf={en:()=>va(()=>Promise.resolve().then(()=>qf),void 0,import.meta.url).then(i=>i.ufoMessages_en),fr:()=>va(()=>import("./UfoMessages_fr-NZrwNFCQ.js"),[],import.meta.url).then(i=>i.ufoMessages_fr)};function Vf(i){return Hf[i]()}const Wf={en:()=>va(()=>Promise.resolve().then(()=>pb),void 0,import.meta.url).then(i=>i.ufoRecorderMessages_en),fr:()=>va(()=>import("./UfoRecorderMessages_fr-DU4ld1Gl.js"),[],import.meta.url).then(i=>i.ufoRecorderMessages_fr)};function Xf(i){return Wf[i]()}const yu={play:"Play",pause:"Pause",noDuration:"No observation duration",autoReplay:"Auto-replay",currentPosition:"Current position",duration:"Duration",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen"},qf=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:yu},Symbol.toStringTag,{value:"Module"})),uh=new Set;class Yf extends HTMLElement{static get observedAttributes(){return["src"]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;playPauseButton;loopButton;fullscreenButton;seekInput;timeStartLabel;timeEndLabel;currentSighting=La.create();sightingAudio=new Of;soundPreview;player;loopEnabled=!0;highlightedSourceIds=new Set;occludedSourceIds=uh;enableClickToPlay=!0;fullscreenTarget;messages=yu;realDurationMs;realStartMs;handleFullscreenChange=()=>this.updateFullscreenButton();handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),n=t&&this.currentSighting.timeline.hitTest(this.currentTime,t.x,t.y,this.occludedSourceIds);if(!n?.shape.title){this.tooltip.hidden=!0;return}this.tooltip.textContent=n.shape.title,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-s.left+12}px`,this.tooltip.style.top=`${e.clientY-s.top+12}px`};handlePointerLeave=()=>{this.tooltip.hidden=!0};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${sf}</style>${nf}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Nf(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.loopButton=this.shadow.getElementById("loop"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.seekInput=this.shadow.getElementById("seek"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.loopButton.addEventListener("click",()=>this.toggleLoop()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.seekInput.addEventListener("input",()=>this.player.seek(Number(this.seekInput.value))),this.canvas.addEventListener("click",()=>{this.enableClickToPlay&&this.togglePlayPause()}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.refresh(),this.loadLocaleMessages()}connectedCallback(){const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sightingAudio.dispose()}attributeChangedCallback(e,t,n){e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n)}async loadFromSrc(e){const t=await fetch(e);this.sightingData=await t.json()}get sightingData(){return Bf(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=kf(e),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh()}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}setOccludedSourceIds(e){e.size===this.occludedSourceIds.size&&[...e].every(n=>this.occludedSourceIds.has(n))||(this.occludedSourceIds=e,this.refresh())}hasVisibleShapeAt(e,t){return this.currentSighting.timeline.hitTest(this.currentTime,e,t,this.occludedSourceIds)!==void 0}refresh(){this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.player.seek(this.player.time)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const n=this.playbackState!=="playing"?this.highlightedSourceIds:uh;for(const[s,r]of t){if(this.occludedSourceIds.has(s))continue;const a=n.has(s);a&&n.size===1?this.canvasRenderer.paintShape({...r,selected:!0}):(this.canvasRenderer.paintShape(r),a&&this.canvasRenderer.paintMemberOutline(r))}if(n.size>1){const s=$e.groupBoundsFor([...t].filter(([r])=>n.has(r)).map(([,r])=>r.bounds));this.canvasRenderer.paintGroupHandles(s)}this.seekInput.value=String(e),this.timeStartLabel.textContent=this.formatPosition(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(vu(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}createPlayer(){const e=new Rf(this.currentSighting.timeline,(t,n)=>this.onFrame(t,n));return e.loop=this.loopEnabled,e}togglePlayPause(){this.player.seekableDuration<=0||(this.player.playbackState==="playing"?(this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh()):(this.sightingAudio.resume(),this.player.play()),this.updatePlayPauseButton())}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.playPauseButton.textContent=e?"⏸":"▶";const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const n=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=n,this.playPauseButton.setAttribute("aria-label",n),this.toolbar.classList.toggle("auto-hide",e),this.fullscreenButton.classList.toggle("auto-hide",e)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.loopButton.setAttribute("aria-pressed",String(this.loopEnabled)),this.player.loop=this.loopEnabled}toggleFullscreen(){document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}updateFullscreenButton(){const e=document.fullscreenElement===this.fullscreenTarget;this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}async loadLocaleMessages(){const e=Na(navigator.languages,Su);e!=="en"&&this.applyMessages(await Vf(e))}applyMessages(e){this.messages=e,this.timeStartLabel.title=e.currentPosition,this.timeEndLabel.title=e.duration,this.loopButton.title=e.autoReplay,this.loopButton.setAttribute("aria-label",e.autoReplay),this.updatePlayPauseButton(),this.updateFullscreenButton()}updateTimeLabels(){const e=this.currentSighting.event,t=rr(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Zo(e.time):void 0;const n=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&n>0?n/this.realDurationMs:1,this.player.durationOverrideMs=n>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time)}formatPosition(e){if(this.realDurationMs===void 0)return vr(e);const t=this.currentSighting.timeline.duration,n=t>0&&e<=t?e/t*this.realDurationMs:e;return this.realStartMs!==void 0?ph(fh(this.realStartMs+n)):vr(n)}formatEndOfTimeline(){return this.realDurationMs===void 0?vr(this.currentSighting.timeline.duration):this.realStartMs!==void 0?ph(fh(this.realStartMs+this.realDurationMs)):vr(this.realDurationMs)}}function fh(i){const e=new Date(i);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function ph(i){if(i.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return i.second?`${e(i.hour)}:${e(i.minute??0)}:${e(i.second)}`:`${e(i.hour)}:${e(i.minute??0)}`}function vr(i){const e=Math.round(i/1e3),t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,"0")}`}const jo="rr0-ufo";function Ua(){customElements.get(jo)||customElements.define(jo,Yf)}const Kf=`
|
|
869
869
|
<div class="stage" id="stage">
|
|
870
870
|
<div class="frame" id="frame">
|
|
871
871
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -5755,4 +5755,4 @@ void main() {
|
|
|
5755
5755
|
float blur = max(vNearBlur, vHaze);
|
|
5756
5756
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
5757
5757
|
}
|
|
5758
|
-
`;let ra;function wy(){if(ra)return ra;const i=128,e=document.createElement("canvas");e.width=i,e.height=i;const t=e.getContext("2d"),n=t.createRadialGradient(i/2,i/2,0,i/2,i/2,i/2);return n.addColorStop(0,"rgba(255,255,255,1)"),n.addColorStop(.4,"rgba(255,255,255,0.35)"),n.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=n,t.fillRect(0,0,i,i),ra=new Wn(e),ra}function Ty(i){const t=document.createElement("canvas");t.width=128,t.height=128;const n=t.getContext("2d"),s=128/2-2,r=128/2,a=128/2,o="#2e2b26",l="#f4f1e2";n.fillStyle=o,n.beginPath(),n.arc(r,a,s,0,Math.PI*2),n.fill();const c=V0(i.illuminatedFraction,0,1),h=i.phaseFraction<.5,u=s*Math.abs(1-2*c),d=c<.5;return n.save(),n.beginPath(),n.arc(r,a,s,0,Math.PI*2),n.clip(),n.fillStyle=l,n.beginPath(),h?(n.arc(r,a,s,-Math.PI/2,Math.PI/2,!1),n.ellipse(r,a,u,s,0,Math.PI/2,-Math.PI/2,d)):(n.arc(r,a,s,Math.PI/2,-Math.PI/2,!1),n.ellipse(r,a,u,s,0,-Math.PI/2,Math.PI/2,d)),n.fill(),n.restore(),new Wn(t)}function Ay(i){const e=document.createElement("canvas");e.width=128,e.height=128;const t=e.getContext("2d");return t.fillStyle="rgba(0, 0, 0, 0.55)",t.beginPath(),t.arc(64,64,60,0,Math.PI*2),t.fill(),t.fillStyle="#ffffff",t.font="bold 52px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(i,64,68),new Wn(e)}function Wo(i){let e=i;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}const iu=new Map;function Iy(i){const e=i.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),t=e,n=t*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(i,0*n,t),dec:new Float32Array(i,1*n,t),mag:new Float32Array(i,2*n,t),ci:new Float32Array(i,3*n,t)}}function Ry(i){let e=iu.get(i);return e||(e=fetch(i).then(t=>t.arrayBuffer()).then(Iy),iu.set(i,e)),e}const Cy=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,Dy=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,Py=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,Ly=20,Ny=1;class Uy{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}this.context.state==="suspended"&&this.context.resume()}setAmbient(e,t,n){if(this.requested={type:e,intensity:t,windSpeed:n},!this.context)return;this.paused&&(e="none",t=0,n=0);const s=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=s==="hail"?Math.min(1,t*1.3+.2):s==="rain"?t:0,s!==this.ambientKey){this.ambientKey=s;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,s!=="none"&&this.startLoop(Cy,this.ambientVolume).then(o=>this.applyIfCurrent(o,a,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(n/Ly,1);const r=n>Ny;if(r!==this.windActive){this.windActive=r;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,r&&this.startLoop(Dy,this.windVolume).then(o=>this.applyIfCurrent(o,a,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:n,windSpeed:s}=this.requested;this.setAmbient(t,n,s)}playThunder(){!this.context||this.paused||this.playOneShot(Py,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.buffers.clear()}applyIfCurrent(e,t,n,s){if(t!==n()){e?.source.stop();return}s(e)}async startLoop(e,t){const n=this.context;if(n)try{const s=await this.getBuffer(e),r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();return a.gain.value=t,r.connect(a).connect(n.destination),r.start(),{source:r,gain:a}}catch(s){console.warn("Weather ambient sound failed to load, staying silent:",s);return}}async playOneShot(e,t){const n=this.context;if(n)try{const s=await this.getBuffer(e),r=n.createBufferSource();r.buffer=s;const a=n.createGain();a.gain.value=t,r.connect(a).connect(n.destination),r.start()}catch(s){console.warn("Thunder sound failed to load:",s)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let n=this.buffers.get(e);return n||(n=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,n)),n}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}Ua();const Fy={sun:{en:"Sun",fr:"Soleil"},moon:{en:"Moon",fr:"Lune"},Venus:{en:"Venus",fr:"Vénus"},Mars:{en:"Mars",fr:"Mars"},Jupiter:{en:"Jupiter",fr:"Jupiter"},Saturn:{en:"Saturn",fr:"Saturne"}},Oy=["en","fr"],By={building:{en:"Building",fr:"Bâtiment"},tree:{en:"Tree",fr:"Arbre"},streetlight:{en:"Streetlight",fr:"Lampadaire"},vehicle:{en:"Vehicle",fr:"Véhicule"},witness:{en:"Witness",fr:"Témoin"}},ky=new URL(""+new URL("stars-mag7.5-DDr9QasD.bin",import.meta.url).href,import.meta.url).href,zy={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Xo={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Gy extends HTMLElement{static get observedAttributes(){return["src","star-catalog-src","show-compass","lens-flare-intensity","lens-flare-brightness"]}shadow;stageElement;frameElement;sceneCanvas;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;lastTimeMs=0;starCatalog;weatherAudio=new Uy;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(n.width===0||n.height===0)return;const s=(e.clientX-n.left)/n.width*t.width,r=(e.clientY-n.top)/n.height*t.height;if(this.ufoElement.hasVisibleShapeAt(s,r)){this.hoverTooltip.hidden=!0;return}const a=(e.clientX-n.left)/n.width*2-1,o=-((e.clientY-n.top)/n.height*2-1),l=Na(navigator.languages,Oy),c=this.sceneRenderer.pickBodyAt(a,o);if(c){this.showHoverTooltip(e,Fy[c]?.[l]??c);return}const h=this.sceneRenderer.pickDecorAt(a,o),u=h?this.ufoElement.sighting.decor.find(d=>d.id===h):void 0;if(u){this.showHoverTooltip(e,u.title||By[u.kind][l]);return}this.hoverTooltip.hidden=!0};showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.hoverTooltip.style.left=`${e.clientX-n.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-n.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash=()=>{clearTimeout(this.thunderTimeoutId);const e=(.5+Math.random()*3.5)*1e3;this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),e)};handleFirstInteraction=()=>{this.weatherAudio.resume(),this.setWeather(Jo(this.ufoElement.sighting,this.lastTimeMs))};handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.updateUfoOcclusion(this.lastTimeMs)};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e),this.weatherAudio.setPaused(!e),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${$f}</style>${Kf}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new gy(this.sceneCanvas,void 0,this.handleLightningFlash),this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(jo),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave),this.ufoElement.canvasElement.addEventListener("pointerdown",this.handleFirstInteraction,{once:!0})}connectedCallback(){this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),document.addEventListener("fullscreenchange",this.handleFullscreenChange);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose()}attributeChangedCallback(e,t,n){if(e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n),e==="star-catalog-src"&&n!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&n!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="lens-flare-intensity"&&n!==t){const s=n===null?NaN:parseFloat(n);this.sceneRenderer.setLensFlareArtifactIntensity(Number.isFinite(s)?s:0)}if(e==="lens-flare-brightness"&&n!==t){const s=n===null?NaN:parseFloat(n);this.sceneRenderer.setDazzleIntensity(Number.isFinite(s)?s:1)}}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity,e.windSpeed)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume()}async loadFromSrc(e){const t=await fetch(e);this.sightingData=await t.json()}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.lastTimeMs=0,this.updateAstronomy(0)}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=n,this.sceneRenderer.resize(t,n)}async loadStars(){const e=this.getAttribute("star-catalog-src")??ky;this.starCatalog=await Ry(e),this.updateAstronomy(this.lastTimeMs)}updateAstronomy(e){const t=this.ufoElement.sighting;this.setWeather(Jo(t,e)),this.sceneRenderer.setDecor(t.decor);const n=Ss(t,e);this.sceneRenderer.setObserverPose(n??Xo),this.sceneRenderer.updateDecorAnchoring(Ss(t,0),n),this.sceneRenderer.updateDecorLitState(e),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng);const s=n?.lat??Xo.lat,r=n?.lng??Xo.lng,a=Hc(t.event.time??{},r,t.event.utcOffsetHours);if(!a){this.sceneRenderer.setAstronomy(zy);return}const o=new Date(a.getTime()+e),l={lat:s,lng:r,elevationM:n?.elevationM??0},c={...Do("Sun",o,l),magnitude:Po("Sun",o)},h={...Do("Moon",o,l),phase:CS(o),magnitude:Po("Moon",o)},u=IS.map(d=>({body:d,position:Do(d,o,l),magnitude:Po(d,o)}));this.sceneRenderer.setAstronomy({sun:c,moon:h,planets:u,stars:this.starCatalog?{catalog:this.starCatalog,date:o,observer:l}:void 0})}updateUfoOcclusion(e){const t=this.ufoElement.sighting.timeline,n=this.ufoElement.canvasElement,s=new Set;for(const r of t.sourceIds){const a=t.getInterpolatedShapeAt(e,r);if(!a)continue;const o=(a.bounds.x+a.bounds.width/2)/n.width*2-1,l=-((a.bounds.y+a.bounds.height/2)/n.height*2-1),c={declared:a.behindCloud,distanceM:a.physical?.distanceM};this.sceneRenderer.isScreenPointOccluded(o,l,r,c)&&s.add(r)}this.ufoElement.setOccludedSourceIds(s)}}const xc="rr0-scene";function Hy(){Ua(),customElements.get(xc)||customElements.define(xc,Gy)}class Vy{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(n=>this.recordSample(n))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=mu(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class Wy{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const n=performance.now()-this.startTime;n-this.lastTick>=this.intervalMs&&(this.lastTick=n,e(n)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}const aa=36e5,su=25;class qo{constructor(e){this.provider=e}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{origin:n,start:s}=t,r=rr(e.event)??0,a=this.sampleTimings(e,s,r);let o;try{o=await this.provider.getWeather({points:a.map(l=>this.pointAt(e,l,n))})}catch{return{status:"failed",at:s}}return o?{status:"inferred",at:s,source:o.source,keyframes:o.samples.map((l,c)=>({t:a[c].t,weather:l.weather}))}:{status:"unavailable",at:s}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const n of t.keyframes)e.weatherTrack.addKeyframe(n.t,n.weather);e.weatherSource=t.source}}sampleTimes(e,t){const n=[e],s=e.getTime()+t;let r=Math.floor(e.getTime()/aa)*aa+aa;for(;r<=s&&n.length<su;)n.push(new Date(r)),r+=aa;return t>0&&n[n.length-1].getTime()!==s&&n.length<su&&n.push(new Date(s)),n}sampleTimings(e,t,n){const s=e.timeline.duration>0?e.timeline.duration:n;return n<=0||s<=0?[{time:t,t:0}]:this.sampleTimes(t,n).map(r=>{const a=(r.getTime()-t.getTime())/n;return{time:r,t:Math.round(s*Math.max(0,Math.min(1,a)))}})}canInfer(e){return this.questionOf(e)!==void 0}questionOf(e){const t=this.originOf(e);if(!t)return;const n=e.event.time;if(n?.year===void 0||n.month===void 0||n.day===void 0)return;const s=Hc(n,t.lng,e.event.utcOffsetHours);return s?{origin:t,start:s}:void 0}originOf(e){const t=Ss(e,0),n=e.event.place?.[0],s=t?.lat??n?.lat,r=t?.lng??n?.lng;return s===void 0||r===void 0?void 0:{lat:s,lng:r}}pointAt(e,t,n){const s=Ss(e,t.t);return{lat:s?.lat??n.lat,lng:s?.lng??n.lng,time:t.time}}}const Xy=Date.UTC(1940,0,1),ru=36e5,au=.25,qy=.7,Yy=.45,Ky=.1,$y=2,Zy=.3,Jy=.2,Qy=8,Yo=.125,jy=.05,eb=125,tb=100,nb=2500,ou=3500,lu=8e3,ib=95,sb=99,rb=[96,99],ab=["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"];class W0{fetchImpl;baseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive"}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(f=>f.time.getTime()),n=Math.min(...t);if(n<Xy)return;const s=new Map;for(const f of e.points){const g=this.cellKey(f);s.has(g)||s.set(g,{lat:f.lat,lng:f.lng,index:s.size})}const r=this.requestUrl([...s.values()],new Date(n),new Date(Math.max(...t))),a=this.cache.get(r);if(a)return a;const o=await this.fetchImpl(r);if(!o.ok)throw new Error(`Open-Meteo HTTP ${o.status}`);const l=await o.json(),c=Array.isArray(l)?l:[l];if(c.length<s.size||c.some(f=>f.error||!f.hourly))return;const h={id:"era5",name:"ERA5 (Open-Meteo)",url:r},u=e.points.map(f=>this.sampleAt(c[s.get(this.cellKey(f)).index].hourly,f.time));if(u.some(f=>f===void 0))return;const d={samples:u,source:h};return this.cache.set(r,d),d}cellKey(e){return`${Math.round(e.lat/au)},${Math.round(e.lng/au)}`}requestUrl(e,t,n){const s=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(n),hourly:ab.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${this.baseUrl}?${s}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const n=this.recordAt(e,t);return n&&{time:t,weather:this.toWeather(n)}}recordAt(e,t){const n=e.time.map(o=>Date.parse(`${o}Z`)),s=t.getTime();if(n.length===0||s<n[0]-ru||s>n[n.length-1]+ru)return;if(s<=n[0])return this.recordFrom(e,0);if(s>=n[n.length-1])return this.recordFrom(e,n.length-1);let r=0;for(;r+1<n.length&&n[r+1]<=s;)r++;const a=n[r+1]-n[r];return this.blendRecords(this.recordFrom(e,r),this.recordFrom(e,r+1),a>0?(s-n[r])/a:0)}recordFrom(e,t){const n={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(n).some(s=>s===void 0||Number.isNaN(s))?void 0:n}blendRecords(e,t,n){if(!e||!t)return e??t;const s=(a,o)=>a+(o-a)*n,r=((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:n<.5?e.weatherCode:t.weatherCode,windSpeedMs:s(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+r*n)%360+360)%360,temperatureC:s(e.temperatureC,t.temperatureC),dewPointC:s(e.dewPointC,t.dewPointC)}}toWeather(e){const t=e.weatherCode>=ib&&e.weatherCode<=sb,n=this.precipitationTypeFrom(e);return{cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),precipitationType:n,precipitationIntensity:n==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/Qy),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":rb.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const n=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(n<=0)return 0;const s=(qy*e.cloudCoverLow+Yy*e.cloudCoverMid+Ky*e.cloudCoverHigh)/n,r=Math.min(1,e.precipitationMm/$y);return this.clamp(s+Zy*r+(t?Jy:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<jy)return;const t=this.clamp(eb*(e.temperatureC-e.dewPointC),tb,nb);if(e.cloudCoverLow>=Yo)return Math.round(t);if(e.cloudCoverMid>=Yo)return ou;if(e.cloudCoverHigh>=Yo)return lu;const n=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(n<=0))return n===e.cloudCoverLow?Math.round(t):n===e.cloudCoverMid?ou:lu}clamp(e,t,n){return Math.max(t,Math.min(n,e))}}function ob(){return new W0}const lb=5;class X0{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,n={}){const s=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});n.language&&s.set("accept-language",n.language);const r=`${this.reverseUrl}?${s}`,a=this.cache.get(r);if(a)return a[0];const o=await this.fetchImpl(r,{signal:n.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const l=await o.json(),c=l.error?void 0:this.toMatch(l);return this.cache.set(r,c?[c]:[]),c}async search(e,t={}){const n=e.trim();if(n==="")return[];const s=this.requestUrl(n,t),r=this.cache.get(s);if(r)return r;const a=await this.fetchImpl(s,{signal:t.signal});if(!a.ok)throw new Error(`Nominatim HTTP ${a.status}`);const o=await a.json(),l=(Array.isArray(o)?o:[]).map(c=>this.toMatch(c)).filter(c=>c!==void 0);return this.cache.set(s,l),l}requestUrl(e,t){const n=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??lb)});return t.language&&n.set("accept-language",t.language),`${this.baseUrl}?${n}`}toMatch(e){const t=e.display_name??e.name,n=this.coordinate(e.lat),s=this.coordinate(e.lon);return t&&n!==void 0&&s!==void 0?{name:t,lat:n,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 cb(){return new X0}const hb=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new X0}],db=[{id:"era5",name:"ERA5 (Open-Meteo)",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new W0}];class ub{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return{source:await C0(e,t,s=>this.tileUrlTemplate.replace("{z}",String(s.z)).replace("{y}",String(s.y)).replace("{x}",String(s.x)),this.fetchImpl),width:t.width,height:t.height}}}const Ko=[{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new R0}],cu=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:()=>new D0},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:()=>new ub}];class Wc{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const n=Wc.SPAN_DEG;try{const r=(await this.provider.getElevationGrid({south:e-n,north:e+n,west:t-n,east:t+n},{width:2,height:2})).heights[0];return Number.isFinite(r)?r:void 0}catch{return}}}class fb{available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const n=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(n));if(s!==void 0)return this.zoneOffsetHours(e,new Date(n-s*36e5))??s}zoneOffsetHours(e,t){let n;try{n=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).formatToParts(t).find(r=>r.type==="timeZoneName")?.value??""}catch{return}const s=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(n);if(s)return s[1]?(s[1]==="-"?-1:1)*(Number(s[2])+Number(s[3])/60):0}}function Xs(i,e){return i.find(t=>t.id===e)??i[0]}const q0={oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",color:"Color",transparency:"Transparency",halo:"Halo",shape:"Shape",shapeTitle:"Name",objectSize:"Real size",objectDistance:"Distance",apparentSize:"i.e. {deg}° — {moons}× the Moon",utcOffset:"Time zone",utcOffsetPlaceholder:"from longitude",objectSizePlaceholder:"reported width",objectDistancePlaceholder:"reported distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",autoReplay:"Auto-replay",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",confirmDeleteShape:"Delete {name}? This can't be undone.",confirmDeleteShapes:"Delete {count} shapes? This can't be undone.",onlyOneShape:"There is only one shape",alreadyAtFront:"This shape is already at the front",alreadyAtBack:"This shape is already at the back",needTwoShapesToGroup:"Select at least two shapes to group them",notGrouped:"This shape isn't part of a group",multipleShapesSelected:"Multiple shapes selected — select just one to edit this",cloudBase:"Cloud base",elevation:"Altitude",samplingRate:"Sampling rate",duration:"Duration",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Export JSON",importFile:"Load JSON file",importUrl:"Or load from URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Load",importError:"Couldn't load that recording — check the file or URL and try again.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",placeName:"Place",placeNamePlaceholder:"Valensole, France",searchPlace:"Locate",placeMatch:"Matches",placeSearching:"Looking up the place…",placeMatchFound:"place found",placeMatchesFound:"places found",placeNotFound:"No place by that name",placeSearchFailed:"Place search temporarily unavailable",utcOffsetImplausible:"This time zone doesn't match the longitude entered, whose own solar time is UTC{solar} — yet the scene and the weather record both obey what is declared here. Clear the field to derive it from the longitude.",timeZoneManual:"offset entered",altitudeAboveSeaLevel:"The witness's altitude above sea level — the ground at the location entered sets its floor: a witness in the Alps is not at 0 m.",groundAt:"ground at {m} m",latitude:"Latitude",longitude:"Longitude",heading:"Heading",headingPlaceholder:"unknown",pitch:"Tilt",observationTime:"Observation start",observationEndTime:"Observation end",edtfInvalid:"Not a valid EDTF date/time (e.g. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"YYYY-MM-DDThh:mm[?~%] or hh:mm",observationTimeHint:"EDTF — e.g. 1965-07-01T05:00, 2025-06? (uncertain), 2025~ (approximate), or just 05:00 if the date isn't known",observationEndTimeHint:"EDTF — e.g. 1965-07-01T05:10, 2025-06? (uncertain), 2025~ (approximate), or just 05:10 if the date isn't known",presetsGroupLabel:"UFO shape",witnessId:"Witness ID",witnessDirName:"Witness dir name",witnessTitle:"Witness title",witnessLastName:"Witness last name",witnessFirstNames:"Witness first names",caseId:"Case ID",description:"Description",tags:"Tags",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Shape",soundGroup:"Sound",temporalGroup:"Date and time",locationGroup:"Location",observationGroup:"Observation",witnessGroup:"Witness",circumstancesGroup:"Circumstances",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't testimony: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the witness reported, which then override the record.",weatherFrom:"From",weatherLookingUp:"Looking up the record…",weatherNeedsDateAndPlace:"A full date and a place are needed to look up the record",weatherNoRecord:"No record for this date and place",weatherLookupFailed:"Weather records temporarily unreachable",cloudCover:"Cloud cover",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",soundSrcPlaceholder:"URL of a real recording",lensFlareBrightness:"Light intensity",cameraDevice:"Camera/video device",decor:"Decor",decorBuilding:"Building",decorTree:"Tree",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorWitness:"Other witness",addDecor:"Add",deleteDecor:"Delete decor",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorLit:"Lit",decorTitle:"Name",decorSightingUrl:"Witness's own recording URL",viewTestimony:"View testimony",noWitnessRecording:"No recording URL set for this witness",masks:"Masks",addWitness:"Add witness",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorWitnessSide:"Witness location",decorWitnessSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},pb=Object.freeze(Object.defineProperty({__proto__:null,ufoRecorderMessages_en:q0},Symbol.toStringTag,{value:"Module"}));Ua();Hy();const ls={width:48,height:28},mb=2500,gb=600,vb=900,oa=2e-4,_b=900,xb=3,hu=.2,du=60,uu=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),ni=4,la="ufo-1",fu=["oval","polygon"],Sb={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5};function yb(i){return i.kind==="oval"?"oval":"polygon"}class bb extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZones=new fb;objectSizeInput;objectDistanceInput;apparentSizeOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewTestimonyButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;timeStartLabel;timeEndLabel;loopButton;durationInput;exportButton;importFileInput;importUrlInput;importUrlButton;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=cb();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;pitchInput;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;obsEndTimeInput;witnessIdInput;witnessDirNameInput;witnessTitleInput;witnessLastNameInput;witnessFirstNamesInput;caseIdInput;descriptionInput;tagsInput;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;weatherSourceLink;weatherFields;weatherInference=new qo(ob());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;lensFlareBrightnessInput;cameraDeviceInput;labelColor;labelTransparency;labelHalo;labelShape;labelShapeTitle;labelUtcOffset;labelObjectSize;labelObjectDistance;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelElevation;labelObservationTime;labelObservationEndTime;labelWitnessId;labelWitnessDirName;labelWitnessTitle;labelWitnessLastName;labelWitnessFirstNames;labelCaseId;labelDescription;labelTags;labelWeather;labelImportFile;labelImportUrl;labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelWitnessGroup;labelCircumstancesGroup;labelCloudCover;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelLensFlareBrightness;labelCameraDevice;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorWitnessButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorLitInput;decorSightingUrlInput;decorFloorsInput;decorOccupiedFloorInput;decorWitnessSideSelect;decorWindowInputs;labelDecorSide;optionWitnessSide;labelDecor;labelDecorFieldset;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorLit;labelDecorSightingUrl;labelDecorFloors;labelDecorOccupiedFloor;labelDecorWitnessSide;labelDecorWindows;optionWitnessSideNone;optionDecorBuilding;optionDecorTree;optionDecorStreetlight;optionDecorVehicle;optionDecorWitness;recorder;isRecording=!1;messages=q0;currentAppearance={...Sb};currentSourceId=la;selectedSourceIds=new Set([la]);currentDecorId;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),uu.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;uu.has(e.key)?this.moveOrResizeSelectedShapes(e):this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>this.endDrag();constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${tf}</style>${ef}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(xc),this.sceneElement.setAttribute("show-compass",""),this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.objectSizeInput=this.shadow.getElementById("objectSize"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),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.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.contextViewTestimonyButton=this.shadow.getElementById("context-view-testimony"),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.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.loopButton=this.shadow.getElementById("loop"),this.durationInput=this.shadow.getElementById("durationSeconds"),this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),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.pitchInput=this.shadow.getElementById("pitch"),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.witnessIdInput=this.shadow.getElementById("witnessId"),this.witnessDirNameInput=this.shadow.getElementById("witnessDirName"),this.witnessTitleInput=this.shadow.getElementById("witnessTitle"),this.witnessLastNameInput=this.shadow.getElementById("witnessLastName"),this.witnessFirstNamesInput=this.shadow.getElementById("witnessFirstNames"),this.caseIdInput=this.shadow.getElementById("caseId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),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.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,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.lensFlareBrightnessInput=this.shadow.getElementById("lensFlareBrightness"),this.cameraDeviceInput=this.shadow.getElementById("cameraDevice"),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelObjectSize=this.shadow.getElementById("label-object-size"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),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.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.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),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.labelWitnessId=this.shadow.getElementById("label-witness-id"),this.labelWitnessDirName=this.shadow.getElementById("label-witness-dir-name"),this.labelWitnessTitle=this.shadow.getElementById("label-witness-title"),this.labelWitnessLastName=this.shadow.getElementById("label-witness-last-name"),this.labelWitnessFirstNames=this.shadow.getElementById("label-witness-first-names"),this.labelCaseId=this.shadow.getElementById("label-case-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelWeather=this.shadow.getElementById("label-weather"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelWitnessGroup=this.shadow.getElementById("label-witness-group"),this.labelCircumstancesGroup=this.shadow.getElementById("label-circumstances-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),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.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelLensFlareBrightness=this.shadow.getElementById("label-lens-flare-brightness"),this.labelCameraDevice=this.shadow.getElementById("label-camera-device"),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.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorWitnessButton=this.shadow.getElementById("add-decor-witness"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.decorSelect=this.shadow.getElementById("decor"),this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorWitnessSideSelect=this.shadow.getElementById("decorWitnessSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionWitnessSide={front:this.shadow.getElementById("option-witness-side-front"),behind:this.shadow.getElementById("option-witness-side-behind"),left:this.shadow.getElementById("option-witness-side-left"),right:this.shadow.getElementById("option-witness-side-right"),"front-left":this.shadow.getElementById("option-witness-side-front-left"),"front-right":this.shadow.getElementById("option-witness-side-front-right"),"behind-left":this.shadow.getElementById("option-witness-side-behind-left"),"behind-right":this.shadow.getElementById("option-witness-side-behind-right")},this.optionWitnessSideNone=this.shadow.getElementById("option-witness-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorFieldset=this.shadow.getElementById("label-decor-fieldset"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorWitnessSide=this.shadow.getElementById("label-decor-witness-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorWitness=this.shadow.getElementById("option-decor-witness"),this.ufoElement.canvasElement.addEventListener("pointerdown",t=>this.onPointerDown(t)),this.ufoElement.canvasElement.addEventListener("pointermove",t=>this.onPointerMove(t)),this.ufoElement.canvasElement.addEventListener("contextmenu",t=>this.onContextMenu(t)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),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.contextViewTestimonyButton.addEventListener("click",()=>this.viewWitnessTestimony()),this.playPauseButton.addEventListener("click",()=>{this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.loopButton.addEventListener("click",()=>{this.ufoElement.toggleLoop(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=Number(this.seekInput.value)),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),this.durationInput.addEventListener("input",()=>{this.ufoElement.durationSeconds=this.durationInput.value===""?void 0:Number(this.durationInput.value),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle());for(const t of[this.objectSizeInput,this.objectDistanceInput])t.addEventListener("input",()=>this.updatePhysicalExtent());this.addDecorWitnessButton.addEventListener("click",()=>this.addDecor("witness")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value));for(const t of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorSightingUrlInput,this.decorFloorsInput,this.decorOccupiedFloorInput])t.addEventListener("input",()=>this.updateDecor());this.decorWitnessSideSelect.addEventListener("change",()=>this.updateDecor());for(const t of ss)this.decorWindowInputs[t].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.dispatchEvent(new CustomEvent("sightingchange"))}),document.addEventListener("keydown",this.handleKeyDown);for(const t of fu)this.presetButtons[t].addEventListener("click",()=>this.setAppearance({presetId:t}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const t of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.elevationInput])t.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",t=>{t.key==="Enter"&&(t.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("focus",()=>this.sceneElement.setCompassForced(!0)),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.lensFlareBrightnessInput.addEventListener("input",()=>this.sceneElement.setAttribute("lens-flare-brightness",this.lensFlareBrightnessInput.value)),this.cameraDeviceInput.addEventListener("input",()=>this.sceneElement.setAttribute("lens-flare-intensity",this.cameraDeviceInput.value)),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>this.updateTimeZone()),this.obsTimeInput.addEventListener("input",()=>this.updateObservationTime()),this.obsEndTimeInput.addEventListener("input",()=>this.updateObservationEndTime()),this.obsTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsTimeInput)),this.obsEndTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsEndTimeInput));for(const t of[this.witnessIdInput,this.witnessDirNameInput,this.witnessTitleInput,this.witnessLastNameInput,this.witnessFirstNamesInput,this.caseIdInput])t.addEventListener("input",()=>this.updateWitnessMetadata());this.descriptionInput.addEventListener("input",()=>this.updateDescription()),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const t of this.weatherFields)t.addEventListener("input",()=>this.applyWeatherAtPlayhead());for(const t of this.soundFields)t.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.applyAppearanceAtPlayhead(),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,n){e==="src"&&n&&n!==t&&this.isConnected&&this.importFromUrl(n)}disconnectedCallback(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??la,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.syncWitnessMetadataFields(),this.refreshTimeZoneOptions(),this.utcOffsetInput.readOnly=this.ufoElement.sighting.event.timeZone!==void 0,this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership()}exportJson(){const e=this.sightingData,t=`${e.witness?.id??"sighting"}-sighting.json`,n=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=t,r.click(),URL.revokeObjectURL(s)}async importFromFile(){const e=this.importFileInput.files?.[0];if(e)try{const t=await new Promise((n,s)=>{const r=new FileReader;r.onload=()=>n(r.result),r.onerror=()=>s(r.error),r.readAsText(e)});this.sightingData=JSON.parse(t)}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}async importFromUrl(e=this.importUrlInput.value.trim()){if(e)try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);this.sightingData=await t.json()}catch{window.alert(this.messages.importError)}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const n=(e%360+360)%360;return String(n)!==t.value&&(t.value=String(n)),n}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",hb,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",db,e=>{this.weatherInference=new qo(e.create()),this.scheduleWeatherLookup()})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Ko,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,cu,()=>this.applyTerrainSources()))}sourcePicker(e,t,n){const s=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,r.appendChild(c)}r.value=this.chosenSourceId.get(e)??t[0].id;const a=document.createElement("a");a.className="source-credit",a.target="_blank",a.rel="noopener noreferrer";const o=()=>{const l=Xs(t,r.value);r.title=l.credit,a.href=l.creditUrl,a.textContent=l.credit};return o(),r.addEventListener("change",()=>{this.chosenSourceId.set(e,r.value),o(),n(Xs(t,r.value))}),s.append(r,document.createTextNode(" "),a),s}labelledPicker(e,t,n,s){const r=document.createElement("label"),a=document.createElement("span");return a.textContent=t,r.append(a,this.sourcePicker(e,n,s)),r}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:Xs(Ko,this.chosenSourceId.get("elevation")).create(),imagery:Xs(cu,this.chosenSourceId.get("imagery")).create()}),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==="")return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let n;try{n=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=n,this.refreshPlaceMatches(),n.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const n=document.createElement("option");return n.textContent=t.name,n.title=t.name,n})),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)return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<oa&&Math.abs(t-this.namedCoordinates.lng)<oa||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),vb))}async reversePlace(e,t){const n=++this.placeSearchToken;let s;try{s=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}n===this.placeSearchToken&&(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,this.updateObserver())}updateObserver(){if(this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),n=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),s=this.numberOrUndefined(this.pitchInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=Math.max(0,r-(this.groundElevationM??0)),o=this.ufoElement.sighting.event,l=this.ufoElement.sighting.witnessTrack,c=this.ufoElement.currentTime,h=this.stringOrUndefined(this.placeNameInput.value.trim());o.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:h}]:void 0,e===void 0&&t===void 0&&n===void 0&&s===0&&a===0?l.removeKeyframeAt(c):l.addKeyframe(c,{lat:e,lng:t,elevationM:a,headingDeg:n,pitchDeg:s,fovDeg:du}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.schedulePlaceReverse(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}applyEdtfTimeInput(e,t){const n=e.value.trim();if(n==="")t(void 0);else{const s=nh(n);if(!s)return;t(s)}e.setCustomValidity(""),e.classList.remove("invalid"),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&rr({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.durationSeconds=void 0)}validateEdtfTimeInput(e){const t=e.value.trim();t===""||nh(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}refreshTimeZoneOptions(){const e=document.createElement("option");e.value="",e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(t=>{const n=document.createElement("option");return n.value=t,n.textContent=t,n})),this.timeZoneSelect.value=this.ufoElement.sighting.event.timeZone??""}updateTimeZone(){const e=this.stringOrUndefined(this.timeZoneSelect.value);this.ufoElement.sighting.event.timeZone=e,this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event,t=e.timeZone&&e.time?this.timeZones.offsetHoursAt(e.timeZone,e.time):void 0;t!==void 0&&(e.utcOffsetHours=t),this.utcOffsetInput.readOnly=e.timeZone!==void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateUtcOffset(){this.ufoElement.sighting.event.utcOffsetHours=this.numberOrUndefined(this.utcOffsetInput.value),this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObservationTime(){this.applyEdtfTimeInput(this.obsTimeInput,e=>{this.ufoElement.sighting.event.time=e})}updateObservationEndTime(){this.applyEdtfTimeInput(this.obsEndTimeInput,e=>{this.ufoElement.sighting.event.endTime=e})}updateWitnessMetadata(){const e=this.ufoElement.sighting,t=this.witnessFirstNamesInput.value.split(",").map(s=>s.trim()).filter(s=>s.length>0),n={id:this.stringOrUndefined(this.witnessIdInput.value),dirName:this.stringOrUndefined(this.witnessDirNameInput.value),title:this.stringOrUndefined(this.witnessTitleInput.value),lastName:this.stringOrUndefined(this.witnessLastNameInput.value),firstNames:t.length>0?t:void 0};e.witness=Object.values(n).some(s=>s!==void 0)?n:void 0,e.caseId=this.stringOrUndefined(this.caseIdInput.value),this.ufoElement.refresh()}updateDescription(){this.ufoElement.sighting.event.description=this.stringOrUndefined(this.descriptionInput.value),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0);this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={cloudCover: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()}buildSoundKindOptions(){for(const e of xf){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(),mb)}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=vu(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 qo(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),gb))}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(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0;const n=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!n,this.weatherInferredInput.checked=n&&this.weatherFromRecords;const s=n?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s;const r=t&&e!==void 0;if(this.weatherSourceLink.hidden=!r,r){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent=`${this.messages.weatherFrom} `,this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const a=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=a===""?"":`${a} `,this.weatherSourceRow.hidden=a===""}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&&Hc(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.weatherLookupResult=void 0,this.weatherFromRecords=e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0,this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup()}syncDurationField(){if(this.shadow.activeElement!==this.durationInput){const e=rr(this.ufoElement.sighting.event);this.durationInput.value=e!==void 0?String(e/1e3):""}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("invalid",e),this.durationInput.setAttribute("aria-invalid",String(e));const t=wf(this.ufoElement.sighting.event);this.durationInput.title=t==="imprecise"?this.messages.durationImprecise:""}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;this.playPauseButton.textContent=e?"⏸":"▶",this.playPauseButton.disabled=!t;const n=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=n,this.playPauseButton.setAttribute("aria-label",n),this.loopButton.setAttribute("aria-pressed",String(this.ufoElement.autoReplayEnabled)),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}syncObservationTimeFields(){const e=this.ufoElement.sighting.event.time;this.obsTimeInput.value=e?ih(e):"",this.obsTimeInput.setCustomValidity(""),this.obsTimeInput.classList.remove("invalid")}syncObservationEndTimeFields(){const e=this.ufoElement.sighting.event.endTime;this.obsEndTimeInput.value=e?ih(e):"",this.obsEndTimeInput.setCustomValidity(""),this.obsEndTimeInput.classList.remove("invalid")}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,n=t===void 0?void 0:Math.round(t/15),s=e!==void 0&&n!==void 0&&Math.abs(e-n)>xb;this.utcOffsetInput.classList.toggle("invalid",s),this.utcOffsetInput.title=s?this.messages.utcOffsetImplausible.replace("{solar}",n>=0?`+${n}`:String(n)):""}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),_b))}isSamePlace(e,t,n){return Math.abs(e.lat-t)<oa&&Math.abs(e.lng-n)<oa}async applyGroundElevation(e,t){const n=++this.groundElevationToken,s=Xs(Ko,this.chosenSourceId.get("elevation")),r=await new Wc(s.create()).at(e,t);if(n!==this.groundElevationToken||r===void 0)return;this.groundElevationFor={lat:e,lng:t};const a=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(r),this.syncElevationField(a),this.updateObserver()}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(Ss(this.ufoElement.sighting,0)?.elevationM??0),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=""}syncWitnessMetadataFields(){const e=this.ufoElement.sighting;this.witnessIdInput.value=e.witness?.id??"",this.witnessDirNameInput.value=e.witness?.dirName??"",this.witnessTitleInput.value=e.witness?.title??"",this.witnessLastNameInput.value=e.witness?.lastName??"",this.witnessFirstNamesInput.value=e.witness?.firstNames?.join(", ")??"",this.caseIdInput.value=e.caseId??"",this.descriptionInput.value=e.event.description??"",this.tagsInput.value=e.event.tags?.join(", ")??""}syncWeatherFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=Jo(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),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(e.windDirectionDeg)),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(e.windSpeed)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=e.witnessTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),n=e.event.place?.[0],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):n?String(n.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):n?String(n.lng):""),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(t.headingDeg):""),s!==this.pitchInput&&(this.pitchInput.value=String(t?.pitchDeg??0)),s!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},this.updatePresetButtons(),!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=n.getInterpolatedShapeAt(s,this.currentSourceId),a=this.buildAppearanceShape(e??r?.bounds??this.defaultBounds(),r,t);n.addKeyframe(s,[{sourceId:this.currentSourceId,shape:a}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,n=!0){if(t&&!n)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale};const s=eh(e,this.currentAppearance);return t?{...s,angle:t.angle,title:t.title,selected:t.selected}:s}onSelectionOrTimeChanged(){this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const e=this.ufoElement.sighting.timeline.sourceIds,t=e.filter(n=>this.selectedSourceIds.has(n)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0||e.length-t<1}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const n of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.objectSizeInput,this.objectDistanceInput,this.sourceSelect,...Object.values(this.presetButtons)])n.disabled=e,n.title=t}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:yb(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=e.title??""),this.shadow.activeElement!==this.objectSizeInput&&(this.objectSizeInput.value=e.physical?String(Number(e.physical.sizeM.toFixed(2))):""),this.shadow.activeElement!==this.objectDistanceInput&&(this.objectDistanceInput.value=e.physical?String(Number(e.physical.distanceM.toFixed(2))):""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,n=e.getInterpolatedShapeAt(t,this.currentSourceId);n&&(e.addKeyframe(t,[{sourceId:this.currentSourceId,shape:{...n,title:this.stringOrUndefined(this.shapeTitleInput.value)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}updatePhysicalExtent(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,n=e.getInterpolatedShapeAt(t,this.currentSourceId);if(!n)return;const s=this.numberOrUndefined(this.objectSizeInput.value),r=this.numberOrUndefined(this.objectDistanceInput.value);if(s===void 0&&r===void 0){e.addKeyframe(t,[{sourceId:this.currentSourceId,shape:{...n,physical:void 0}}]),this.ufoElement.refresh(),this.refreshApparentSize();return}if(s===void 0||r===void 0||s<=0||r<=0){this.refreshApparentSize();return}const a={sizeM:s,distanceM:r},o=this.ufoElement.canvasElement,l=ps.widthPx(a,o.height,this.currentFovDeg()),c=n.bounds.height*(n.bounds.width===0?1:l/n.bounds.width),h={x:n.bounds.x+(n.bounds.width-l)/2,y:n.bounds.y+(n.bounds.height-c)/2,width:l,height:c},u=n.kind==="oval"?{...n,bounds:h,physical:a}:{...n,bounds:h,physical:a,points:this.scalePoints(n,h)};e.addKeyframe(t,[{sourceId:this.currentSourceId,shape:u}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const n=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(r=>({x:r.x*n,y:r.y*s}))}currentFovDeg(){return Ss(this.ufoElement.sighting,this.ufoElement.currentTime)?.fovDeg??du}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="";return}const t=this.ufoElement.canvasElement,n=ps.pxToDeg(e.bounds.width,t.height,this.currentFovDeg()),s=ps.inMoons(n);this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{deg}",n.toLocaleString(void 0,{maximumFractionDigits:n<1?2:1})).replace("{moons}",s.toLocaleString(void 0,{maximumFractionDigits:s<10?1:0}))}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&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);if(t?.title)return t.title;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline,t=new Set([...e.sourceIds,this.currentSourceId]);let n=t.size+1;for(;t.has(`ufo-${n}`);)n++;this.currentSourceId=`ufo-${n}`,this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(s=>this.selectedSourceIds.has(s));if(!(t.length===0||e.sourceIds.length-t.length<1||!(t.length===1?window.confirm(this.messages.confirmDeleteShape.replace("{name}",this.shapeLabel(t[0]))):window.confirm(this.messages.confirmDeleteShapes.replace("{count}",String(t.length)))))){for(const s of t)e.removeSource(s);this.currentSourceId=e.sourceIds[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}}offsetDefaultBounds(e){const t=this.defaultBounds(),n=24;return{...t,x:t.x+e*n,y:t.y+e*n}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=[...new Set([...e.sourceIds,this.currentSourceId])];this.sourceSelect.innerHTML="";for(const n of t){const s=document.createElement("option");s.value=n,s.textContent=this.shapeLabel(n),this.sourceSelect.appendChild(s)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){if(e.title)return e.title;const n=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${n}`}addDecor(e=this.decorKindSelect.value){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==="building"?{floors:ga}:{},windows:m2(e)};t.decor=[...t.decor,s],this.currentDecorId=s.id,this.refreshDecorList(),this.ufoElement.refresh()}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(s=>s.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??e} ${t+1}`}deleteDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.filter(t=>t.id!==this.currentDecorId),this.currentDecorId=e.decor[0]?.id,this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.decorSelect.value=e,this.syncDecorFields()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,n=this.decorWitnessSideSelect.value;e.decor=e.decor.map(s=>{if(s.id!==this.currentDecorId)return s;const r=Qs(s.kind)&&n!==""?n:void 0;return{...s,title:this.stringOrUndefined(this.decorTitleInput.value),eastM:Number(this.decorEastInput.value),northM:Number(this.decorNorthInput.value),headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),witnessSide:r,floors:s.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:s.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(s=>s.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const n={};for(const s of ss){const r=this.decorWindowInputs[s];if(r.value==="")continue;const a=fc(t.kind,s)?0:uc,o=Math.max(a,Math.min(100,Number(r.value)));n[s]=o,String(o)!==r.value&&(r.value=String(o))}return{...t,windows:n}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,n=this.decorLitInput.checked;e.decor=e.decor.map(s=>{if(s.id!==this.currentDecorId)return s;const r=[...(s.litKeyframes??[]).filter(a=>a.t!==t),{t,lit:n}].sort((a,o)=>a.t-o.t);return{...s,litKeyframes:r}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const n=document.createElement("option");n.value=t.id,n.textContent=this.decorLabel(t),this.decorSelect.appendChild(n)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const n of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorWitnessSideSelect])n.disabled=!t;this.decorTitleInput.value=e?.title??"",this.decorEastInput.value=String(e?.eastM??0),this.decorNorthInput.value=String(e?.northM??0),this.decorHeadingInput.value=String(e?.headingDeg??0),this.decorLitInput.checked=e?pc(e,this.ufoElement.currentTime):!1,this.decorSightingUrlInput.value=e?.sightingUrl??"",this.decorFloorsInput.value=String(e?.floors??ga),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorWitnessSideSelect.value=e?.witnessSide??"";for(const n of ss){const s=e?.windows?.[n];this.decorWindowInputs[n].value=s===void 0?"":String(s)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const n=e.closest("label")??e;n.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId),t=e!==void 0,n=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorLitInput,t);const s=t&&n!==void 0&&P0(n);this.setRowVisible(this.labelDecorWindows,s);const r=n!==void 0?Vc(n):[];for(const c of ss)this.decorWindowInputs[c].disabled=!t,this.decorWindowInputs[c].min=String(n!==void 0&&fc(n,c)?0:uc),this.setRowVisible(this.decorWindowInputs[c],s&&r.includes(c));const a=t&&n!==void 0&&Qs(n);this.setRowVisible(this.decorWitnessSideSelect,a);const o=n!==void 0?f2(n):[];for(const c of ss)this.optionWitnessSide[c].hidden=!o.includes(c);const l=t&&n==="building";this.setRowVisible(this.decorFloorsInput,l),this.setRowVisible(this.decorOccupiedFloorInput,l),this.decorOccupiedFloorInput.max=String(e?.floors??ga)}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=pc(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of fu)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return eh(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-ls.width/2,y:e.height/2-ls.height/2,width:ls.width,height:ls.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 Vy(this.ufoElement.sighting.timeline,new Wy(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){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=Na(navigator.languages,Su);e!=="en"&&this.applyMessages(await Xf(e))}applyMessages(e){this.currentSourceId===la&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,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.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelObjectSize.textContent=e.objectSize,this.labelObjectDistance.textContent=e.objectDistance,this.objectSizeInput.placeholder=e.objectSizePlaceholder,this.objectDistanceInput.placeholder=e.objectDistancePlaceholder,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.durationInput.placeholder=e.durationPlaceholder,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.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,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.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.obsTimeInput.title=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.obsEndTimeInput.title=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorFieldset.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorWitness.textContent=e.decorWitness,this.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewTestimonyButton.textContent=e.viewTestimony,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorWitnessButton.textContent=e.addWitness,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorWitnessSide.textContent=e.decorWitnessSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionWitnessSideNone.textContent=e.decorWitnessSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const n of ss)this.labelDecorSide[n].textContent=t[n],this.optionWitnessSide[n].textContent=t[n];this.refreshDecorList(),this.labelWitnessId.textContent=e.witnessId,this.labelWitnessDirName.textContent=e.witnessDirName,this.labelWitnessTitle.textContent=e.witnessTitle,this.labelWitnessLastName.textContent=e.witnessLastName,this.labelWitnessFirstNames.textContent=e.witnessFirstNames,this.witnessFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelCaseId.textContent=e.caseId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelWeather.textContent=e.weather,this.labelShapeGroup.textContent=e.shapeGroup,this.labelTemporalGroup.textContent=e.temporalGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelWitnessGroup.textContent=e.witnessGroup,this.labelCircumstancesGroup.textContent=e.circumstancesGroup,this.labelCloudCover.textContent=e.cloudCover,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.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;for(const[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelLensFlareBrightness.textContent=e.lensFlareBrightness,this.labelCameraDevice.textContent=e.cameraDevice,this.loopButton.title=e.autoReplay,this.loopButton.setAttribute("aria-label",e.autoReplay),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState==="playing";if(this.selectedSourceIds.size>1){const l=new Xa(this.selectedMembers()),c=$e.hitTestHandle({bounds:l.bounds(),angle:0},t);if(c==="rotate"){if(r)return;this.dragState={kind:"group-rotate",group:l,startPointer:t},this.startDragListening();return}if(c){if(r)return;this.dragState={kind:"group-resize",group:l,handle:c},this.startDragListening();return}}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId),c=l?.kind==="polygon"?$e.hitTestVertex(l,t):void 0;if(l?.kind==="polygon"&&c!==void 0){if(r)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:l,vertexIndex:c},this.startDragListening();return}const h=l&&$e.hitTestHandle(l,t);if(l&&h){if(r)return;this.beginDrag(h==="rotate"?"rotate":"resize",this.currentSourceId,l,t,h);return}}const a=n.hitTest(s,t.x,t.y);if(!a){const l=this.pickDecorAt(e);if(l!==void 0){this.selectDecor(l);return}r||this.beginCameraDrag(t);return}if(e.shiftKey?this.toggleUnitSelection(a.sourceId):this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),r)return;const o=[...this.selectedSourceIds].map(l=>({sourceId:l,original:l===a.sourceId?a.shape:n.getInterpolatedShapeAt(s,l)??a.shape}));this.dragState={kind:"move",sources:o,startPointer:t},this.startDragListening()}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(n=>({sourceId:n,shape:e.getInterpolatedShapeAt(t,n)})).filter(n=>!!n.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(n=>this.selectedSourceIds.has(n))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,n=t.groupMembers(e)??[e];if(n.every(r=>this.selectedSourceIds.has(r))){if(n.length>=this.selectedSourceIds.size)return;for(const r of n)this.selectedSourceIds.delete(r);if(!this.selectedSourceIds.has(this.currentSourceId)){const r=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((a,o)=>r.indexOf(a)-r.indexOf(o)).pop()}}else{for(const r of n)this.selectedSourceIds.add(r);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 n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.selectedSourceIds.size===1?n.getInterpolatedShapeAt(s,this.currentSourceId):void 0,o=r?.kind==="polygon"&&$e.hitTestVertex(r,t)!==void 0?{sourceId:this.currentSourceId}:n.hitTest(s,t.x,t.y);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const n=this.ufoElement.canvasElement.getBoundingClientRect();if(n.width===0||n.height===0)return;const s=(e.clientX-n.left)/n.width*2-1,r=-((e.clientY-n.top)/n.height*2-1);return this.sceneElement.pickDecorAt(s,r)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const n=this.ufoElement.sighting.timeline.sourceIds,s=n.filter(f=>this.selectedSourceIds.has(f)),r=n.length<=s.length,a=s.length>0&&n.slice(n.length-s.length).every(f=>this.selectedSourceIds.has(f)),o=s.length>0&&n.slice(0,s.length).every(f=>this.selectedSourceIds.has(f));this.contextBringToFrontButton.disabled=r||a,this.contextSendToBackButton.disabled=r||o,this.contextBringToFrontButton.title=r?this.messages.onlyOneShape:a?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=r?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title=this.contextDeleteButton.disabled?this.messages.onlyOneShape:"";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const u=h&&this.contextMenuPoint?$e.hitTestVertex(c,this.contextMenuPoint):void 0,d=h&&c.points.length<=xu;this.contextDeleteVertexButton.disabled=!h||u===void 0||d,this.contextDeleteVertexButton.title=h?d?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,n){this.contextMenuDecorId=n.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewTestimonyButton.disabled=!n.sightingUrl,this.contextViewTestimonyButton.title=n.sightingUrl?"":this.messages.noWitnessRecording,this.refreshContextMasksSubmenu(n),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";for(const t of this.ufoElement.sighting.timeline.sourceIds){const n=document.createElement("label"),s=document.createElement("input");s.type="checkbox",s.checked=e.occludesSourceIds?.includes(t)??!1,s.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,t,s.checked)),n.appendChild(s),n.appendChild(document.createTextNode(this.shapeLabel(t))),this.contextMasksSubmenu.appendChild(n)}}updateDecorOccludesShape(e,t,n){const s=this.ufoElement.sighting;s.decor=s.decor.map(r=>{if(r.id!==e)return r;const a=n?[...new Set([...r.occludesSourceIds??[],t])]:(r.occludesSourceIds??[]).filter(o=>o!==t);return{...r,occludesSourceIds:a.length>0?a:void 0}}),this.ufoElement.refresh()}viewWitnessTestimony(){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,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const s=$e.insertVertexNear(n,e);this.ufoElement.sighting.timeline.addKeyframe(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const s=$e.hitTestVertex(n,e);if(s===void 0)return;const r=$e.deleteVertex(n,s);this.ufoElement.sighting.timeline.addKeyframe(t,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)).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,n,s,r){this.dragState={kind:e,sourceId:t,original:n,handle:r,startPointer:s},this.startDragListening()}beginCameraDrag(e){const t=this.isWitnessInsideDecor();this.cameraDragState={startPointer:e,startHeadingDeg:t?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:t?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:t},t||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isWitnessInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.witnessSide!==void 0&&Qs(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(n=>n.witnessSide!==void 0&&Qs(n.kind)),t=e?`${e.id}:${e.witnessSide}`: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.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:s,startPointer:r}=this.dragState,a=t.x-r.x,o=t.y-r.y,l=s.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+a,y:h.bounds.y+o}}}));this.ufoElement.sighting.timeline.addKeyframe(n,l)}else if(this.dragState.kind==="group-resize"){const{group:s,handle:r}=this.dragState;this.ufoElement.sighting.timeline.addKeyframe(n,s.resize(r,t))}else if(this.dragState.kind==="group-rotate"){const{group:s,startPointer:r}=this.dragState;this.ufoElement.sighting.timeline.addKeyframe(n,s.rotate(t,r))}else if(this.dragState.kind==="vertex"){const{sourceId:s,original:r,vertexIndex:a}=this.dragState,o=$e.moveVertex(r,a,t);this.ufoElement.sighting.timeline.addKeyframe(n,[{sourceId:s,shape:o}])}else{const{kind:s,sourceId:r,original:a,handle:o}=this.dragState,l=s==="resize"?$e.resizeShape(a,o,t):$e.rotateShape(a,t);this.ufoElement.sighting.timeline.addKeyframe(n,[{sourceId:r,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:n,startHeadingDeg:s,startPitchDeg:r,insideDecor:a}=this.cameraDragState,o=s+(t.x-n.x)*hu,l=Math.max(-90,Math.min(90,r-(t.y-n.y)*hu));if(a){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(o),this.pitchInput.value=String(l),this.updateObserver()}endDrag(){!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}nudgeBounds(e,t){const n={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":n.width=Math.max(ai,n.width-ni);break;case"ArrowRight":n.width+=ni;break;case"ArrowUp":n.height=Math.max(ai,n.height-ni);break;case"ArrowDown":n.height+=ni;break}n.x-=(n.width-e.width)/2,n.y-=(n.height-e.height)/2}else switch(t.key){case"ArrowLeft":n.x-=ni;break;case"ArrowRight":n.x+=ni;break;case"ArrowUp":n.y-=ni;break;case"ArrowDown":n.y+=ni;break}return n}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedMembers();if(s.length!==0){if(e.preventDefault(),s.length===1){const{sourceId:r,shape:a}=s[0];t.addKeyframe(n,[{sourceId:r,shape:{...a,bounds:this.nudgeBounds(a.bounds,e)}}])}else{const r=new Xa(s),a=this.nudgeBounds(r.bounds(),e);t.addKeyframe(n,r.scaleTo(a))}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 n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(r)if(this.selectedSourceIds.size>1){const a=$e.hitTestHandle({bounds:new Xa(this.selectedMembers()).bounds(),angle:0},t);if(a)return this.cursorForHandle(a,0)}else{const a=n.getInterpolatedShapeAt(s,this.currentSourceId);if(a?.kind==="polygon"&&$e.hitTestVertex(a,t)!==void 0)return"vertex";const o=a&&$e.hitTestHandle(a,t);if(a&&o)return this.cursorForHandle(o,a.angle)}return n.hitTest(s,t.x,t.y)?r?"move":"select":this.pickDecorAt(e)!==void 0?"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${$e.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,n=t.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top;this.recorder?.onPointerMove(s,r),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(mu(this.buildPrototype({x:0,y:0,width:ls.width,height:ls.height}),s,r))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(!(n.width===0||n.height===0))return{x:(e.clientX-n.left)/n.width*t.width,y:(e.clientY-n.top)/n.height*t.height}}}const pu="rr0-ufo-recorder";function Mb(){Ua(),customElements.get(pu)||customElements.define(pu,bb)}Mb();
|
|
5758
|
+
`;let ra;function wy(){if(ra)return ra;const i=128,e=document.createElement("canvas");e.width=i,e.height=i;const t=e.getContext("2d"),n=t.createRadialGradient(i/2,i/2,0,i/2,i/2,i/2);return n.addColorStop(0,"rgba(255,255,255,1)"),n.addColorStop(.4,"rgba(255,255,255,0.35)"),n.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=n,t.fillRect(0,0,i,i),ra=new Wn(e),ra}function Ty(i){const t=document.createElement("canvas");t.width=128,t.height=128;const n=t.getContext("2d"),s=128/2-2,r=128/2,a=128/2,o="#2e2b26",l="#f4f1e2";n.fillStyle=o,n.beginPath(),n.arc(r,a,s,0,Math.PI*2),n.fill();const c=V0(i.illuminatedFraction,0,1),h=i.phaseFraction<.5,u=s*Math.abs(1-2*c),d=c<.5;return n.save(),n.beginPath(),n.arc(r,a,s,0,Math.PI*2),n.clip(),n.fillStyle=l,n.beginPath(),h?(n.arc(r,a,s,-Math.PI/2,Math.PI/2,!1),n.ellipse(r,a,u,s,0,Math.PI/2,-Math.PI/2,d)):(n.arc(r,a,s,Math.PI/2,-Math.PI/2,!1),n.ellipse(r,a,u,s,0,-Math.PI/2,Math.PI/2,d)),n.fill(),n.restore(),new Wn(t)}function Ay(i){const e=document.createElement("canvas");e.width=128,e.height=128;const t=e.getContext("2d");return t.fillStyle="rgba(0, 0, 0, 0.55)",t.beginPath(),t.arc(64,64,60,0,Math.PI*2),t.fill(),t.fillStyle="#ffffff",t.font="bold 52px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(i,64,68),new Wn(e)}function Wo(i){let e=i;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}const iu=new Map;function Iy(i){const e=i.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),t=e,n=t*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(i,0*n,t),dec:new Float32Array(i,1*n,t),mag:new Float32Array(i,2*n,t),ci:new Float32Array(i,3*n,t)}}function Ry(i){let e=iu.get(i);return e||(e=fetch(i).then(t=>t.arrayBuffer()).then(Iy),iu.set(i,e)),e}const Cy=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,Dy=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,Py=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,Ly=20,Ny=1;class Uy{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}this.context.state==="suspended"&&this.context.resume()}setAmbient(e,t,n){if(this.requested={type:e,intensity:t,windSpeed:n},!this.context)return;this.paused&&(e="none",t=0,n=0);const s=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=s==="hail"?Math.min(1,t*1.3+.2):s==="rain"?t:0,s!==this.ambientKey){this.ambientKey=s;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,s!=="none"&&this.startLoop(Cy,this.ambientVolume).then(o=>this.applyIfCurrent(o,a,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(n/Ly,1);const r=n>Ny;if(r!==this.windActive){this.windActive=r;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,r&&this.startLoop(Dy,this.windVolume).then(o=>this.applyIfCurrent(o,a,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:n,windSpeed:s}=this.requested;this.setAmbient(t,n,s)}playThunder(){!this.context||this.paused||this.playOneShot(Py,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.buffers.clear()}applyIfCurrent(e,t,n,s){if(t!==n()){e?.source.stop();return}s(e)}async startLoop(e,t){const n=this.context;if(n)try{const s=await this.getBuffer(e),r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();return a.gain.value=t,r.connect(a).connect(n.destination),r.start(),{source:r,gain:a}}catch(s){console.warn("Weather ambient sound failed to load, staying silent:",s);return}}async playOneShot(e,t){const n=this.context;if(n)try{const s=await this.getBuffer(e),r=n.createBufferSource();r.buffer=s;const a=n.createGain();a.gain.value=t,r.connect(a).connect(n.destination),r.start()}catch(s){console.warn("Thunder sound failed to load:",s)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let n=this.buffers.get(e);return n||(n=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,n)),n}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}Ua();const Fy={sun:{en:"Sun",fr:"Soleil"},moon:{en:"Moon",fr:"Lune"},Venus:{en:"Venus",fr:"Vénus"},Mars:{en:"Mars",fr:"Mars"},Jupiter:{en:"Jupiter",fr:"Jupiter"},Saturn:{en:"Saturn",fr:"Saturne"}},Oy=["en","fr"],By={building:{en:"Building",fr:"Bâtiment"},tree:{en:"Tree",fr:"Arbre"},streetlight:{en:"Streetlight",fr:"Lampadaire"},vehicle:{en:"Vehicle",fr:"Véhicule"},witness:{en:"Witness",fr:"Témoin"}},ky=new URL(""+new URL("stars-mag7.5-DDr9QasD.bin",import.meta.url).href,import.meta.url).href,zy={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Xo={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Gy extends HTMLElement{static get observedAttributes(){return["src","star-catalog-src","show-compass","lens-flare-intensity","lens-flare-brightness"]}shadow;stageElement;frameElement;sceneCanvas;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;lastTimeMs=0;starCatalog;weatherAudio=new Uy;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(n.width===0||n.height===0)return;const s=(e.clientX-n.left)/n.width*t.width,r=(e.clientY-n.top)/n.height*t.height;if(this.ufoElement.hasVisibleShapeAt(s,r)){this.hoverTooltip.hidden=!0;return}const a=(e.clientX-n.left)/n.width*2-1,o=-((e.clientY-n.top)/n.height*2-1),l=Na(navigator.languages,Oy),c=this.sceneRenderer.pickBodyAt(a,o);if(c){this.showHoverTooltip(e,Fy[c]?.[l]??c);return}const h=this.sceneRenderer.pickDecorAt(a,o),u=h?this.ufoElement.sighting.decor.find(d=>d.id===h):void 0;if(u){this.showHoverTooltip(e,u.title||By[u.kind][l]);return}this.hoverTooltip.hidden=!0};showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.hoverTooltip.style.left=`${e.clientX-n.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-n.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash=()=>{clearTimeout(this.thunderTimeoutId);const e=(.5+Math.random()*3.5)*1e3;this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),e)};handleFirstInteraction=()=>{this.weatherAudio.resume(),this.setWeather(Jo(this.ufoElement.sighting,this.lastTimeMs))};handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.updateUfoOcclusion(this.lastTimeMs)};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e),this.weatherAudio.setPaused(!e),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${$f}</style>${Kf}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new gy(this.sceneCanvas,void 0,this.handleLightningFlash),this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(jo),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave),this.ufoElement.canvasElement.addEventListener("pointerdown",this.handleFirstInteraction,{once:!0})}connectedCallback(){this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),document.addEventListener("fullscreenchange",this.handleFullscreenChange);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose()}attributeChangedCallback(e,t,n){if(e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n),e==="star-catalog-src"&&n!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&n!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="lens-flare-intensity"&&n!==t){const s=n===null?NaN:parseFloat(n);this.sceneRenderer.setLensFlareArtifactIntensity(Number.isFinite(s)?s:0)}if(e==="lens-flare-brightness"&&n!==t){const s=n===null?NaN:parseFloat(n);this.sceneRenderer.setDazzleIntensity(Number.isFinite(s)?s:1)}}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity,e.windSpeed)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume()}async loadFromSrc(e){const t=await fetch(e);this.sightingData=await t.json()}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.lastTimeMs=0,this.updateAstronomy(0)}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=n,this.sceneRenderer.resize(t,n)}async loadStars(){const e=this.getAttribute("star-catalog-src")??ky;this.starCatalog=await Ry(e),this.updateAstronomy(this.lastTimeMs)}updateAstronomy(e){const t=this.ufoElement.sighting;this.setWeather(Jo(t,e)),this.sceneRenderer.setDecor(t.decor);const n=Ss(t,e);this.sceneRenderer.setObserverPose(n??Xo),this.sceneRenderer.updateDecorAnchoring(Ss(t,0),n),this.sceneRenderer.updateDecorLitState(e),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng);const s=n?.lat??Xo.lat,r=n?.lng??Xo.lng,a=Hc(t.event.time??{},r,t.event.utcOffsetHours);if(!a){this.sceneRenderer.setAstronomy(zy);return}const o=new Date(a.getTime()+e),l={lat:s,lng:r,elevationM:n?.elevationM??0},c={...Do("Sun",o,l),magnitude:Po("Sun",o)},h={...Do("Moon",o,l),phase:CS(o),magnitude:Po("Moon",o)},u=IS.map(d=>({body:d,position:Do(d,o,l),magnitude:Po(d,o)}));this.sceneRenderer.setAstronomy({sun:c,moon:h,planets:u,stars:this.starCatalog?{catalog:this.starCatalog,date:o,observer:l}:void 0})}updateUfoOcclusion(e){const t=this.ufoElement.sighting.timeline,n=this.ufoElement.canvasElement,s=new Set;for(const r of t.sourceIds){const a=t.getInterpolatedShapeAt(e,r);if(!a)continue;const o=(a.bounds.x+a.bounds.width/2)/n.width*2-1,l=-((a.bounds.y+a.bounds.height/2)/n.height*2-1),c={declared:a.behindCloud,distanceM:a.physical?.distanceM};this.sceneRenderer.isScreenPointOccluded(o,l,r,c)&&s.add(r)}this.ufoElement.setOccludedSourceIds(s)}}const xc="rr0-scene";function Hy(){Ua(),customElements.get(xc)||customElements.define(xc,Gy)}class Vy{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(n=>this.recordSample(n))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=mu(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class Wy{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const n=performance.now()-this.startTime;n-this.lastTick>=this.intervalMs&&(this.lastTick=n,e(n)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}const aa=36e5,su=25;class qo{constructor(e){this.provider=e}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{origin:n,start:s}=t,r=rr(e.event)??0,a=this.sampleTimings(e,s,r);let o;try{o=await this.provider.getWeather({points:a.map(l=>this.pointAt(e,l,n))})}catch{return{status:"failed",at:s}}return o?{status:"inferred",at:s,source:o.source,keyframes:o.samples.map((l,c)=>({t:a[c].t,weather:l.weather}))}:{status:"unavailable",at:s}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const n of t.keyframes)e.weatherTrack.addKeyframe(n.t,n.weather);e.weatherSource=t.source}}sampleTimes(e,t){const n=[e],s=e.getTime()+t;let r=Math.floor(e.getTime()/aa)*aa+aa;for(;r<=s&&n.length<su;)n.push(new Date(r)),r+=aa;return t>0&&n[n.length-1].getTime()!==s&&n.length<su&&n.push(new Date(s)),n}sampleTimings(e,t,n){const s=e.timeline.duration>0?e.timeline.duration:n;return n<=0||s<=0?[{time:t,t:0}]:this.sampleTimes(t,n).map(r=>{const a=(r.getTime()-t.getTime())/n;return{time:r,t:Math.round(s*Math.max(0,Math.min(1,a)))}})}canInfer(e){return this.questionOf(e)!==void 0}questionOf(e){const t=this.originOf(e);if(!t)return;const n=e.event.time;if(n?.year===void 0||n.month===void 0||n.day===void 0)return;const s=Hc(n,t.lng,e.event.utcOffsetHours);return s?{origin:t,start:s}:void 0}originOf(e){const t=Ss(e,0),n=e.event.place?.[0],s=t?.lat??n?.lat,r=t?.lng??n?.lng;return s===void 0||r===void 0?void 0:{lat:s,lng:r}}pointAt(e,t,n){const s=Ss(e,t.t);return{lat:s?.lat??n.lat,lng:s?.lng??n.lng,time:t.time}}}const Xy=Date.UTC(1940,0,1),ru=36e5,au=.25,qy=.7,Yy=.45,Ky=.1,$y=2,Zy=.3,Jy=.2,Qy=8,Yo=.125,jy=.05,eb=125,tb=100,nb=2500,ou=3500,lu=8e3,ib=95,sb=99,rb=[96,99],ab=["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"];class W0{fetchImpl;baseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive"}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(f=>f.time.getTime()),n=Math.min(...t);if(n<Xy)return;const s=new Map;for(const f of e.points){const g=this.cellKey(f);s.has(g)||s.set(g,{lat:f.lat,lng:f.lng,index:s.size})}const r=this.requestUrl([...s.values()],new Date(n),new Date(Math.max(...t))),a=this.cache.get(r);if(a)return a;const o=await this.fetchImpl(r);if(!o.ok)throw new Error(`Open-Meteo HTTP ${o.status}`);const l=await o.json(),c=Array.isArray(l)?l:[l];if(c.length<s.size||c.some(f=>f.error||!f.hourly))return;const h={id:"era5",name:"ERA5 (Open-Meteo)",url:r},u=e.points.map(f=>this.sampleAt(c[s.get(this.cellKey(f)).index].hourly,f.time));if(u.some(f=>f===void 0))return;const d={samples:u,source:h};return this.cache.set(r,d),d}cellKey(e){return`${Math.round(e.lat/au)},${Math.round(e.lng/au)}`}requestUrl(e,t,n){const s=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(n),hourly:ab.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${this.baseUrl}?${s}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const n=this.recordAt(e,t);return n&&{time:t,weather:this.toWeather(n)}}recordAt(e,t){const n=e.time.map(o=>Date.parse(`${o}Z`)),s=t.getTime();if(n.length===0||s<n[0]-ru||s>n[n.length-1]+ru)return;if(s<=n[0])return this.recordFrom(e,0);if(s>=n[n.length-1])return this.recordFrom(e,n.length-1);let r=0;for(;r+1<n.length&&n[r+1]<=s;)r++;const a=n[r+1]-n[r];return this.blendRecords(this.recordFrom(e,r),this.recordFrom(e,r+1),a>0?(s-n[r])/a:0)}recordFrom(e,t){const n={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(n).some(s=>s===void 0||Number.isNaN(s))?void 0:n}blendRecords(e,t,n){if(!e||!t)return e??t;const s=(a,o)=>a+(o-a)*n,r=((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:n<.5?e.weatherCode:t.weatherCode,windSpeedMs:s(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+r*n)%360+360)%360,temperatureC:s(e.temperatureC,t.temperatureC),dewPointC:s(e.dewPointC,t.dewPointC)}}toWeather(e){const t=e.weatherCode>=ib&&e.weatherCode<=sb,n=this.precipitationTypeFrom(e);return{cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),precipitationType:n,precipitationIntensity:n==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/Qy),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":rb.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const n=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(n<=0)return 0;const s=(qy*e.cloudCoverLow+Yy*e.cloudCoverMid+Ky*e.cloudCoverHigh)/n,r=Math.min(1,e.precipitationMm/$y);return this.clamp(s+Zy*r+(t?Jy:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<jy)return;const t=this.clamp(eb*(e.temperatureC-e.dewPointC),tb,nb);if(e.cloudCoverLow>=Yo)return Math.round(t);if(e.cloudCoverMid>=Yo)return ou;if(e.cloudCoverHigh>=Yo)return lu;const n=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(n<=0))return n===e.cloudCoverLow?Math.round(t):n===e.cloudCoverMid?ou:lu}clamp(e,t,n){return Math.max(t,Math.min(n,e))}}function ob(){return new W0}const lb=5;class X0{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,n={}){const s=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});n.language&&s.set("accept-language",n.language);const r=`${this.reverseUrl}?${s}`,a=this.cache.get(r);if(a)return a[0];const o=await this.fetchImpl(r,{signal:n.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const l=await o.json(),c=l.error?void 0:this.toMatch(l);return this.cache.set(r,c?[c]:[]),c}async search(e,t={}){const n=e.trim();if(n==="")return[];const s=this.requestUrl(n,t),r=this.cache.get(s);if(r)return r;const a=await this.fetchImpl(s,{signal:t.signal});if(!a.ok)throw new Error(`Nominatim HTTP ${a.status}`);const o=await a.json(),l=(Array.isArray(o)?o:[]).map(c=>this.toMatch(c)).filter(c=>c!==void 0);return this.cache.set(s,l),l}requestUrl(e,t){const n=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??lb)});return t.language&&n.set("accept-language",t.language),`${this.baseUrl}?${n}`}toMatch(e){const t=e.display_name??e.name,n=this.coordinate(e.lat),s=this.coordinate(e.lon);return t&&n!==void 0&&s!==void 0?{name:t,lat:n,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 cb(){return new X0}const hb=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new X0}],db=[{id:"era5",name:"ERA5 (Open-Meteo)",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new W0}];class ub{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return{source:await C0(e,t,s=>this.tileUrlTemplate.replace("{z}",String(s.z)).replace("{y}",String(s.y)).replace("{x}",String(s.x)),this.fetchImpl),width:t.width,height:t.height}}}const Ko=[{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new R0}],cu=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:()=>new D0},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:()=>new ub}];class Wc{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const n=Wc.SPAN_DEG;try{const r=(await this.provider.getElevationGrid({south:e-n,north:e+n,west:t-n,east:t+n},{width:2,height:2})).heights[0];return Number.isFinite(r)?r:void 0}catch{return}}}class fb{available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const n=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(n));if(s!==void 0)return this.zoneOffsetHours(e,new Date(n-s*36e5))??s}zoneOffsetHours(e,t){let n;try{n=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).formatToParts(t).find(r=>r.type==="timeZoneName")?.value??""}catch{return}const s=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(n);if(s)return s[1]?(s[1]==="-"?-1:1)*(Number(s[2])+Number(s[3])/60):0}}function Xs(i,e){return i.find(t=>t.id===e)??i[0]}const q0={oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",color:"Color",transparency:"Transparency",halo:"Halo",shape:"Shape",shapeTitle:"Name",objectSize:"Real size",objectDistance:"Distance",apparentSize:"i.e. {deg}° — {moons}× the Moon",utcOffset:"Time zone",utcOffsetPlaceholder:"from longitude",objectSizePlaceholder:"reported width",objectDistancePlaceholder:"reported distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",autoReplay:"Auto-replay",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",confirmDeleteShape:"Delete {name}? This can't be undone.",confirmDeleteShapes:"Delete {count} shapes? This can't be undone.",onlyOneShape:"There is only one shape",alreadyAtFront:"This shape is already at the front",alreadyAtBack:"This shape is already at the back",needTwoShapesToGroup:"Select at least two shapes to group them",notGrouped:"This shape isn't part of a group",multipleShapesSelected:"Multiple shapes selected — select just one to edit this",cloudBase:"Cloud base",elevation:"Altitude",samplingRate:"Sampling rate",duration:"Duration",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Export JSON",importFile:"Load JSON file",importUrl:"Or load from URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Load",importError:"Couldn't load that recording — check the file or URL and try again.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",placeName:"Place",placeNamePlaceholder:"Valensole, France",searchPlace:"Locate",placeMatch:"Matches",placeSearching:"Looking up the place…",placeMatchFound:"place found",placeMatchesFound:"places found",placeNotFound:"No place by that name",placeSearchFailed:"Place search temporarily unavailable",utcOffsetImplausible:"This time zone doesn't match the longitude entered, whose own solar time is UTC{solar} — yet the scene and the weather record both obey what is declared here. Clear the field to derive it from the longitude.",timeZoneManual:"offset entered",altitudeAboveSeaLevel:"The witness's altitude above sea level — the ground at the location entered sets its floor: a witness in the Alps is not at 0 m.",groundAt:"ground at {m} m",latitude:"Latitude",longitude:"Longitude",heading:"Heading",headingPlaceholder:"unknown",pitch:"Tilt",observationTime:"Observation start",observationEndTime:"Observation end",edtfInvalid:"Not a valid EDTF date/time (e.g. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"YYYY-MM-DDThh:mm[?~%] or hh:mm",observationTimeHint:"EDTF — e.g. 1965-07-01T05:00, 2025-06? (uncertain), 2025~ (approximate), or just 05:00 if the date isn't known",observationEndTimeHint:"EDTF — e.g. 1965-07-01T05:10, 2025-06? (uncertain), 2025~ (approximate), or just 05:10 if the date isn't known",presetsGroupLabel:"UFO shape",witnessId:"Witness ID",witnessDirName:"Witness dir name",witnessTitle:"Witness title",witnessLastName:"Witness last name",witnessFirstNames:"Witness first names",caseId:"Case ID",description:"Description",tags:"Tags",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Shape",soundGroup:"Sound",temporalGroup:"Date and time",locationGroup:"Location",observationGroup:"Observation",witnessGroup:"Witness",circumstancesGroup:"Circumstances",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't testimony: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the witness reported, which then override the record.",weatherLookingUp:"Looking up the record…",weatherNeedsDateAndPlace:"A full date and a place are needed to look up the record",weatherNoRecord:"No record for this date and place",weatherLookupFailed:"Weather records temporarily unreachable",cloudCover:"Cloud cover",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",soundSrcPlaceholder:"URL of a real recording",lensFlareBrightness:"Light intensity",cameraDevice:"Camera/video device",decor:"Decor",decorBuilding:"Building",decorTree:"Tree",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorWitness:"Other witness",addDecor:"Add",deleteDecor:"Delete decor",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorLit:"Lit",decorTitle:"Name",decorSightingUrl:"Witness's own recording URL",viewTestimony:"View testimony",noWitnessRecording:"No recording URL set for this witness",masks:"Masks",addWitness:"Add witness",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorWitnessSide:"Witness location",decorWitnessSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},pb=Object.freeze(Object.defineProperty({__proto__:null,ufoRecorderMessages_en:q0},Symbol.toStringTag,{value:"Module"}));Ua();Hy();const ls={width:48,height:28},mb=2500,gb=600,vb=900,oa=2e-4,_b=900,xb=3,hu=.2,du=60,uu=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),ni=4,la="ufo-1",fu=["oval","polygon"],Sb={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5};function yb(i){return i.kind==="oval"?"oval":"polygon"}class bb extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZones=new fb;objectSizeInput;objectDistanceInput;apparentSizeOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewTestimonyButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;timeStartLabel;timeEndLabel;loopButton;durationInput;exportButton;importFileInput;importUrlInput;importUrlButton;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=cb();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;pitchInput;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;obsEndTimeInput;witnessIdInput;witnessDirNameInput;witnessTitleInput;witnessLastNameInput;witnessFirstNamesInput;caseIdInput;descriptionInput;tagsInput;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;weatherSourceLink;weatherFields;weatherInference=new qo(ob());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;lensFlareBrightnessInput;cameraDeviceInput;labelColor;labelTransparency;labelHalo;labelShape;labelShapeTitle;labelUtcOffset;labelObjectSize;labelObjectDistance;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelElevation;labelObservationTime;labelObservationEndTime;labelWitnessId;labelWitnessDirName;labelWitnessTitle;labelWitnessLastName;labelWitnessFirstNames;labelCaseId;labelDescription;labelTags;labelWeather;labelImportFile;labelImportUrl;labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelWitnessGroup;labelCircumstancesGroup;labelCloudCover;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelLensFlareBrightness;labelCameraDevice;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorWitnessButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorLitInput;decorSightingUrlInput;decorFloorsInput;decorOccupiedFloorInput;decorWitnessSideSelect;decorWindowInputs;labelDecorSide;optionWitnessSide;labelDecor;labelDecorFieldset;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorLit;labelDecorSightingUrl;labelDecorFloors;labelDecorOccupiedFloor;labelDecorWitnessSide;labelDecorWindows;optionWitnessSideNone;optionDecorBuilding;optionDecorTree;optionDecorStreetlight;optionDecorVehicle;optionDecorWitness;recorder;isRecording=!1;messages=q0;currentAppearance={...Sb};currentSourceId=la;selectedSourceIds=new Set([la]);currentDecorId;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),uu.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;uu.has(e.key)?this.moveOrResizeSelectedShapes(e):this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>this.endDrag();constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${tf}</style>${ef}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(xc),this.sceneElement.setAttribute("show-compass",""),this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.objectSizeInput=this.shadow.getElementById("objectSize"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),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.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.contextViewTestimonyButton=this.shadow.getElementById("context-view-testimony"),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.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.loopButton=this.shadow.getElementById("loop"),this.durationInput=this.shadow.getElementById("durationSeconds"),this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),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.pitchInput=this.shadow.getElementById("pitch"),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.witnessIdInput=this.shadow.getElementById("witnessId"),this.witnessDirNameInput=this.shadow.getElementById("witnessDirName"),this.witnessTitleInput=this.shadow.getElementById("witnessTitle"),this.witnessLastNameInput=this.shadow.getElementById("witnessLastName"),this.witnessFirstNamesInput=this.shadow.getElementById("witnessFirstNames"),this.caseIdInput=this.shadow.getElementById("caseId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),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.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,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.lensFlareBrightnessInput=this.shadow.getElementById("lensFlareBrightness"),this.cameraDeviceInput=this.shadow.getElementById("cameraDevice"),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelObjectSize=this.shadow.getElementById("label-object-size"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),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.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.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),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.labelWitnessId=this.shadow.getElementById("label-witness-id"),this.labelWitnessDirName=this.shadow.getElementById("label-witness-dir-name"),this.labelWitnessTitle=this.shadow.getElementById("label-witness-title"),this.labelWitnessLastName=this.shadow.getElementById("label-witness-last-name"),this.labelWitnessFirstNames=this.shadow.getElementById("label-witness-first-names"),this.labelCaseId=this.shadow.getElementById("label-case-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelWeather=this.shadow.getElementById("label-weather"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelWitnessGroup=this.shadow.getElementById("label-witness-group"),this.labelCircumstancesGroup=this.shadow.getElementById("label-circumstances-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),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.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelLensFlareBrightness=this.shadow.getElementById("label-lens-flare-brightness"),this.labelCameraDevice=this.shadow.getElementById("label-camera-device"),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.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorWitnessButton=this.shadow.getElementById("add-decor-witness"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.decorSelect=this.shadow.getElementById("decor"),this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorWitnessSideSelect=this.shadow.getElementById("decorWitnessSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionWitnessSide={front:this.shadow.getElementById("option-witness-side-front"),behind:this.shadow.getElementById("option-witness-side-behind"),left:this.shadow.getElementById("option-witness-side-left"),right:this.shadow.getElementById("option-witness-side-right"),"front-left":this.shadow.getElementById("option-witness-side-front-left"),"front-right":this.shadow.getElementById("option-witness-side-front-right"),"behind-left":this.shadow.getElementById("option-witness-side-behind-left"),"behind-right":this.shadow.getElementById("option-witness-side-behind-right")},this.optionWitnessSideNone=this.shadow.getElementById("option-witness-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorFieldset=this.shadow.getElementById("label-decor-fieldset"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorWitnessSide=this.shadow.getElementById("label-decor-witness-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorWitness=this.shadow.getElementById("option-decor-witness"),this.ufoElement.canvasElement.addEventListener("pointerdown",t=>this.onPointerDown(t)),this.ufoElement.canvasElement.addEventListener("pointermove",t=>this.onPointerMove(t)),this.ufoElement.canvasElement.addEventListener("contextmenu",t=>this.onContextMenu(t)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),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.contextViewTestimonyButton.addEventListener("click",()=>this.viewWitnessTestimony()),this.playPauseButton.addEventListener("click",()=>{this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.loopButton.addEventListener("click",()=>{this.ufoElement.toggleLoop(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=Number(this.seekInput.value)),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),this.durationInput.addEventListener("input",()=>{this.ufoElement.durationSeconds=this.durationInput.value===""?void 0:Number(this.durationInput.value),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle());for(const t of[this.objectSizeInput,this.objectDistanceInput])t.addEventListener("input",()=>this.updatePhysicalExtent());this.addDecorWitnessButton.addEventListener("click",()=>this.addDecor("witness")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value));for(const t of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorSightingUrlInput,this.decorFloorsInput,this.decorOccupiedFloorInput])t.addEventListener("input",()=>this.updateDecor());this.decorWitnessSideSelect.addEventListener("change",()=>this.updateDecor());for(const t of ss)this.decorWindowInputs[t].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.dispatchEvent(new CustomEvent("sightingchange"))}),document.addEventListener("keydown",this.handleKeyDown);for(const t of fu)this.presetButtons[t].addEventListener("click",()=>this.setAppearance({presetId:t}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const t of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.elevationInput])t.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",t=>{t.key==="Enter"&&(t.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("focus",()=>this.sceneElement.setCompassForced(!0)),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.lensFlareBrightnessInput.addEventListener("input",()=>this.sceneElement.setAttribute("lens-flare-brightness",this.lensFlareBrightnessInput.value)),this.cameraDeviceInput.addEventListener("input",()=>this.sceneElement.setAttribute("lens-flare-intensity",this.cameraDeviceInput.value)),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>this.updateTimeZone()),this.obsTimeInput.addEventListener("input",()=>this.updateObservationTime()),this.obsEndTimeInput.addEventListener("input",()=>this.updateObservationEndTime()),this.obsTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsTimeInput)),this.obsEndTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsEndTimeInput));for(const t of[this.witnessIdInput,this.witnessDirNameInput,this.witnessTitleInput,this.witnessLastNameInput,this.witnessFirstNamesInput,this.caseIdInput])t.addEventListener("input",()=>this.updateWitnessMetadata());this.descriptionInput.addEventListener("input",()=>this.updateDescription()),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const t of this.weatherFields)t.addEventListener("input",()=>this.applyWeatherAtPlayhead());for(const t of this.soundFields)t.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.applyAppearanceAtPlayhead(),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,n){e==="src"&&n&&n!==t&&this.isConnected&&this.importFromUrl(n)}disconnectedCallback(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??la,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.syncWitnessMetadataFields(),this.refreshTimeZoneOptions(),this.utcOffsetInput.readOnly=this.ufoElement.sighting.event.timeZone!==void 0,this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership()}exportJson(){const e=this.sightingData,t=`${e.witness?.id??"sighting"}-sighting.json`,n=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=t,r.click(),URL.revokeObjectURL(s)}async importFromFile(){const e=this.importFileInput.files?.[0];if(e)try{const t=await new Promise((n,s)=>{const r=new FileReader;r.onload=()=>n(r.result),r.onerror=()=>s(r.error),r.readAsText(e)});this.sightingData=JSON.parse(t)}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}async importFromUrl(e=this.importUrlInput.value.trim()){if(e)try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);this.sightingData=await t.json()}catch{window.alert(this.messages.importError)}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const n=(e%360+360)%360;return String(n)!==t.value&&(t.value=String(n)),n}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",hb,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",db,e=>{this.weatherInference=new qo(e.create()),this.scheduleWeatherLookup()})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Ko,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,cu,()=>this.applyTerrainSources()))}sourcePicker(e,t,n){const s=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,r.appendChild(c)}r.value=this.chosenSourceId.get(e)??t[0].id;const a=document.createElement("a");a.className="source-credit",a.target="_blank",a.rel="noopener noreferrer";const o=()=>{const l=Xs(t,r.value);r.title=l.credit,a.href=l.creditUrl,a.textContent=l.credit};return o(),r.addEventListener("change",()=>{this.chosenSourceId.set(e,r.value),o(),n(Xs(t,r.value))}),s.append(r,document.createTextNode(" "),a),s}labelledPicker(e,t,n,s){const r=document.createElement("label"),a=document.createElement("span");return a.textContent=t,r.append(a,this.sourcePicker(e,n,s)),r}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:Xs(Ko,this.chosenSourceId.get("elevation")).create(),imagery:Xs(cu,this.chosenSourceId.get("imagery")).create()}),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==="")return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let n;try{n=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=n,this.refreshPlaceMatches(),n.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const n=document.createElement("option");return n.textContent=t.name,n.title=t.name,n})),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)return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<oa&&Math.abs(t-this.namedCoordinates.lng)<oa||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),vb))}async reversePlace(e,t){const n=++this.placeSearchToken;let s;try{s=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}n===this.placeSearchToken&&(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,this.updateObserver())}updateObserver(){if(this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),n=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),s=this.numberOrUndefined(this.pitchInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=Math.max(0,r-(this.groundElevationM??0)),o=this.ufoElement.sighting.event,l=this.ufoElement.sighting.witnessTrack,c=this.ufoElement.currentTime,h=this.stringOrUndefined(this.placeNameInput.value.trim());o.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:h}]:void 0,e===void 0&&t===void 0&&n===void 0&&s===0&&a===0?l.removeKeyframeAt(c):l.addKeyframe(c,{lat:e,lng:t,elevationM:a,headingDeg:n,pitchDeg:s,fovDeg:du}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.schedulePlaceReverse(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}applyEdtfTimeInput(e,t){const n=e.value.trim();if(n==="")t(void 0);else{const s=nh(n);if(!s)return;t(s)}e.setCustomValidity(""),e.classList.remove("invalid"),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&rr({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.durationSeconds=void 0)}validateEdtfTimeInput(e){const t=e.value.trim();t===""||nh(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}refreshTimeZoneOptions(){const e=document.createElement("option");e.value="",e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(t=>{const n=document.createElement("option");return n.value=t,n.textContent=t,n})),this.timeZoneSelect.value=this.ufoElement.sighting.event.timeZone??""}updateTimeZone(){const e=this.stringOrUndefined(this.timeZoneSelect.value);this.ufoElement.sighting.event.timeZone=e,this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event,t=e.timeZone&&e.time?this.timeZones.offsetHoursAt(e.timeZone,e.time):void 0;t!==void 0&&(e.utcOffsetHours=t),this.utcOffsetInput.readOnly=e.timeZone!==void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateUtcOffset(){this.ufoElement.sighting.event.utcOffsetHours=this.numberOrUndefined(this.utcOffsetInput.value),this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObservationTime(){this.applyEdtfTimeInput(this.obsTimeInput,e=>{this.ufoElement.sighting.event.time=e})}updateObservationEndTime(){this.applyEdtfTimeInput(this.obsEndTimeInput,e=>{this.ufoElement.sighting.event.endTime=e})}updateWitnessMetadata(){const e=this.ufoElement.sighting,t=this.witnessFirstNamesInput.value.split(",").map(s=>s.trim()).filter(s=>s.length>0),n={id:this.stringOrUndefined(this.witnessIdInput.value),dirName:this.stringOrUndefined(this.witnessDirNameInput.value),title:this.stringOrUndefined(this.witnessTitleInput.value),lastName:this.stringOrUndefined(this.witnessLastNameInput.value),firstNames:t.length>0?t:void 0};e.witness=Object.values(n).some(s=>s!==void 0)?n:void 0,e.caseId=this.stringOrUndefined(this.caseIdInput.value),this.ufoElement.refresh()}updateDescription(){this.ufoElement.sighting.event.description=this.stringOrUndefined(this.descriptionInput.value),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0);this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={cloudCover: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()}buildSoundKindOptions(){for(const e of xf){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(),mb)}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=vu(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 qo(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),gb))}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(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0;const n=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!n,this.weatherInferredInput.checked=n&&this.weatherFromRecords;const s=n?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s;const r=t&&e!==void 0;if(this.weatherSourceLink.hidden=!r,r){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const a=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=a===""?"":`${a} `,this.weatherSourceRow.hidden=a===""}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&&Hc(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.weatherLookupResult=void 0,this.weatherFromRecords=e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0,this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup()}syncDurationField(){if(this.shadow.activeElement!==this.durationInput){const e=rr(this.ufoElement.sighting.event);this.durationInput.value=e!==void 0?String(e/1e3):""}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("invalid",e),this.durationInput.setAttribute("aria-invalid",String(e));const t=wf(this.ufoElement.sighting.event);this.durationInput.title=t==="imprecise"?this.messages.durationImprecise:""}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;this.playPauseButton.textContent=e?"⏸":"▶",this.playPauseButton.disabled=!t;const n=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=n,this.playPauseButton.setAttribute("aria-label",n),this.loopButton.setAttribute("aria-pressed",String(this.ufoElement.autoReplayEnabled)),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}syncObservationTimeFields(){const e=this.ufoElement.sighting.event.time;this.obsTimeInput.value=e?ih(e):"",this.obsTimeInput.setCustomValidity(""),this.obsTimeInput.classList.remove("invalid")}syncObservationEndTimeFields(){const e=this.ufoElement.sighting.event.endTime;this.obsEndTimeInput.value=e?ih(e):"",this.obsEndTimeInput.setCustomValidity(""),this.obsEndTimeInput.classList.remove("invalid")}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,n=t===void 0?void 0:Math.round(t/15),s=e!==void 0&&n!==void 0&&Math.abs(e-n)>xb;this.utcOffsetInput.classList.toggle("invalid",s),this.utcOffsetInput.title=s?this.messages.utcOffsetImplausible.replace("{solar}",n>=0?`+${n}`:String(n)):""}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),_b))}isSamePlace(e,t,n){return Math.abs(e.lat-t)<oa&&Math.abs(e.lng-n)<oa}async applyGroundElevation(e,t){const n=++this.groundElevationToken,s=Xs(Ko,this.chosenSourceId.get("elevation")),r=await new Wc(s.create()).at(e,t);if(n!==this.groundElevationToken||r===void 0)return;this.groundElevationFor={lat:e,lng:t};const a=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(r),this.syncElevationField(a),this.updateObserver()}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(Ss(this.ufoElement.sighting,0)?.elevationM??0),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=""}syncWitnessMetadataFields(){const e=this.ufoElement.sighting;this.witnessIdInput.value=e.witness?.id??"",this.witnessDirNameInput.value=e.witness?.dirName??"",this.witnessTitleInput.value=e.witness?.title??"",this.witnessLastNameInput.value=e.witness?.lastName??"",this.witnessFirstNamesInput.value=e.witness?.firstNames?.join(", ")??"",this.caseIdInput.value=e.caseId??"",this.descriptionInput.value=e.event.description??"",this.tagsInput.value=e.event.tags?.join(", ")??""}syncWeatherFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=Jo(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),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(e.windDirectionDeg)),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(e.windSpeed)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=e.witnessTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),n=e.event.place?.[0],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):n?String(n.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):n?String(n.lng):""),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(t.headingDeg):""),s!==this.pitchInput&&(this.pitchInput.value=String(t?.pitchDeg??0)),s!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},this.updatePresetButtons(),!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=n.getInterpolatedShapeAt(s,this.currentSourceId),a=this.buildAppearanceShape(e??r?.bounds??this.defaultBounds(),r,t);n.addKeyframe(s,[{sourceId:this.currentSourceId,shape:a}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,n=!0){if(t&&!n)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale};const s=eh(e,this.currentAppearance);return t?{...s,angle:t.angle,title:t.title,selected:t.selected}:s}onSelectionOrTimeChanged(){this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const e=this.ufoElement.sighting.timeline.sourceIds,t=e.filter(n=>this.selectedSourceIds.has(n)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0||e.length-t<1}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const n of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.objectSizeInput,this.objectDistanceInput,this.sourceSelect,...Object.values(this.presetButtons)])n.disabled=e,n.title=t}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:yb(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=e.title??""),this.shadow.activeElement!==this.objectSizeInput&&(this.objectSizeInput.value=e.physical?String(Number(e.physical.sizeM.toFixed(2))):""),this.shadow.activeElement!==this.objectDistanceInput&&(this.objectDistanceInput.value=e.physical?String(Number(e.physical.distanceM.toFixed(2))):""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,n=e.getInterpolatedShapeAt(t,this.currentSourceId);n&&(e.addKeyframe(t,[{sourceId:this.currentSourceId,shape:{...n,title:this.stringOrUndefined(this.shapeTitleInput.value)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}updatePhysicalExtent(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,n=e.getInterpolatedShapeAt(t,this.currentSourceId);if(!n)return;const s=this.numberOrUndefined(this.objectSizeInput.value),r=this.numberOrUndefined(this.objectDistanceInput.value);if(s===void 0&&r===void 0){e.addKeyframe(t,[{sourceId:this.currentSourceId,shape:{...n,physical:void 0}}]),this.ufoElement.refresh(),this.refreshApparentSize();return}if(s===void 0||r===void 0||s<=0||r<=0){this.refreshApparentSize();return}const a={sizeM:s,distanceM:r},o=this.ufoElement.canvasElement,l=ps.widthPx(a,o.height,this.currentFovDeg()),c=n.bounds.height*(n.bounds.width===0?1:l/n.bounds.width),h={x:n.bounds.x+(n.bounds.width-l)/2,y:n.bounds.y+(n.bounds.height-c)/2,width:l,height:c},u=n.kind==="oval"?{...n,bounds:h,physical:a}:{...n,bounds:h,physical:a,points:this.scalePoints(n,h)};e.addKeyframe(t,[{sourceId:this.currentSourceId,shape:u}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const n=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(r=>({x:r.x*n,y:r.y*s}))}currentFovDeg(){return Ss(this.ufoElement.sighting,this.ufoElement.currentTime)?.fovDeg??du}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="";return}const t=this.ufoElement.canvasElement,n=ps.pxToDeg(e.bounds.width,t.height,this.currentFovDeg()),s=ps.inMoons(n);this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{deg}",n.toLocaleString(void 0,{maximumFractionDigits:n<1?2:1})).replace("{moons}",s.toLocaleString(void 0,{maximumFractionDigits:s<10?1:0}))}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&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);if(t?.title)return t.title;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline,t=new Set([...e.sourceIds,this.currentSourceId]);let n=t.size+1;for(;t.has(`ufo-${n}`);)n++;this.currentSourceId=`ufo-${n}`,this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(s=>this.selectedSourceIds.has(s));if(!(t.length===0||e.sourceIds.length-t.length<1||!(t.length===1?window.confirm(this.messages.confirmDeleteShape.replace("{name}",this.shapeLabel(t[0]))):window.confirm(this.messages.confirmDeleteShapes.replace("{count}",String(t.length)))))){for(const s of t)e.removeSource(s);this.currentSourceId=e.sourceIds[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}}offsetDefaultBounds(e){const t=this.defaultBounds(),n=24;return{...t,x:t.x+e*n,y:t.y+e*n}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=[...new Set([...e.sourceIds,this.currentSourceId])];this.sourceSelect.innerHTML="";for(const n of t){const s=document.createElement("option");s.value=n,s.textContent=this.shapeLabel(n),this.sourceSelect.appendChild(s)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){if(e.title)return e.title;const n=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${n}`}addDecor(e=this.decorKindSelect.value){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==="building"?{floors:ga}:{},windows:m2(e)};t.decor=[...t.decor,s],this.currentDecorId=s.id,this.refreshDecorList(),this.ufoElement.refresh()}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(s=>s.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??e} ${t+1}`}deleteDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.filter(t=>t.id!==this.currentDecorId),this.currentDecorId=e.decor[0]?.id,this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.decorSelect.value=e,this.syncDecorFields()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,n=this.decorWitnessSideSelect.value;e.decor=e.decor.map(s=>{if(s.id!==this.currentDecorId)return s;const r=Qs(s.kind)&&n!==""?n:void 0;return{...s,title:this.stringOrUndefined(this.decorTitleInput.value),eastM:Number(this.decorEastInput.value),northM:Number(this.decorNorthInput.value),headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),witnessSide:r,floors:s.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:s.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(s=>s.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const n={};for(const s of ss){const r=this.decorWindowInputs[s];if(r.value==="")continue;const a=fc(t.kind,s)?0:uc,o=Math.max(a,Math.min(100,Number(r.value)));n[s]=o,String(o)!==r.value&&(r.value=String(o))}return{...t,windows:n}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,n=this.decorLitInput.checked;e.decor=e.decor.map(s=>{if(s.id!==this.currentDecorId)return s;const r=[...(s.litKeyframes??[]).filter(a=>a.t!==t),{t,lit:n}].sort((a,o)=>a.t-o.t);return{...s,litKeyframes:r}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const n=document.createElement("option");n.value=t.id,n.textContent=this.decorLabel(t),this.decorSelect.appendChild(n)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const n of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorWitnessSideSelect])n.disabled=!t;this.decorTitleInput.value=e?.title??"",this.decorEastInput.value=String(e?.eastM??0),this.decorNorthInput.value=String(e?.northM??0),this.decorHeadingInput.value=String(e?.headingDeg??0),this.decorLitInput.checked=e?pc(e,this.ufoElement.currentTime):!1,this.decorSightingUrlInput.value=e?.sightingUrl??"",this.decorFloorsInput.value=String(e?.floors??ga),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorWitnessSideSelect.value=e?.witnessSide??"";for(const n of ss){const s=e?.windows?.[n];this.decorWindowInputs[n].value=s===void 0?"":String(s)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const n=e.closest("label")??e;n.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId),t=e!==void 0,n=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorLitInput,t);const s=t&&n!==void 0&&P0(n);this.setRowVisible(this.labelDecorWindows,s);const r=n!==void 0?Vc(n):[];for(const c of ss)this.decorWindowInputs[c].disabled=!t,this.decorWindowInputs[c].min=String(n!==void 0&&fc(n,c)?0:uc),this.setRowVisible(this.decorWindowInputs[c],s&&r.includes(c));const a=t&&n!==void 0&&Qs(n);this.setRowVisible(this.decorWitnessSideSelect,a);const o=n!==void 0?f2(n):[];for(const c of ss)this.optionWitnessSide[c].hidden=!o.includes(c);const l=t&&n==="building";this.setRowVisible(this.decorFloorsInput,l),this.setRowVisible(this.decorOccupiedFloorInput,l),this.decorOccupiedFloorInput.max=String(e?.floors??ga)}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=pc(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of fu)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return eh(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-ls.width/2,y:e.height/2-ls.height/2,width:ls.width,height:ls.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 Vy(this.ufoElement.sighting.timeline,new Wy(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){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=Na(navigator.languages,Su);e!=="en"&&this.applyMessages(await Xf(e))}applyMessages(e){this.currentSourceId===la&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,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.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelObjectSize.textContent=e.objectSize,this.labelObjectDistance.textContent=e.objectDistance,this.objectSizeInput.placeholder=e.objectSizePlaceholder,this.objectDistanceInput.placeholder=e.objectDistancePlaceholder,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.durationInput.placeholder=e.durationPlaceholder,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.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,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.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.obsTimeInput.title=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.obsEndTimeInput.title=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorFieldset.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorWitness.textContent=e.decorWitness,this.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewTestimonyButton.textContent=e.viewTestimony,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorWitnessButton.textContent=e.addWitness,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorWitnessSide.textContent=e.decorWitnessSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionWitnessSideNone.textContent=e.decorWitnessSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const n of ss)this.labelDecorSide[n].textContent=t[n],this.optionWitnessSide[n].textContent=t[n];this.refreshDecorList(),this.labelWitnessId.textContent=e.witnessId,this.labelWitnessDirName.textContent=e.witnessDirName,this.labelWitnessTitle.textContent=e.witnessTitle,this.labelWitnessLastName.textContent=e.witnessLastName,this.labelWitnessFirstNames.textContent=e.witnessFirstNames,this.witnessFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelCaseId.textContent=e.caseId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelWeather.textContent=e.weather,this.labelShapeGroup.textContent=e.shapeGroup,this.labelTemporalGroup.textContent=e.temporalGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelWitnessGroup.textContent=e.witnessGroup,this.labelCircumstancesGroup.textContent=e.circumstancesGroup,this.labelCloudCover.textContent=e.cloudCover,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.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;for(const[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelLensFlareBrightness.textContent=e.lensFlareBrightness,this.labelCameraDevice.textContent=e.cameraDevice,this.loopButton.title=e.autoReplay,this.loopButton.setAttribute("aria-label",e.autoReplay),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState==="playing";if(this.selectedSourceIds.size>1){const l=new Xa(this.selectedMembers()),c=$e.hitTestHandle({bounds:l.bounds(),angle:0},t);if(c==="rotate"){if(r)return;this.dragState={kind:"group-rotate",group:l,startPointer:t},this.startDragListening();return}if(c){if(r)return;this.dragState={kind:"group-resize",group:l,handle:c},this.startDragListening();return}}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId),c=l?.kind==="polygon"?$e.hitTestVertex(l,t):void 0;if(l?.kind==="polygon"&&c!==void 0){if(r)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:l,vertexIndex:c},this.startDragListening();return}const h=l&&$e.hitTestHandle(l,t);if(l&&h){if(r)return;this.beginDrag(h==="rotate"?"rotate":"resize",this.currentSourceId,l,t,h);return}}const a=n.hitTest(s,t.x,t.y);if(!a){const l=this.pickDecorAt(e);if(l!==void 0){this.selectDecor(l);return}r||this.beginCameraDrag(t);return}if(e.shiftKey?this.toggleUnitSelection(a.sourceId):this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),r)return;const o=[...this.selectedSourceIds].map(l=>({sourceId:l,original:l===a.sourceId?a.shape:n.getInterpolatedShapeAt(s,l)??a.shape}));this.dragState={kind:"move",sources:o,startPointer:t},this.startDragListening()}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(n=>({sourceId:n,shape:e.getInterpolatedShapeAt(t,n)})).filter(n=>!!n.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(n=>this.selectedSourceIds.has(n))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,n=t.groupMembers(e)??[e];if(n.every(r=>this.selectedSourceIds.has(r))){if(n.length>=this.selectedSourceIds.size)return;for(const r of n)this.selectedSourceIds.delete(r);if(!this.selectedSourceIds.has(this.currentSourceId)){const r=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((a,o)=>r.indexOf(a)-r.indexOf(o)).pop()}}else{for(const r of n)this.selectedSourceIds.add(r);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 n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.selectedSourceIds.size===1?n.getInterpolatedShapeAt(s,this.currentSourceId):void 0,o=r?.kind==="polygon"&&$e.hitTestVertex(r,t)!==void 0?{sourceId:this.currentSourceId}:n.hitTest(s,t.x,t.y);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const n=this.ufoElement.canvasElement.getBoundingClientRect();if(n.width===0||n.height===0)return;const s=(e.clientX-n.left)/n.width*2-1,r=-((e.clientY-n.top)/n.height*2-1);return this.sceneElement.pickDecorAt(s,r)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const n=this.ufoElement.sighting.timeline.sourceIds,s=n.filter(f=>this.selectedSourceIds.has(f)),r=n.length<=s.length,a=s.length>0&&n.slice(n.length-s.length).every(f=>this.selectedSourceIds.has(f)),o=s.length>0&&n.slice(0,s.length).every(f=>this.selectedSourceIds.has(f));this.contextBringToFrontButton.disabled=r||a,this.contextSendToBackButton.disabled=r||o,this.contextBringToFrontButton.title=r?this.messages.onlyOneShape:a?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=r?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title=this.contextDeleteButton.disabled?this.messages.onlyOneShape:"";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const u=h&&this.contextMenuPoint?$e.hitTestVertex(c,this.contextMenuPoint):void 0,d=h&&c.points.length<=xu;this.contextDeleteVertexButton.disabled=!h||u===void 0||d,this.contextDeleteVertexButton.title=h?d?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,n){this.contextMenuDecorId=n.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewTestimonyButton.disabled=!n.sightingUrl,this.contextViewTestimonyButton.title=n.sightingUrl?"":this.messages.noWitnessRecording,this.refreshContextMasksSubmenu(n),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";for(const t of this.ufoElement.sighting.timeline.sourceIds){const n=document.createElement("label"),s=document.createElement("input");s.type="checkbox",s.checked=e.occludesSourceIds?.includes(t)??!1,s.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,t,s.checked)),n.appendChild(s),n.appendChild(document.createTextNode(this.shapeLabel(t))),this.contextMasksSubmenu.appendChild(n)}}updateDecorOccludesShape(e,t,n){const s=this.ufoElement.sighting;s.decor=s.decor.map(r=>{if(r.id!==e)return r;const a=n?[...new Set([...r.occludesSourceIds??[],t])]:(r.occludesSourceIds??[]).filter(o=>o!==t);return{...r,occludesSourceIds:a.length>0?a:void 0}}),this.ufoElement.refresh()}viewWitnessTestimony(){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,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const s=$e.insertVertexNear(n,e);this.ufoElement.sighting.timeline.addKeyframe(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,n=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(n?.kind!=="polygon")return;const s=$e.hitTestVertex(n,e);if(s===void 0)return;const r=$e.deleteVertex(n,s);this.ufoElement.sighting.timeline.addKeyframe(t,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(n=>this.selectedSourceIds.has(n)).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,n,s,r){this.dragState={kind:e,sourceId:t,original:n,handle:r,startPointer:s},this.startDragListening()}beginCameraDrag(e){const t=this.isWitnessInsideDecor();this.cameraDragState={startPointer:e,startHeadingDeg:t?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:t?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:t},t||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isWitnessInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.witnessSide!==void 0&&Qs(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(n=>n.witnessSide!==void 0&&Qs(n.kind)),t=e?`${e.id}:${e.witnessSide}`: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.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const n=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:s,startPointer:r}=this.dragState,a=t.x-r.x,o=t.y-r.y,l=s.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+a,y:h.bounds.y+o}}}));this.ufoElement.sighting.timeline.addKeyframe(n,l)}else if(this.dragState.kind==="group-resize"){const{group:s,handle:r}=this.dragState;this.ufoElement.sighting.timeline.addKeyframe(n,s.resize(r,t))}else if(this.dragState.kind==="group-rotate"){const{group:s,startPointer:r}=this.dragState;this.ufoElement.sighting.timeline.addKeyframe(n,s.rotate(t,r))}else if(this.dragState.kind==="vertex"){const{sourceId:s,original:r,vertexIndex:a}=this.dragState,o=$e.moveVertex(r,a,t);this.ufoElement.sighting.timeline.addKeyframe(n,[{sourceId:s,shape:o}])}else{const{kind:s,sourceId:r,original:a,handle:o}=this.dragState,l=s==="resize"?$e.resizeShape(a,o,t):$e.rotateShape(a,t);this.ufoElement.sighting.timeline.addKeyframe(n,[{sourceId:r,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:n,startHeadingDeg:s,startPitchDeg:r,insideDecor:a}=this.cameraDragState,o=s+(t.x-n.x)*hu,l=Math.max(-90,Math.min(90,r-(t.y-n.y)*hu));if(a){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(o),this.pitchInput.value=String(l),this.updateObserver()}endDrag(){!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}nudgeBounds(e,t){const n={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":n.width=Math.max(ai,n.width-ni);break;case"ArrowRight":n.width+=ni;break;case"ArrowUp":n.height=Math.max(ai,n.height-ni);break;case"ArrowDown":n.height+=ni;break}n.x-=(n.width-e.width)/2,n.y-=(n.height-e.height)/2}else switch(t.key){case"ArrowLeft":n.x-=ni;break;case"ArrowRight":n.x+=ni;break;case"ArrowUp":n.y-=ni;break;case"ArrowDown":n.y+=ni;break}return n}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedMembers();if(s.length!==0){if(e.preventDefault(),s.length===1){const{sourceId:r,shape:a}=s[0];t.addKeyframe(n,[{sourceId:r,shape:{...a,bounds:this.nudgeBounds(a.bounds,e)}}])}else{const r=new Xa(s),a=this.nudgeBounds(r.bounds(),e);t.addKeyframe(n,r.scaleTo(a))}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 n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(r)if(this.selectedSourceIds.size>1){const a=$e.hitTestHandle({bounds:new Xa(this.selectedMembers()).bounds(),angle:0},t);if(a)return this.cursorForHandle(a,0)}else{const a=n.getInterpolatedShapeAt(s,this.currentSourceId);if(a?.kind==="polygon"&&$e.hitTestVertex(a,t)!==void 0)return"vertex";const o=a&&$e.hitTestHandle(a,t);if(a&&o)return this.cursorForHandle(o,a.angle)}return n.hitTest(s,t.x,t.y)?r?"move":"select":this.pickDecorAt(e)!==void 0?"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${$e.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,n=t.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top;this.recorder?.onPointerMove(s,r),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(mu(this.buildPrototype({x:0,y:0,width:ls.width,height:ls.height}),s,r))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(!(n.width===0||n.height===0))return{x:(e.clientX-n.left)/n.width*t.width,y:(e.clientY-n.top)/n.height*t.height}}}const pu="rr0-ufo-recorder";function Mb(){Ua(),customElements.get(pu)||customElements.define(pu,bb)}Mb();
|
|
@@ -5363,4 +5363,4 @@ void main() {
|
|
|
5363
5363
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
5364
5364
|
}
|
|
5365
5365
|
`;let Jr;function z3(){if(Jr)return Jr;const i=128,e=document.createElement("canvas");e.width=i,e.height=i;const t=e.getContext("2d"),n=t.createRadialGradient(i/2,i/2,0,i/2,i/2,i/2);return n.addColorStop(0,"rgba(255,255,255,1)"),n.addColorStop(.4,"rgba(255,255,255,0.35)"),n.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=n,t.fillRect(0,0,i,i),Jr=new Wn(e),Jr}function k3(i){const t=document.createElement("canvas");t.width=128,t.height=128;const n=t.getContext("2d"),s=128/2-2,r=128/2,a=128/2,o="#2e2b26",l="#f4f1e2";n.fillStyle=o,n.beginPath(),n.arc(r,a,s,0,Math.PI*2),n.fill();const c=rd(i.illuminatedFraction,0,1),h=i.phaseFraction<.5,d=s*Math.abs(1-2*c),u=c<.5;return n.save(),n.beginPath(),n.arc(r,a,s,0,Math.PI*2),n.clip(),n.fillStyle=l,n.beginPath(),h?(n.arc(r,a,s,-Math.PI/2,Math.PI/2,!1),n.ellipse(r,a,d,s,0,Math.PI/2,-Math.PI/2,u)):(n.arc(r,a,s,Math.PI/2,-Math.PI/2,!1),n.ellipse(r,a,d,s,0,-Math.PI/2,Math.PI/2,u)),n.fill(),n.restore(),new Wn(t)}function G3(i){const e=document.createElement("canvas");e.width=128,e.height=128;const t=e.getContext("2d");return t.fillStyle="rgba(0, 0, 0, 0.55)",t.beginPath(),t.arc(64,64,60,0,Math.PI*2),t.fill(),t.fillStyle="#ffffff",t.font="bold 52px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(i,64,68),new Wn(e)}function Po(i){let e=i;return function(){e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}const Nu=new Map;function H3(i){const e=i.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),t=e,n=t*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(i,0*n,t),dec:new Float32Array(i,1*n,t),mag:new Float32Array(i,2*n,t),ci:new Float32Array(i,3*n,t)}}function V3(i){let e=Nu.get(i);return e||(e=fetch(i).then(t=>t.arrayBuffer()).then(H3),Nu.set(i,e)),e}const W3=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,X3=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,q3=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,Y3=20,$3=1;class Z3{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}this.context.state==="suspended"&&this.context.resume()}setAmbient(e,t,n){if(this.requested={type:e,intensity:t,windSpeed:n},!this.context)return;this.paused&&(e="none",t=0,n=0);const s=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=s==="hail"?Math.min(1,t*1.3+.2):s==="rain"?t:0,s!==this.ambientKey){this.ambientKey=s;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,s!=="none"&&this.startLoop(W3,this.ambientVolume).then(o=>this.applyIfCurrent(o,a,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(n/Y3,1);const r=n>$3;if(r!==this.windActive){this.windActive=r;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,r&&this.startLoop(X3,this.windVolume).then(o=>this.applyIfCurrent(o,a,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:n,windSpeed:s}=this.requested;this.setAmbient(t,n,s)}playThunder(){!this.context||this.paused||this.playOneShot(q3,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.buffers.clear()}applyIfCurrent(e,t,n,s){if(t!==n()){e?.source.stop();return}s(e)}async startLoop(e,t){const n=this.context;if(n)try{const s=await this.getBuffer(e),r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();return a.gain.value=t,r.connect(a).connect(n.destination),r.start(),{source:r,gain:a}}catch(s){console.warn("Weather ambient sound failed to load, staying silent:",s);return}}async playOneShot(e,t){const n=this.context;if(n)try{const s=await this.getBuffer(e),r=n.createBufferSource();r.buffer=s;const a=n.createGain();a.gain.value=t,r.connect(a).connect(n.destination),r.start()}catch(s){console.warn("Thunder sound failed to load:",s)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let n=this.buffers.get(e);return n||(n=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,n)),n}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}ku();const K3={sun:{en:"Sun",fr:"Soleil"},moon:{en:"Moon",fr:"Lune"},Venus:{en:"Venus",fr:"Vénus"},Mars:{en:"Mars",fr:"Mars"},Jupiter:{en:"Jupiter",fr:"Jupiter"},Saturn:{en:"Saturn",fr:"Saturne"}},J3=["en","fr"],Q3={building:{en:"Building",fr:"Bâtiment"},tree:{en:"Tree",fr:"Arbre"},streetlight:{en:"Streetlight",fr:"Lampadaire"},vehicle:{en:"Vehicle",fr:"Véhicule"},witness:{en:"Witness",fr:"Témoin"}},j3=new URL(""+new URL("stars-mag7.5-DDr9QasD.bin",import.meta.url).href,import.meta.url).href,eM={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Io={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class tM extends HTMLElement{static get observedAttributes(){return["src","star-catalog-src","show-compass","lens-flare-intensity","lens-flare-brightness"]}shadow;stageElement;frameElement;sceneCanvas;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;lastTimeMs=0;starCatalog;weatherAudio=new Z3;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);const t=this.ufoElement.canvasElement,n=t.getBoundingClientRect();if(n.width===0||n.height===0)return;const s=(e.clientX-n.left)/n.width*t.width,r=(e.clientY-n.top)/n.height*t.height;if(this.ufoElement.hasVisibleShapeAt(s,r)){this.hoverTooltip.hidden=!0;return}const a=(e.clientX-n.left)/n.width*2-1,o=-((e.clientY-n.top)/n.height*2-1),l=ya(navigator.languages,J3),c=this.sceneRenderer.pickBodyAt(a,o);if(c){this.showHoverTooltip(e,K3[c]?.[l]??c);return}const h=this.sceneRenderer.pickDecorAt(a,o),d=h?this.ufoElement.sighting.decor.find(u=>u.id===h):void 0;if(d){this.showHoverTooltip(e,d.title||Q3[d.kind][l]);return}this.hoverTooltip.hidden=!0};showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.hoverTooltip.style.left=`${e.clientX-n.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-n.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash=()=>{clearTimeout(this.thunderTimeoutId);const e=(.5+Math.random()*3.5)*1e3;this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),e)};handleFirstInteraction=()=>{this.weatherAudio.resume(),this.setWeather(Fc(this.ufoElement.sighting,this.lastTimeMs))};handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.updateUfoOcclusion(this.lastTimeMs)};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e),this.weatherAudio.setPaused(!e),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${vd}</style>${_d}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new P3(this.sceneCanvas,void 0,this.handleLightningFlash),this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(Fo),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave),this.ufoElement.canvasElement.addEventListener("pointerdown",this.handleFirstInteraction,{once:!0})}connectedCallback(){this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),document.addEventListener("fullscreenchange",this.handleFullscreenChange);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose()}attributeChangedCallback(e,t,n){if(e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n),e==="star-catalog-src"&&n!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&n!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="lens-flare-intensity"&&n!==t){const s=n===null?NaN:parseFloat(n);this.sceneRenderer.setLensFlareArtifactIntensity(Number.isFinite(s)?s:0)}if(e==="lens-flare-brightness"&&n!==t){const s=n===null?NaN:parseFloat(n);this.sceneRenderer.setDazzleIntensity(Number.isFinite(s)?s:1)}}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity,e.windSpeed)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume()}async loadFromSrc(e){const t=await fetch(e);this.sightingData=await t.json()}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.lastTimeMs=0,this.updateAstronomy(0)}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=n,this.sceneRenderer.resize(t,n)}async loadStars(){const e=this.getAttribute("star-catalog-src")??j3;this.starCatalog=await V3(e),this.updateAstronomy(this.lastTimeMs)}updateAstronomy(e){const t=this.ufoElement.sighting;this.setWeather(Fc(t,e)),this.sceneRenderer.setDecor(t.decor);const n=Uc(t,e);this.sceneRenderer.setObserverPose(n??Io),this.sceneRenderer.updateDecorAnchoring(Uc(t,0),n),this.sceneRenderer.updateDecorLitState(e),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng);const s=n?.lat??Io.lat,r=n?.lng??Io.lng,a=V0(t.event.time??{},r,t.event.utcOffsetHours);if(!a){this.sceneRenderer.setAstronomy(eM);return}const o=new Date(a.getTime()+e),l={lat:s,lng:r,elevationM:n?.elevationM??0},c={..._o("Sun",o,l),magnitude:vo("Sun",o)},h={..._o("Moon",o,l),phase:Gx(o),magnitude:vo("Moon",o)},d=zx.map(u=>({body:u,position:_o(u,o,l),magnitude:vo(u,o)}));this.sceneRenderer.setAstronomy({sun:c,moon:h,planets:d,stars:this.starCatalog?{catalog:this.starCatalog,date:o,observer:l}:void 0})}updateUfoOcclusion(e){const t=this.ufoElement.sighting.timeline,n=this.ufoElement.canvasElement,s=new Set;for(const r of t.sourceIds){const a=t.getInterpolatedShapeAt(e,r);if(!a)continue;const o=(a.bounds.x+a.bounds.width/2)/n.width*2-1,l=-((a.bounds.y+a.bounds.height/2)/n.height*2-1),c={declared:a.behindCloud,distanceM:a.physical?.distanceM};this.sceneRenderer.isScreenPointOccluded(o,l,r,c)&&s.add(r)}this.ufoElement.setOccludedSourceIds(s)}}const jl="rr0-scene";function ad(){ku(),customElements.get(jl)||customElements.define(jl,tM)}const od={testimonyBy:"Testimony by",about:"About",close:"Close",observation:"Observation",date:"Date",location:"Location",case:"Case",description:"Description",tags:"Tags",credits:"Credits",editThisObservation:"Edit this observation",embed:"Embed",embedReplay:"Replay",embedEdit:"Editor",embedCopy:"Copy",embedCopied:"Copied"},nM=Object.freeze(Object.defineProperty({__proto__:null,eyewitnessMessages_en:od},Symbol.toStringTag,{value:"Module"}));ad();const iM="“Thunder” by Jerimee",sM="https://creativecommons.org/licenses/by/3.0/",rM="CC BY 3.0",Lo="https://ufoathome.org";class aM extends HTMLElement{static get observedAttributes(){return["src"]}shadow;sceneElement;toolbarElement;testimonyPrefix;witnessText;witnessSelect;infoButton;infoPanel;infoAppLink;infoObservationHeading;infoObservationList;infoCreditsToggle;infoCreditsList;infoCloseButton;infoEmbedToggle;infoEmbedPanel;embedReplayRadio;embedEditRadio;labelEmbedReplay;labelEmbedEdit;embedMarkup;embedCopyButton;supportsPopover=typeof HTMLElement.prototype.showPopover=="function";entries=[];currentSrc;infoOpen=!1;creditsOpen=!1;embedOpen=!1;language="en";messages=od;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${gd}</style>${md}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(jl),this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.toolbarElement=this.shadow.getElementById("toolbar"),this.testimonyPrefix=this.shadow.getElementById("testimony-prefix"),this.witnessText=this.shadow.getElementById("witness-text"),this.witnessSelect=this.shadow.getElementById("witness"),this.infoButton=this.shadow.getElementById("info-button"),this.infoPanel=this.shadow.getElementById("info-panel"),this.infoAppLink=this.shadow.getElementById("info-app-link"),this.infoObservationHeading=this.shadow.getElementById("info-observation-heading"),this.infoObservationList=this.shadow.getElementById("info-observation-list"),this.infoCreditsToggle=this.shadow.getElementById("info-credits-toggle"),this.infoCreditsList=this.shadow.getElementById("info-credits-list"),this.infoCloseButton=this.shadow.getElementById("info-close"),this.infoEmbedToggle=this.shadow.getElementById("info-embed-toggle"),this.infoEmbedPanel=this.shadow.getElementById("info-embed"),this.embedReplayRadio=this.shadow.getElementById("embed-kind-replay"),this.embedEditRadio=this.shadow.getElementById("embed-kind-edit"),this.labelEmbedReplay=this.shadow.getElementById("label-embed-replay"),this.labelEmbedEdit=this.shadow.getElementById("label-embed-edit"),this.embedMarkup=this.shadow.getElementById("embed-markup"),this.embedCopyButton=this.shadow.getElementById("embed-copy"),this.witnessSelect.addEventListener("change",()=>this.selectWitness(this.witnessSelect.value)),this.supportsPopover?(this.infoPanel.setAttribute("popover","auto"),this.infoPanel.removeAttribute("hidden"),this.infoButton.setAttribute("popovertarget","info-panel"),this.infoPanel.addEventListener("beforetoggle",t=>{t.newState==="open"&&this.populateInfoPanel()}),this.infoPanel.addEventListener("toggle",t=>this.syncInfoOpen(t.newState==="open"))):this.infoButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCloseButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCreditsToggle.addEventListener("click",()=>this.toggleCredits()),this.infoEmbedToggle.addEventListener("click",()=>this.toggleEmbed());for(const t of[this.embedReplayRadio,this.embedEditRadio])t.addEventListener("change",()=>this.refreshEmbedMarkup());this.embedCopyButton.addEventListener("click",()=>void this.copyEmbedMarkup()),this.loadLocaleMessages()}async loadLocaleMessages(){this.language=ya(navigator.languages,Bu),this.language!=="en"&&(this.messages=await sf(this.language),this.testimonyPrefix.textContent=this.messages.testimonyBy,this.infoButton.title=this.messages.about,this.infoButton.setAttribute("aria-label",this.messages.about),this.infoCloseButton.setAttribute("aria-label",this.messages.close),this.infoObservationHeading.textContent=this.messages.observation,this.infoCreditsToggle.textContent=this.messages.credits,this.infoEmbedToggle.textContent=this.messages.embed,this.labelEmbedReplay.textContent=this.messages.embedReplay,this.labelEmbedEdit.textContent=this.messages.embedEdit,this.embedCopyButton.textContent=this.messages.embedCopy,this.infoOpen&&this.populateInfoPanel(),this.updateTestimonyLine())}connectedCallback(){const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(e,t,n){e==="src"&&n&&n!==t&&this.isConnected&&this.loadFromSrc(n)}async loadFromSrc(e){const n=await(await fetch(e)).json();Array.isArray(n)?await this.loadWitnessUrls(n):this.setEntries([{src:e,sighting:n}])}get witnessUrls(){return this.entries.map(e=>e.src)}set witnessUrls(e){this.loadWitnessUrls(e)}async loadWitnessUrls(e){const t=await Promise.all(e.map(async n=>{const s=await fetch(n);return{src:n,sighting:await s.json()}}));this.setEntries(t)}setEntries(e){this.entries=e,this.warnOnMismatchedCaseIds(e),this.toolbarElement.hidden=e.length===0;const t=e.length>1;this.witnessSelect.hidden=!t,this.witnessText.hidden=t,this.witnessSelect.innerHTML="";for(const s of e){const r=document.createElement("option");r.value=s.src,r.textContent=this.witnessDisplayName(s.sighting.witness)??s.src,this.witnessSelect.appendChild(r)}const n=e.find(s=>s.src===this.currentSrc)??e[0];n?this.selectWitness(n.src):this.updateTestimonyLine()}editorUrl(){if(!this.currentSrc)return Lo;const e=new URL(this.currentSrc,location.href);return e.origin===location.origin?`${Lo}${e.pathname}`:`${Lo}/?sighting=${encodeURIComponent(e.href)}`}embedMarkupFor(e){const t=e==="edit"?"rr0-ufo-recorder":"rr0-eyewitness",n=new URL(`${t}.mjs`,import.meta.url).href,s=this.currentSrc?new URL(this.currentSrc,location.href).href:"";return`<script type="module" src="${n}"><\/script>
|
|
5366
|
-
<${t} src="${s}"></${t}>`}refreshEmbedMarkup(){this.embedMarkup.value=this.embedMarkupFor(this.embedEditRadio.checked?"edit":"replay")}async copyEmbedMarkup(){try{await navigator.clipboard.writeText(this.embedMarkup.value),this.embedCopyButton.textContent=this.messages.embedCopied,window.setTimeout(()=>this.embedCopyButton.textContent=this.messages.embedCopy,1500)}catch{this.embedMarkup.select()}}warnOnMismatchedCaseIds(e){const t=new Set(e.map(n=>n.sighting.caseId).filter(n=>n!==void 0));t.size>1&&console.warn(`<rr0-eyewitness>: witnesses declare different case ids (${[...t].join(", ")}) — they may not belong to the same case.`)}selectWitness(e){const t=this.entries.find(n=>n.src===e);t&&(this.currentSrc=e,this.witnessSelect.value=e,this.sceneElement.sightingData=t.sighting,this.updateTestimonyLine(),this.infoOpen&&this.populateInfoPanel())}updateTestimonyLine(){const e=this.entries.find(t=>t.src===this.currentSrc);e&&(this.witnessText.textContent=this.witnessDisplayName(e.sighting.witness)??e.src)}witnessDisplayName(e){if(!e)return;const t=[...e.firstNames??[],e.lastName].filter(Boolean).join(" ");return e.title||t||e.id||e.dirName}formatDate(e){const t=e.place?.[0],n=V0(e.time??{},t?.lng??0,e.utcOffsetHours);if(!n)return;const s=n.getTime()+this.utcOffsetHoursOf(e,t?.lng??0)*36e5;return new Intl.DateTimeFormat(this.language==="fr"?"fr-FR":"en-US",{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(s))}utcOffsetHoursOf(e,t){return e.utcOffsetHours??Math.round(t/15)}formatLocation(e){const t=e.place?.[0];if(t)return`${t.lat.toFixed(4)}, ${t.lng.toFixed(4)}`}toggleInfoPanel(){const e=!this.infoOpen;if(this.supportsPopover){const t=this.infoPanel.matches(":popover-open");e&&!t?this.infoPanel.showPopover():!e&&t&&this.infoPanel.hidePopover();return}this.syncInfoOpen(e),this.infoPanel.hidden=!e,e?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}syncInfoOpen(e){e!==this.infoOpen&&(this.infoOpen=e,this.infoButton.setAttribute("aria-expanded",String(e)),e?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false"),this.embedOpen=!1,this.infoEmbedPanel.hidden=!0,this.infoEmbedToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=e=>{const t=e.composedPath();!t.includes(this.infoPanel)&&!t.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}toggleEmbed(){this.embedOpen=!this.embedOpen,this.infoEmbedPanel.hidden=!this.embedOpen,this.infoEmbedToggle.setAttribute("aria-expanded",String(this.embedOpen)),this.embedOpen&&(this.refreshEmbedMarkup(),this.revealInPanel(this.infoEmbedPanel))}revealInPanel(e){e.scrollIntoView?.({block:"nearest"})}populateInfoPanel(){const e=this.entries.find(r=>r.src===this.currentSrc);if(this.infoObservationList.innerHTML="",e){const r=this.formatDate(e.sighting);r&&this.appendInfoRow(this.infoObservationList,this.messages.date,r);const a=this.formatLocation(e.sighting);a&&this.appendInfoRow(this.infoObservationList,this.messages.location,a),e.sighting.caseId&&this.appendInfoRow(this.infoObservationList,this.messages.case,e.sighting.caseId),e.sighting.description&&this.appendInfoRow(this.infoObservationList,this.messages.description,e.sighting.description),e.sighting.tags&&e.sighting.tags.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,e.sighting.tags.join(", "))}this.refreshEmbedMarkup(),this.infoAppLink.href=this.editorUrl(),this.infoAppLink.textContent="UFO@home v0.19.
|
|
5366
|
+
<${t} src="${s}"></${t}>`}refreshEmbedMarkup(){this.embedMarkup.value=this.embedMarkupFor(this.embedEditRadio.checked?"edit":"replay")}async copyEmbedMarkup(){try{await navigator.clipboard.writeText(this.embedMarkup.value),this.embedCopyButton.textContent=this.messages.embedCopied,window.setTimeout(()=>this.embedCopyButton.textContent=this.messages.embedCopy,1500)}catch{this.embedMarkup.select()}}warnOnMismatchedCaseIds(e){const t=new Set(e.map(n=>n.sighting.caseId).filter(n=>n!==void 0));t.size>1&&console.warn(`<rr0-eyewitness>: witnesses declare different case ids (${[...t].join(", ")}) — they may not belong to the same case.`)}selectWitness(e){const t=this.entries.find(n=>n.src===e);t&&(this.currentSrc=e,this.witnessSelect.value=e,this.sceneElement.sightingData=t.sighting,this.updateTestimonyLine(),this.infoOpen&&this.populateInfoPanel())}updateTestimonyLine(){const e=this.entries.find(t=>t.src===this.currentSrc);e&&(this.witnessText.textContent=this.witnessDisplayName(e.sighting.witness)??e.src)}witnessDisplayName(e){if(!e)return;const t=[...e.firstNames??[],e.lastName].filter(Boolean).join(" ");return e.title||t||e.id||e.dirName}formatDate(e){const t=e.place?.[0],n=V0(e.time??{},t?.lng??0,e.utcOffsetHours);if(!n)return;const s=n.getTime()+this.utcOffsetHoursOf(e,t?.lng??0)*36e5;return new Intl.DateTimeFormat(this.language==="fr"?"fr-FR":"en-US",{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(s))}utcOffsetHoursOf(e,t){return e.utcOffsetHours??Math.round(t/15)}formatLocation(e){const t=e.place?.[0];if(t)return`${t.lat.toFixed(4)}, ${t.lng.toFixed(4)}`}toggleInfoPanel(){const e=!this.infoOpen;if(this.supportsPopover){const t=this.infoPanel.matches(":popover-open");e&&!t?this.infoPanel.showPopover():!e&&t&&this.infoPanel.hidePopover();return}this.syncInfoOpen(e),this.infoPanel.hidden=!e,e?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}syncInfoOpen(e){e!==this.infoOpen&&(this.infoOpen=e,this.infoButton.setAttribute("aria-expanded",String(e)),e?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false"),this.embedOpen=!1,this.infoEmbedPanel.hidden=!0,this.infoEmbedToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=e=>{const t=e.composedPath();!t.includes(this.infoPanel)&&!t.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}toggleEmbed(){this.embedOpen=!this.embedOpen,this.infoEmbedPanel.hidden=!this.embedOpen,this.infoEmbedToggle.setAttribute("aria-expanded",String(this.embedOpen)),this.embedOpen&&(this.refreshEmbedMarkup(),this.revealInPanel(this.infoEmbedPanel))}revealInPanel(e){e.scrollIntoView?.({block:"nearest"})}populateInfoPanel(){const e=this.entries.find(r=>r.src===this.currentSrc);if(this.infoObservationList.innerHTML="",e){const r=this.formatDate(e.sighting);r&&this.appendInfoRow(this.infoObservationList,this.messages.date,r);const a=this.formatLocation(e.sighting);a&&this.appendInfoRow(this.infoObservationList,this.messages.location,a),e.sighting.caseId&&this.appendInfoRow(this.infoObservationList,this.messages.case,e.sighting.caseId),e.sighting.description&&this.appendInfoRow(this.infoObservationList,this.messages.description,e.sighting.description),e.sighting.tags&&e.sighting.tags.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,e.sighting.tags.join(", "))}this.refreshEmbedMarkup(),this.infoAppLink.href=this.editorUrl(),this.infoAppLink.textContent="UFO@home v0.19.5",this.infoAppLink.title=this.messages.editThisObservation,this.infoAppLink.setAttribute("aria-label",this.messages.editThisObservation),this.infoCreditsList.innerHTML="";const t=this.sceneElement.currentTerrainAttribution;if(t){const r=document.createElement("li");r.textContent=t,this.infoCreditsList.appendChild(r)}const n=document.createElement("li");n.textContent=`${iM} (`;const s=document.createElement("a");s.href=sM,s.target="_blank",s.rel="noopener",s.textContent=rM,n.appendChild(s),n.appendChild(document.createTextNode(")")),this.infoCreditsList.appendChild(n)}appendInfoRow(e,t,n){const s=document.createElement("dt");s.textContent=t;const r=document.createElement("dd");r.textContent=n,e.appendChild(s),e.appendChild(r)}}const Uu="rr0-eyewitness";function oM(){ad(),customElements.get(Uu)||customElements.define(Uu,aM)}oM();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rr0/ufoathome",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.19.
|
|
4
|
+
"version": "0.19.5",
|
|
5
5
|
"description": "UFO@home — record and replay a UFO sighting's shape, movement and appearance",
|
|
6
6
|
"author": "Jérôme Beau <rr0@rr0.org> (https://rr0.org)",
|
|
7
7
|
"license": "MIT",
|