@rr0/ufoathome 0.104.1 → 0.105.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed-scene/rr0-scene.mjs +2 -2
- package/dist-embed-sighting/{SightingMessages_es-DD2m_7j8.js → SightingMessages_es-B5pZonER.js} +1 -1
- package/dist-embed-sighting/{SightingMessages_fr-DXps3C_h.js → SightingMessages_fr-BC_g9MLr.js} +1 -1
- package/dist-embed-sighting/{SightingMessages_it-Du_Kn9cp.js → SightingMessages_it-CJRrig_B.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +5 -5
- package/dist-embed-sighting-editor/{SightingEditorMessages_es-SrV-tb46.js → SightingEditorMessages_es-BTlk4NH4.js} +2 -2
- package/dist-embed-sighting-editor/{SightingEditorMessages_fr-DcRPYz1n.js → SightingEditorMessages_fr-CvRVAmAa.js} +2 -2
- package/dist-embed-sighting-editor/{SightingEditorMessages_it-DcmpHfvU.js → SightingEditorMessages_it--JZErvoc.js} +2 -2
- package/dist-embed-sighting-editor/{SightingFileEditor-SHzsGZVI.js → SightingFileEditor-BUpjvTYf.js} +10 -10
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +21 -57
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ContrailSystem-oqsCCklf.js","./ContrailGrowth-CuAzwIoc.js","./trafficRuntime-Ce_f9RDO.js","./ModelThumbnails-BMvmda-2.js","./ModelSource-BJHgjQd9.js","./ModelViewer-O9_A3wzF.js","./SightingFileEditor-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ContrailSystem-oqsCCklf.js","./ContrailGrowth-CuAzwIoc.js","./trafficRuntime-Ce_f9RDO.js","./ModelThumbnails-BMvmda-2.js","./ModelSource-BJHgjQd9.js","./ModelViewer-O9_A3wzF.js","./SightingFileEditor-BUpjvTYf.js","./sightingSchema-5AlscPkV.js","./BodyEditor-CiPDf3PA.js","./BodyEditorMessages_en-D6h_2jc7.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
const Kw="modulepreload",Zw=function(a,e){return new URL(a,e).href},Rg={},je=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){let r=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");n=r(t.map(h=>{if(h=Zw(h,i),h in Rg)return;Rg[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(!!i)for(let g=o.length-1;g>=0;g--){const m=o[g];if(m.href===h&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Kw,d||(f.as="script"),f.crossOrigin="",f.href=h,c&&f.setAttribute("nonce",c),document.head.appendChild(f),d)return new Promise((g,m)=>{f.addEventListener("load",g),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return n.then(r=>{for(const o of r||[])o.status==="rejected"&&s(o.reason);return e().catch(s)})};class wn{constructor(e){this.entries=e}static empty(){return new wn(new Map)}get size(){return this.entries.size}at(e){return this.entries.get(e)}paths(){return[...this.entries.keys()]}set(e,t){t.basis==="stated"&&t.rationale===void 0?this.entries.delete(e):this.entries.set(e,t)}clear(e){for(const t of this.entries.keys())(t===e||t.startsWith(`${e}.`))&&this.entries.delete(t)}static strip(e){const t=new wn(new Map);return{recording:wn.stripValue(e,[],t),provenance:t}}static restore(e,t){if(t.size===0)return e;const i=structuredClone(e);for(const n of t.paths()){const s=t.at(n),r=n.split("."),o=wn.holderOf(i,r);if(!o)continue;const l=r[r.length-1],c=o[l];c!==void 0&&(s.of!==void 0&&JSON.stringify(s.of)!==JSON.stringify(c)||(o[l]={value:c,...s.basis==="stated"?{}:{basis:s.basis},...s.rationale===void 0?{}:{rationale:s.rationale}}))}return i}static isWrapper(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"value"in e}static stripValue(e,t,i){return wn.isWrapper(e)?(i.set(t.join("."),{basis:e.basis??"stated",...e.rationale===void 0?{}:{rationale:e.rationale},of:e.value}),wn.stripValue(e.value,t,i)):Array.isArray(e)?e.map((n,s)=>wn.stripValue(n,[...t,String(s)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,wn.stripValue(s,[...t,n],i)])):e}static holderOf(e,t){let i=e;for(const n of t.slice(0,-1)){if(typeof i!="object"||i===null)return;i=i[n]}return typeof i=="object"&&i!==null?i:void 0}}class Es{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static isCase(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Array.isArray(e.events)&&!("timeline"in e)}static sightingUrls(e,t){return(e.events??[]).filter(i=>i.eventType===Es.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,t).href)}static interpretationEvents(e,t){return t?(e.events??[]).filter(i=>i.eventType===Es.INTERPRETATION_EVENT?i.sighting===t:i.eventType!==Es.SIGHTING_EVENT||i.interpretationOf===void 0?!1:[i.interpretationOf].flat().includes(t)).map(i=>i):[]}static async interpretationOf(e,t,i){if(e.bodies||e.reentries)return Es.withModelsFrom(wn.strip({title:e.title,bodies:e.bodies??[],smoke:e.smoke,reentries:e.reentries}).recording,t);if(!e.url)return{title:e.title,bodies:[]};const n=new URL(e.url,t).href,s=await i(n),r="timeline"in s&&s.interpretation?s.interpretation:s;return Es.withModelsFrom(wn.strip({title:e.title??r.title,bodies:r.bodies??[],smoke:r.smoke,reentries:r.reentries}).recording,n)}static withModelsFrom(e,t){return{...e,bodies:e.bodies.map(i=>i.model?.url?{...i,model:{...i.model,url:new URL(i.model.url,t).href}}:i)}}}class xa extends Error{constructor(e,t,i){super(`${e}: ${t}${i===void 0?"":` (HTTP ${i})`}`),this.kind=e,this.url=t,this.status=i,this.name="SightingFetchError"}}class Nc{static async json(e){const t=new URL(e,location.href);if(location.protocol==="https:"&&t.protocol==="http:")throw new xa("mixed-content",e);let i;try{i=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!i.ok)throw new xa("status",e,i.status);try{return await i.json()}catch{throw new xa("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new xa("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new xa("cors",e)}catch{return new xa("unreachable",e)}}}class qn{constructor(e){this.preferences=e}read(e){if(e===void 0||typeof e=="string")return e===""?void 0:e;for(const i of this.preferences){const n=e[i]??e[qn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>qn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(qn.base(i)))return n;return Object.values(e).find(i=>i)??void 0}write(e,t,i){const n=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return n;const s={...e},r=Object.keys(s).find(o=>o===i)??Object.keys(s).find(o=>qn.base(o)===qn.base(i))??i;return n===void 0?delete s[r]:s[r]=n,Object.keys(s).length===0?void 0:s}static base(e){return e.toLowerCase().split("-")[0]}}function Fc(a,e){for(const t of a){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class hs{static preferencesFor(e){const t=navigator.languages??[],i=this.declaredFor(e);return i?[i,...t]:t}static declaredFor(e){for(let t=e;t;){const i=t.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=t.getRootNode();t=n instanceof ShadowRoot?n.host:void 0}}}class bn{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(e){const t=e.trim().toUpperCase(),i=bn.ISO.exec(t);if(!i||t==="P"||t.endsWith("T"))return;const[,n,s,r,o,l]=i,c=d=>d===void 0?0:Number(d.replace(",",".")),h=c(n)*604800+c(s)*86400+c(r)*3600+c(o)*60+c(l);return Number.isFinite(h)?h:void 0}static parse(e){let t=e.trim();if(t==="")return;const i=t.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(t=t.slice(0,-1).trim());const s=t.split("/");if(s.length>2)return;const r=s.map(d=>bn.seconds(d));if(r.some(d=>d===void 0))return;const[o,l]=r,c=Math.min(o,l??o),h=Math.max(o,l??o);return{doubt:n,minSeconds:c,maxSeconds:h,chosenSeconds:(c+h)/2}}static isExact(e){const t=bn.parse(e);return t!==void 0&&t.doubt===""&&t.minSeconds===t.maxSeconds}static format(e){const t=Math.max(0,Math.round(e*10)/10),i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(e){const t=Math.round(e*10)/10;if(t<60)return`${t} s`;const i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%60*10)/10,r=[];return i>0&&r.push(`${i} h`),n>0&&r.push(`${n} min`),s>0&&r.push(`${s} s`),r.join(" ")}}class lt{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(e){return 2*Math.atan(e.sizeM/(2*e.distanceM))*180/Math.PI}static inMoons(e){return e/lt.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(e,t,i){if(!(!e||!t))return{widthDeg:e.widthDeg+(t.widthDeg-e.widthDeg)*i,heightDeg:e.heightDeg+(t.heightDeg-e.heightDeg)*i}}static sizeMAt(e,t){return 2*e*Math.tan(t*Math.PI/360)}static distanceMAt(e,t){return e/(2*Math.tan(t*Math.PI/360))}}function jw(a,e,t){if(!a||!e)return t<1?a:e;const i=((e.azimuthDeg-a.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((a.azimuthDeg+i*t)%360+360)%360,altitudeDeg:a.altitudeDeg+(e.altitudeDeg-a.altitudeDeg)*t}}function Jw(a,e="#39ff14"){return{kind:"oval",bounds:a,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function Qw(a,e,t="#39ff14"){return{kind:"polygon",bounds:a,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function e2(a,e="#39ff14"){const{width:t,height:i}=a;return Qw(a,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const t2={oval:Jw,polygon:e2};function Cg(a,e){return{...t2[e.presetId](a,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function i2(a,e,t){const{bounds:i}=a;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function Ay(a,e,t){const i=a.bounds.width,n=a.bounds.height;return{...a,bounds:{x:e-i/2,y:t-n/2,width:i,height:n}}}function Cn(a,e,t){return a+(e-a)*t}function Pg(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function n2(a){return`#${a.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function s2(a,e,t){const i=Pg(a),n=Pg(e);return!i||!n?t<1?a:e:n2([Cn(i[0],n[0],t),Cn(i[1],n[1],t),Cn(i[2],n[2],t)])}function r2(a,e,t){const i={x:Cn(a.bounds.x,e.bounds.x,t),y:Cn(a.bounds.y,e.bounds.y,t),width:Cn(a.bounds.width,e.bounds.width,t),height:Cn(a.bounds.height,e.bounds.height,t)},n=Cn(a.angle,e.angle,t),s=Cn(a.transparency,e.transparency,t),r=Cn(a.haloScale,e.haloScale,t),o=Cn(a.blur??0,e.blur??0,t),l=Cn(a.brightness??0,e.brightness??0,t),c=s2(a.color,e.color,t),h=lt.lerpAngular(a.angular,e.angular,t),d=jw(a.aim,e.aim,t);return a.kind==="polygon"&&e.kind==="polygon"&&a.points.length===e.points.length?{...a,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d,points:a.points.map((u,p)=>({x:Cn(u.x,e.points[p].x,t),y:Cn(u.y,e.points[p].y,t)}))}:{...t<1?a:e,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d}}class Ea{static DEFAULT_COLOR="#e8e6df";static complete(e,t=[]){const i=new Map;return e.map((n,s)=>({keyframe:n,index:s})).sort((n,s)=>n.keyframe.t-s.keyframe.t).map(({keyframe:n,index:s})=>({t:n.t,shapes:(n.shapes??[]).map((r,o)=>{const l=`timeline.keyframes.${s}.shapes.${o}.shape`,c=Ea.completed(r,i.get(r.sourceId),l,t);return i.set(r.sourceId,c),{sourceId:r.sourceId,shape:c}})}))}static completed(e,t,i,n){const s=e.shape??{},r=t??Ea.firstAppearance(s,i,n),o={...r};s.bounds&&t&&(t.aim||t.angular)&&!s.aim&&!s.angular&&n.push({kind:"pixels-over-angles",path:i}),s.bounds&&(s.aim||delete o.aim,s.angular||delete o.angular);const l=s.kind??r.kind??"oval",c={...o,...s,kind:l};if(l==="polygon"&&!c.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:d}=c.bounds;return{...c,points:[{x:0,y:0},{x:h,y:0},{x:h,y:d},{x:0,y:d}]}}return c}static firstAppearance(e,t,i){return e.kind||i.push({kind:"defaulted",path:`${t}.kind`,expected:'"oval"'}),e.color||i.push({kind:"defaulted",path:`${t}.color`,expected:`"${Ea.DEFAULT_COLOR}"`}),!e.bounds&&!e.aim&&i.push({kind:"unplaced",path:t}),!e.bounds&&!e.angular&&i.push({kind:"unsized",path:t}),{kind:e.kind??"oval",bounds:{...Ea.NEUTRAL_BOUNDS},color:Ea.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:lt.CANVAS_WIDTH_PX/2,y:lt.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Gu{keyframes=[];order=[];groups=[];addKeyframe(e,t){const i=this.findInsertIndex(e);if(this.keyframes[i]?.t===e){const n=new Set(t.map(s=>s.sourceId));this.keyframes[i]={t:e,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...t]}}else this.keyframes.splice(i,0,{t:e,shapes:[...t]});for(const n of t)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getKeyframeAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t];return i?.t===e?i:void 0}getShapeAt(e,t){return this.getKeyframeAt(e)?.shapes.find(i=>i.sourceId===t)?.shape}getLatestShapeAt(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return n.shape}}getInterpolatedShapeAt(e,t){const i=this.findShapeAtOrBefore(e,t);if(i?.t===e)return i.shape;const n=this.findShapeAtOrAfter(e,t);return i?n?r2(i.shape,n.shape,(e-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(e,t){for(let i=this.findInsertIndex(e);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(e,t,i,n){const s=this.sourceIds;for(let r=s.length-1;r>=0;r--){if(n?.has(s[r]))continue;const o=this.getInterpolatedShapeAt(e,s[r]);if(o&&i2(o,t,i))return{sourceId:s[r],shape:o}}}removeSource(e){for(let t=this.keyframes.length-1;t>=0;t--){const i=this.keyframes[t].shapes.filter(n=>n.sourceId!==e);i.length===0?this.keyframes.splice(t,1):i.length!==this.keyframes[t].shapes.length&&(this.keyframes[t]={t:this.keyframes[t].t,shapes:i})}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(i=>i.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(n=>n.includes(e));if(t===-1)return;const i=this.groups[t].filter(n=>n!==e);i.length<2?this.groups.splice(t,1):this.groups[t]=i}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,t){const i=new Gu;for(const n of Ea.complete(e.keyframes??[],t))i.addKeyframe(n.t,n.shapes);if(e.order){const n=i.order.filter(s=>!e.order.includes(s));i.order=[...e.order,...n]}return e.groups&&(i.groups=e.groups.map(n=>n.filter(s=>i.order.includes(s))).filter(n=>n.length>=2)),i}}function a2(a,e,t){return Math.max(e,Math.min(t,a))}function o2(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function bo(a,e,t){return a+(e-a)*t}function l2(a,e,t){return{lat:a.lat===void 0||e.lat===void 0?void 0:bo(a.lat,e.lat,t),lng:a.lng===void 0||e.lng===void 0?void 0:bo(a.lng,e.lng,t),elevationM:bo(a.elevationM,e.elevationM,t),headingDeg:a.headingDeg===void 0||e.headingDeg===void 0?void 0:o2(a.headingDeg,e.headingDeg,t),pitchDeg:bo(a.pitchDeg,e.pitchDeg,t),rollDeg:bo(a.rollDeg??0,e.rollDeg??0,t),fovDeg:bo(a.fovDeg,e.fovDeg,t),fNumber:a.fNumber,focusDistanceM:a.focusDistanceM,filter:a.filter}}class Qa{static at(e,t,i,n,s){const r=e[i],l=e[i+1]-r;if(l<=0)return t[i];const c=Qa.tangent(e,t,i,s),h=Qa.tangent(e,t,i+1,s),d=(n-r)/l,u=d*d,p=u*d;return(2*p-3*u+1)*t[i]+(p-2*u+d)*l*c+(-2*p+3*u)*t[i+1]+(p-u)*l*h}static BRAKE_S=.8;static paced(e,t,i,n){if(!i&&!n)return e;const s=t>0?Math.min(.5,Qa.BRAKE_S/t):.5;if(i&&n){const o=1/(1-s);return e<=s?o*e*e/(2*s):e>=1-s?1-o*(1-e)*(1-e)/(2*s):o*(e-s/2)}const r=o=>{const l=1/(1-s/2);if(o<=1-s)return l*o;const c=o-(1-s);return l*(1-s)+l*(c-c*c/(2*s))};return n?r(e):1-r(1-e)}static tangent(e,t,i,n){const s=e.length-1,r=p=>(t[p+1]-t[p])/(e[p+1]-e[p]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const o=r(i-1),l=r(i);if(o*l<=0)return 0;const c=e[i]-e[i-1],h=e[i+1]-e[i],d=2*h+c,u=h+2*c;return(d+u)/(d/o+u/l)}}class Uc{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,pose:t}:this.keyframes.splice(i,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,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}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),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.pose;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.pose;if(!n)return i.pose;const s=l2(i.pose,n.pose,a2((e-i.t)/(n.t-i.t),0,1));return this.humanly(t-1,e,s)}humanly(e,t,i){const n=Math.max(0,e-1),s=Math.min(this.keyframes.length-1,e+2),r=this.keyframes.slice(n,s+1),o=e-n,l=r.map(y=>y.t),c=(y,b)=>{const w=r.map(S=>y(S.pose));if(!w.some(S=>S===void 0))return Qa.at(l,w,o,t,b)},h=r.map(y=>y.pose.headingDeg);let d;if(h.every(y=>y!==void 0)){const y=[h[0]];for(let b=1;b<h.length;b++)y.push(y[b-1]+((h[b]-h[b-1])%360+540)%360-180);d=(Qa.at(l,y,o,t,!0)%360+360)%360}const u=this.keyframes[e],p=this.keyframes[e+1],f=(y,b)=>y.lat===b.lat&&y.lng===b.lng&&y.elevationM===b.elevationM,g=!f(u.pose,p.pose),m=g&&e>0&&f(this.keyframes[e-1].pose,u.pose),v=g&&e+2<this.keyframes.length&&f(p.pose,this.keyframes[e+2].pose);let x;if(m||v){const y=Qa.paced((t-u.t)/(p.t-u.t),(p.t-u.t)/1e3,m,v),b=(w,S)=>w===void 0||S===void 0?void 0:w+(S-w)*y;x={lat:b(u.pose.lat,p.pose.lat),lng:b(u.pose.lng,p.pose.lng),elevationM:b(u.pose.elevationM,p.pose.elevationM)}}return{...i,lat:x?x.lat:c(y=>y.lat,!1)??i.lat,lng:x?x.lng:c(y=>y.lng,!1)??i.lng,elevationM:x?x.elevationM:c(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:c(y=>y.pitchDeg,!0)??i.pitchDeg,rollDeg:c(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:c(y=>y.fovDeg,!0)??i.fovDeg}}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 Uc;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class $r{static MAX_CHANGE_PER_S=.05;points;followed;constructor(e){let t="none",i=0;this.points=e.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(t=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:t,lastFallingIntensity:i,intensity:s.precipitationType==="none"?0:s.precipitationIntensity,type:s.precipitationType})),this.followed=[];for(let n=0;n<this.points.length;n++){if(n===0){this.followed.push(this.points[0].intensity);continue}const s=this.points[n-1],r=this.points[n];this.followed.push($r.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(e){if(this.points.length===0||e<this.points[0].t)return;let t=this.points.length-1;for(;t>0&&this.points[t].t>e;)t--;const i=this.points[t],n=this.points[t+1],s=n?$r.follow(this.followed[t],i.intensity,n.intensity,(n.t-i.t)/1e3,(e-i.t)/1e3):$r.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:$r.typeBetween(i,n,e,s),intensity:s,character:$r.characterBetween(i,n,e)}}static characterBetween(e,t,i){return e.type==="none"?t&&t.type!=="none"?t.intensity:e.lastFallingIntensity:!t||t.type==="none"?e.intensity:e.intensity+(t.intensity-e.intensity)*(i-e.t)/(t.t-e.t||1)}static typeBetween(e,t,i,n){return e.type==="none"?t&&t.type!=="none"&&i>e.t?t.type:n>0?e.lastFalling:"none":t&&t.type==="none"&&n<=0?"none":e.type}static follow(e,t,i,n,s){const r=$r.MAX_CHANGE_PER_S,o=n>0?(i-t)/n:0,l=d=>t+o*Math.min(Math.max(d,0),n);let c=e,h=0;for(let d=0;d<8&&h<s;d++){const u=l(h)-c;if(Math.abs(u)<1e-9){const y=h<n?o:0;if(Math.abs(y)<=r){const w=h<n?Math.min(s,n):s;c=l(w),h=w;continue}const b=Math.min(s,n);c+=Math.sign(y)*r*(b-h),h=b;continue}const p=Math.sign(u),f=h<n?o:0,g=r-p*f,m=g>0?h+Math.abs(u)/g:1/0,v=h<n?n:1/0,x=Math.min(s,m,v);c+=p*r*(x-h),h=x,x===m&&(c=l(h))}return Math.min(1,Math.max(0,c))}}const xm=1e3,Od=.65,Vu={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function Ks(a){if(a.cloudLayers!==void 0)return a.cloudLayers;const e=[],t=a.lowerCloudCover??a.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:a.cloudBaseM??xm,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:a.cloudDarkness}),(a.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:a.highCloudCover,sizeM:2200,density:.35,darkness:a.cloudDarkness,iceCrystalAlignment:a.iceCrystalAlignment}),e}function ii(a,e,t){return a+(e-a)*t}function Sm(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function c2(a,e,t){return Math.max(e,Math.min(t,a))}function h2(a=[],e=[],t){if(!(!a.length&&!e.length))return[...new Set([...a.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const n=a.find(l=>l.id===i),s=e.find(l=>l.id===i),r=n??{...s,density:0},o=s??{...n,density:0};return{...r,eastM:ii(r.eastM,o.eastM,t),northM:ii(r.northM,o.northM,t),baseM:ii(r.baseM,o.baseM,t),thicknessM:ii(r.thicknessM,o.thicknessM,t),widthM:ii(r.widthM,o.widthM,t),depthM:ii(r.depthM,o.depthM,t),rotationDeg:Sm(r.rotationDeg,o.rotationDeg,t),density:ii(r.density,o.density,t),darkness:ii(r.darkness??0,o.darkness??0,t)}})}function d2(a,e,t){if(a.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=Ks(a),n=Ks(e);return t>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const o=i.find(d=>d.id===r),l=n.find(d=>d.id===r),c=o??{...l,coverage:0},h=l??{...o,coverage:0};return{...c,instances:h2(o?.instances,l?.instances,t),baseM:ii(c.baseM,h.baseM,t),thicknessM:ii(c.thicknessM,h.thicknessM,t),coverage:ii(c.coverage,h.coverage,t),sizeM:ii(c.sizeM,h.sizeM,t),density:ii(c.density,h.density,t),darkness:ii(c.darkness??a.cloudDarkness,h.darkness??e.cloudDarkness,t),iceCrystalAlignment:c.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:ii(c.iceCrystalAlignment,h.iceCrystalAlignment,t),windSpeed:c.windSpeed===void 0&&h.windSpeed===void 0?void 0:ii(c.windSpeed??a.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:c.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:Sm(c.windDirectionDeg??a.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function u2(a,e,t){return{cloudLayers:d2(a,e,t),cloudCover:ii(a.cloudCover,e.cloudCover,t),cloudDarkness:ii(a.cloudDarkness,e.cloudDarkness,t),highCloudCover:a.highCloudCover===void 0||e.highCloudCover===void 0?void 0:ii(a.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:a.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:ii(a.iceCrystalAlignment,e.iceCrystalAlignment,t),lowerCloudCover:a.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:ii(a.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:a.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:ii(a.cloudBaseM,e.cloudBaseM,t),relativeHumidity:a.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:ii(a.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?a.precipitationType:e.precipitationType,precipitationIntensity:ii(a.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:Sm(a.windDirectionDeg,e.windDirectionDeg,t),windSpeed:ii(a.windSpeed,e.windSpeed,t),storm:t<1?a.storm:e.storm}}class Bc{keyframes=[];ramp;addKeyframe(e,t){this.ramp=void 0;const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,weather:t}:this.keyframes.splice(i,0,{t:e,weather:t})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(e){this.ramp=void 0;const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}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),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.weather;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return i?n?u2(i.weather,n.weather,c2((e-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(e){const t=this.getInterpolatedWeatherAt(e);if(!t)return;const i=(this.ramp??=new $r(this.keyframes)).at(e);if(!i)return t;const{type:n,intensity:s,character:r}=i,o=r>0?Math.min(1,s/r):n==="none"?0:1;return{...t,precipitationType:n,precipitationIntensity:r,precipitationAmount:o}}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 Bc;for(const i of e.keyframes)t.addKeyframe(i.t,{...Vu,...i.weather});return t}}class zc{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,sound:t}:this.keyframes.splice(i,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),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.sound;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.sound;if(!n)return i.sound;const s=(e-i.t)/(n.t-i.t);return this.lerp(i.sound,n.sound,Math.max(0,Math.min(1,s)))}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 zc;for(const i of e.keyframes)t.addKeyframe(i.t,i.sound);return t}lerp(e,t,i){return{kind:i<1?e.kind:t.kind,volume:e.volume+(t.volume-e.volume)*i,pitchHz:e.pitchHz+(t.pitchHz-e.pitchHz)*i,src:i<1?e.src:t.src}}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}}const p2=["none","hum","whistle","rumble","crackle"],f2=100,m2={kind:"none",volume:0,pitchHz:f2},dh=[{id:"eye",name:"Naked eye",flare:0,projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",name:"Camera, unknown device",projection:"rectilinear",fNumber:8,fNumberRange:{min:2,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:8},apertureBlades:6},{id:"roamer-1-120",name:"Roamer 1, 120 film",projection:"rectilinear",frame:{widthMm:74,heightMm:60,focalLengthMm:100},fNumber:11,exposureSeconds:1/50,years:{from:1930,to:1965},detailUm:40,medium:{kind:"negative",iso:125}},{id:"instamatic-126",name:"Instamatic, 126 film",projection:"rectilinear",frame:{widthMm:28,heightMm:28,focalLengthMm:43},fNumber:11,exposureSeconds:1/90,years:{from:1963,to:1988},apertureBlades:5,detailUm:20,medium:{kind:"negative",iso:64}},{id:"slr-35mm-50",name:"35 mm SLR, 50 mm lens",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:50},fNumber:8,fNumberRange:{min:2,max:16},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},years:{from:1959},apertureBlades:6,detailUm:20,medium:{kind:"negative",iso:100}},{id:"slr-35mm-zoom",name:"35 mm SLR, 70-210 mm zoom",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:135,focalRangeMm:{minMm:70,maxMm:210}},fNumber:8,fNumberRange:{min:4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},apertureBlades:8,years:{from:1975},detailUm:20,medium:{kind:"negative",iso:100}},{id:"phone-landscape",name:"Phone, held sideways",projection:"rectilinear",frame:{widthMm:7.6,heightMm:5.7,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0}},{id:"phone-portrait",name:"Phone, held upright",projection:"rectilinear",frame:{widthMm:5.7,heightMm:7.6,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0}}];class Rt{static get default(){return dh[0]}static byId(e){return dh.find(t=>t.id===e)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(e){const t=e.frame;return t?2*Math.atan(t.heightMm/(2*t.focalLengthMm))*180/Math.PI:Rt.UNAIDED_FIELD_DEG}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:Rt.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*Rt.aspectOf(e))}static availableAt(e){return e===void 0?dh:dh.filter(t=>!t.years||e>=t.years.from&&(t.years.to===void 0||e<=t.years.to))}static fieldOfViewDegAt(e,t){const i=e.frame;if(!(!i||t<=0))return 2*Math.atan(i.heightMm/(2*t))*180/Math.PI}static focalLengthMmFor(e,t){const i=e.frame;if(!(!i||t<=0||t>=180))return i.heightMm/(2*Math.tan(t*Math.PI/360))}static bladesShowing(e,t){const i=t??e.fNumber;if(i===void 0||e.apertureBlades===void 0)return 0;const n=e.fNumberRange;return!n||n.max<=n.min?1:Math.max(0,Math.min(1,(i-n.min)/(n.max-n.min)))}static LENS_FLARE_ARTIFACTS=1;static flareArtifactsOf(e){return e.flare??Rt.LENS_FLARE_ARTIFACTS}static starPointsOf(e){const t=e.apertureBlades;return t===void 0||t<3?0:t%2===0?t:t*2}}class lo extends Error{}class Wu{constructor(e){this.name=e}validate(e){return!0}}class Ty extends Wu{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new lo(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new lo(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Ri{name;min;max;duration;subUnit;validator;constructor(e,t,i,n,s=new Ty(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class Iy{millisecond;second;minute;hour;day;month;year}class g2 extends Iy{}class Dy extends g2{millisecond=new Ri("millisecond",0,999,void 0);second=new Ri("second",0,59,this.millisecond);minute=new Ri("minute",0,59,this.second);hour=new Ri("hour",0,23,this.minute);day=new Ri("day",1,31,this.hour);month=new Ri("month",1,12,this.day);year=new Ri("year",0,9999,this.month)}const Ze=new Dy;class v2 extends Ty{constructor(e=1,t=12){super("month",e,t)}}class Zs{static instance=new Zs;render(e){return e.value.toString()}}class ln{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new Wu(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=Zs.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Yt{static#e=new Map;static register(e,t){Yt.#e.set(e,t)}static get(e){const t=Yt.#e.get(e);if(!t)throw new lo(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class Nd extends ln{constructor(e=new Date().getFullYear(),t=Ze.year){super(e,t)}static fromString(e,t=Yt.get(Nd)){return new Nd(t.parse(e))}}class lr extends Zs{static default=new lr("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class Fd extends ln{constructor(e=new Date().getMonth()+1,t=Ze.month){super(e,t)}static fromString(e,t=Yt.get(Fd)){return new Fd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class Ud extends ln{constructor(e=new Date().getDate(),t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Ud)){const i=t.parse(e);return new Ud(i)}toString(e=lr.default){return super.toString(e)}}class Bd extends ln{constructor(e=new Date().getHours(),t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Bd)){return new Bd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class zd extends ln{constructor(e=new Date().getMinutes(),t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(zd)){return new zd(t.parse(e))}toString(e=lr.default){return super.toString(e)}}class Hd extends ln{constructor(e=new Date().getSeconds(),t=Ze.second){super(e,t)}static fromString(e,t=Yt.get(Hd)){return new Hd(t.parse(e),Ze.second)}toString(e=lr.default){return super.toString(e)}}class fo extends ln{static renderer=new lr("0",3);constructor(e,t=Ze.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=fo.renderer){return super.toString(e)}}class b2{render(e){return e.toString()}}class y2 extends b2{render(e){const t=e.value,i=Math.abs(t),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=t<0?"-":"+",o=n.toString().padStart(2,"0"),l=s>0?":"+s.toString().padEnd(2,"0"):"";return r+o+l}}}class _l{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=Yt.get(_l),i=void 0){const n=t.parse(e,i);return new _l(n)}toString(e=new y2){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class sn{static timeshift(e,t){return e+(sn.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:n}=e,s=e.hour??12;if(![t,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=sn.rule(t);if(!r)return!1;const o=sn.rank(i,n,s);return o>=sn.rank(r.start.month,r.start.day,2)&&o<sn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:sn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:sn.sunday(e,3,2)},end:{month:11,day:sn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:sn.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:sn.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const n=new Date(Date.UTC(2e3,t-1,1));n.setUTCFullYear(e);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,sn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let o=s;for(;o+7<=r;)o+=7;return o}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const M2={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},w2={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},x2={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},S2={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},E2={name:"PT",timeshift:a=>sn.timeshift(-480,a),title:"Pacific Time (US)"},_2={name:"MT",timeshift:a=>sn.timeshift(-420,a),title:"Mountain Time (US)"},A2={name:"CT",timeshift:a=>sn.timeshift(-360,a),title:"Central Time (US)"},T2={name:"ET",timeshift:a=>sn.timeshift(-300,a),title:"Eastern Time (US)"},I2={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},D2={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},R2={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},C2={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},P2={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},L2={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},k2={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},O2={name:"Z",timeshift:"Z",title:"UTC"},N2={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},F2={name:"BST",timeshift:"+01",title:"British Summer Time"},U2={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},B2={name:"CET",timeshift:"+01",title:"Central European Time"},z2={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},H2={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},G2={name:"BJT",timeshift:"+08",title:"Beijing Time"},V2={name:"CST",timeshift:"-06",title:"Central Standard Time"},W2={name:"JST",timeshift:"+09",title:"Japan Standard Time"},X2={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},$2={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},Y2={name:"LST",timeshift:"?",title:"Local Sideral Time"},Lg=[L2,X2,P2,G2,F2,V2,D2,B2,U2,A2,I2,C2,R2,T2,N2,H2,W2,Y2,x2,z2,S2,_2,$2,w2,M2,E2,k2,O2];class Xu{static instance=new Xu;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const n=t.join("-"),s=e.timeshift?e.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class Sa extends lo{constructor(e="method is abstract"){super(e)}}class Em{units;constructor(e){this.units=e}newYear(e){throw new Sa}newMonth(e){throw new Sa}newDay(e){throw new Sa}newHour(e){throw new Sa}newMinute(e){throw new Sa}newSecond(e){throw new Sa}}class q2 extends Iy{millisecond=new Ri("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Ri("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ri("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Ri("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Ri("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Ri("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Ri("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const _m=new q2;class Am{static instance=new Am;render(e){const t=La.toSpec(e);let i="P";const n=t.years;n&&(i+=n.toString()+"Y");const s=t.months;s&&(i+=s.toString(Zs.instance)+"MM");const r=t.days;r&&(i+=r.toString(Zs.instance)+"D");const o=t.hours;o&&(i+=o.toString(Zs.instance)+"H");const l=t.minutes;l&&(i+=l.toString(Zs.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(Zs.instance)+"S"),i}}class La extends ln{constructor(e={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof e=="number"?e:+(e.years?e.years*Ze.year.duration:0)+(e.months?e.months*Ze.month.duration:0)+(e.days?e.days*Ze.day.duration:0)+(e.hours?e.hours*Ze.hour.duration:0)+(e.minutes?e.minutes*Ze.minute.duration:0)+(e.seconds?e.seconds*Ze.second.duration:0)},new Ri("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=Z2){let i=typeof e=="number"?e:e.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/Ze.year.duration,o=Math.floor(r);o>0&&(s.years=t.newYear(n*o),i-=o*Ze.year.duration);const l=i/Ze.month.duration,c=Math.floor(l);c>0&&(s.months=t.newMonth(n*c),i-=c*Ze.month.duration);const h=i/Ze.day.duration,d=Math.floor(h);d>0&&(s.days=t.newDay(n*d),i-=d*Ze.day.duration);const u=i/Ze.hour.duration,p=Math.floor(u);p>0&&(s.hours=t.newHour(n*p),i-=p*Ze.hour.duration);const f=i/Ze.minute.duration,g=Math.floor(f);g>0&&(s.minutes=t.newMinute(n*g),i-=g*Ze.minute.duration);const m=i/Ze.second.duration,v=Math.floor(n*m);return v>0&&(s.seconds=t.newSecond(v)),s}static fromString(e,t=Yt.get(La)){return new La(t.parse(e))}static between(e,t){const i=t.getTime(),n=e.getTime();return new La(i-n)}toSpec(){return La.toSpec(this)}toString(e=Am.instance){return e.render(this)}}class Ry extends Em{constructor(e){super(e)}newYear(e){return new Nd(e,this.units.year)}newMonth(e){return new Fd(e,this.units.month)}newDay(e){return new Ud(e,this.units.day)}newHour(e){return new Bd(e,this.units.hour)}newMinute(e){return new zd(e,this.units.minute)}newSecond(e){return new Hd(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new _l(typeof e=="number"?e:e.value)}}const K2=new Ry(Ze),Z2=new Ry(_m);class ws{#e;#t;#i;#n;#s;#r;#a;#o;constructor(e={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:ws.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof ln?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof ln?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof ln?e:this.factory.newDay(e)}get hour(){return this.#n}set hour(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newHour(e):!e||e.start||e instanceof ln?e:this.factory.newHour(e)}get minute(){return this.#s}set minute(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newMinute(e):!e||e.start||e instanceof ln?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof ln?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof ln)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof _l)?this.factory.newTimeshift(e):e}get factory(){return K2}static fromString(e,t=Yt.get(ws)){const{year:i,month:n,day:s,hour:r,minute:o,second:l,millisecond:c,timeshift:h}=t.parse(e);return new ws({year:i,month:n,day:s,hour:r,minute:o,second:l,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new ws({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return ws.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new Wu(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#l(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new La(t)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new ws(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Xu.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const n=this.day?.toSpec();n&&(e.day=n);const s=this.hour?.toSpec();s&&(e.hour=s);const r=this.minute?.toSpec();r&&(e.minute=r);const o=this.second?.toSpec();o&&(e.second=o);const l=this.millisecond?.toSpec();l&&(e.millisecond=l);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class ih extends Zs{static instance=new ih(lr.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class mo extends ln{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=ih.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class Cy extends Dy{year=new Ri("year",-9999,9999,this.month);yearExtended=new Ri("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const bd=new Cy;class ka extends mo{constructor(e,t=bd.year){super(e,t)}static fromString(e,t=bd.year,i=Yt.get(ka)){const n=i.parse(e),s=n.value.start;if(e.startsWith("Y")&&(t=bd.yearExtended),s!==void 0){const r=new ka(Object.assign({...n},{value:Math.max(s,t.min)})),o=new ka(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:o}}else return new ka(n,t)}}class Py extends Wu{monthValidator=new v2;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class Oa extends mo{constructor(e,t=new Ri(Ze.month.name,1,24,Ze.day,new Py)){super(e,t)}static fromString(e,t=Yt.get(Oa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.month;const r=new Oa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Oa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Oa(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Na extends mo{constructor(e,t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Na)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.day;const r=new Na(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Na(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Na(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Fa extends mo{constructor(e,t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Fa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=Ze.hour;const r=new Fa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Fa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Fa(i)}}class Ua extends mo{constructor(e,t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(Ua)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.minute,r=new Ua(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ua(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ua(i)}toString(e=ih.instance){return super.toString(e)}}class Ba extends mo{constructor(e,t=Ze.second){super(e,t)}static fromString(e,t=Yt.get(Ba)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.second,r=new Ba(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ba(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ba(i)}}class Al extends _l{static fromString(e,t=Yt.get(Al),i=void 0){return new Al(t.parse(e,i))}}class Ly extends Em{constructor(e){super(e)}newYear(e){return new ka(e,this.units.year)}newMonth(e){return new Oa(e,this.units.month)}newDay(e){return new Na(e,this.units.day)}newHour(e){return new Fa(e,this.units.hour)}newMinute(e){return new Ua(e,this.units.minute)}newSecond(e){return new Ba(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new Al(typeof e=="number"?e:e.value)}}const j2=new Ly(bd);new Ly(_m);class _a extends ws{constructor(e){super(e)}get factory(){return j2}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(e){return new _a({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static fromString(e,t=Yt.get(_a)){const i=t.parse(e);return new _a(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return _a.fromString(i)}clone(){return new _a(this.toSpec())}}class Ul extends mo{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class J2 extends Cy{year=new Ri("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Hf=new J2;class za extends Ul{constructor(e,t=Hf.year){super(e,t)}static fromString(e,t=Hf.year,i=Yt.get(za)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new za(Object.assign({...n},{value:Math.max(s,t.min)})),o=new za(Object.assign({...n},{value:Math.min(n.value.end,t.max)})),l={start:r,end:o},c=n.value.estimate;return c&&(l.estimate=c),l}else return new za(n)}}class Q2 extends Py{validate(e){switch(e){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(e)}}}class Ha extends Ul{constructor(e,t=new Ri(Ze.month.name,1,41,Ze.day,new Q2)){super(e,t)}static fromString(e,t=Yt.get(Ha)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.month,r=new Ha(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ha(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ha(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Ga extends Ul{constructor(e,t=Ze.day){super(e,t)}static fromString(e,t=Yt.get(Ga)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.day,r=new Ga(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Ga(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Ga(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Va extends Ul{constructor(e,t=Ze.hour){super(e,t)}static fromString(e,t=Yt.get(Va)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.hour,r=new Va(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Va(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Va(i)}}class Wa extends Ul{constructor(e,t=Ze.minute){super(e,t)}static fromString(e,t=Yt.get(Wa)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=Ze.minute,r=new Wa(Object.assign({...i},{value:Math.max(n,s.min)})),o=new Wa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:o}}else return new Wa(i)}}class Xa extends Ul{constructor(e,t=Ze.second){super(e,t)}static fromString(e,t=Ze.second,i=Yt.get(Xa)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new Xa(Object.assign({...n},{value:Math.max(s,t.min)})),o=new Xa(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:o}}else return new Xa(n,t)}}class ky extends Al{}class ex extends ih{qualifier(){return""}}class Yr extends Xu{static instance=new Yr;static valueRenderer=new ex(lr.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],n=Yr.names.slice(Yr.names.indexOf(t)+1).map(o=>e[o]).filter(Boolean),s=Yr.qualifier(i.uncertainComponent,i.approximateComponent),r=Yr.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(o=>o.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(o=>o.approximate));return s+i.toString(Yr.valueRenderer)+r}}class Oy extends Em{constructor(e){super(e)}newYear(e){return new za(e,this.units.year)}newMonth(e){return new Ha(e,this.units.month)}newDay(e){return new Ga(e,this.units.day)}newHour(e){return new Va(e,this.units.hour)}newMinute(e){return new Wa(e,this.units.minute)}newSecond(e){return new Xa(e,this.units.second)}newMillisecond(e){return new fo(e,this.units.millisecond)}newTimeshift(e){return new ky(typeof e=="number"?e:e.value)}}const tx=new Oy(Hf);new Oy(_m);class Aa extends _a{constructor(e){super(e)}toString(e=Yr.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return tx}static fromDate(e){return new Aa({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:ws.timeshiftOf(e)})}static fromString(e,t=Yt.get(Aa)){const i=t.parse(e);return new Aa(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Aa.fromString(i)}clone(){return new Aa(this.toSpec())}}class $u{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new lo(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Sa(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class Tm extends $u{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return Tm.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new lo(`${this.name} cannot be negative`);return super.parse(e)}}class ae{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return ae.optional(ae.group(e,...t))}static optionalNonCapturingGroup(...e){return ae.optional(ae.nonCapturingGroup(...e))}static numberGroup(e,t,i,n="\\d"){return ae.group(e,`${i||""}[${n}]${t}`)}}const kg="timeshiftValue",Og="shiftHour",Ng="shiftMinute";class Im extends $u{static format(e=""){return Lg.map(t=>t.name).join("|")+"|"+ae.nonCapturingGroup(ae.group(e+Og,ae.numberGroup(ae.groupName(e,kg),"{2}","[+-]")),ae.optionalNonCapturingGroup(":?",ae.numberGroup(ae.groupName(e,Ng),"{2}",void 0)))}constructor(){super(kg,Im.format())}parse(e,t){let i=0;const n=Lg.find(s=>s.name===e);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(t??{})}catch(s){throw new lo(`The time zone ${e} depends on the date: ${s.message}`)}e=n.timeshift}if(e!=="Z"){const s=this.regexGroups(e),r=s[Og];r&&(i+=parseInt(r,10)*60);const o=s[Ng];o&&(i+=parseInt(o,10))}return i}}class di extends Tm{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=di.uncertainGroup+di.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return ae.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(ae.groupName(di.uncertainGroup,e),"?")+this.qualifierFormat(ae.groupName(di.approximateGroup,e),"~")+this.qualifierFormat(ae.groupName(di.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return ae.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let n=0,s;for(s=0;s<t.length;s++){const c=t[s];if(c==="X")break;n=n*10+parseInt(c,10)}if(s<t.length){let c=1;for(let u=0;u<t.length-s;u++)c*=10;const h=i*n*c,d=h+c-1;n={start:h,end:d}}else n*=i;const r=e[ae.groupName(di.uncertainAndApproximateGroup,this.name)],o=e[ae.groupName(di.approximateGroup,this.name)]||r,l=e[ae.groupName(di.uncertainGroup,this.name)]||r;return{value:n,approximate:o?!!o:!1,uncertain:l?!!l:!1}}}const Fg="yearValue";class Gd extends di{constructor(){super(Fg,Gd.format())}static format(e=""){return"Y?"+di.numberFormat(ae.groupName(e,Fg),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const Ug="monthValue";class Vd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Ug),"{1,2}",void 0)}constructor(){super(Ug,Vd.format())}}const Bg="dayValue";class Wd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Bg),"{1,2}",void 0)}constructor(){super(Bg,Wd.format())}}const zg="hourValue";class Xd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,zg),"{1,2}",void 0)}constructor(){super(zg,Xd.format())}}const Hg="minuteValue";class $d extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Hg),"{1,2}",void 0)}constructor(){super(Hg,$d.format())}}const Gg="secondValue";class Yd extends di{static format(e=""){return di.numberFormat(ae.groupName(e,Gg),"{1,2}",void 0)}constructor(){super(Gg,Yd.format())}}class qd extends Im{}class Li extends $u{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(e=Li.format()){super("date",e)}static format(e=""){return ae.group(ae.groupName(e,Li.yearGroup),Gd.format(e))+ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,Li.monthGroup),Vd.format(e)),ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,Li.dayGroup),Wd.format(e)),ae.optionalNonCapturingGroup("[T ]",ae.group(ae.groupName(e,Li.hourGroup),Xd.format(e)),":",ae.group(ae.groupName(e,Li.minuteGroup),$d.format(e)),ae.optionalNonCapturingGroup(":",ae.group(ae.groupName(e,Li.secondGroup),Yd.format(e)),ae.optionalNonCapturingGroup("[.,]",ae.group(ae.groupName(e,Li.millisecondGroup),"\\d+"))),ae.optionalGroup(ae.groupName(e,Li.timeshiftGroup),qd.format(e)))))}parseGroups(e){const t=e[Li.millisecondGroup],i=t?fo.parseFraction(t):void 0,n=e[Li.secondGroup],s=n?Ba.fromString(n,new Yd):void 0,r=e[Li.minuteGroup];let o;r&&(o=Ua.fromString(r,new $d),o.uncertain=o.uncertain||s?.uncertain||!1,o.approximate=o.approximate||s?.approximate||!1);const l=e[Li.hourGroup];let c;l&&(c=Fa.fromString(l,new Xd),c.uncertain=c.uncertain||o?.uncertain||!1,c.approximate=c.approximate||o?.approximate||!1);const h=e[Li.dayGroup];let d;h&&(d=Na.fromString(h,new Wd),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[Li.monthGroup];let p;u&&(p=Oa.fromString(u,new Vd),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Li.yearGroup];let g;f&&(g=ka.fromString(f,void 0,new Gd),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[Li.timeshiftGroup],v=m?Al.fromString(m,new qd,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:o,second:s,millisecond:i,timeshift:v}}}class _i extends di{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=_i.uncertainGroup+_i.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(ae.groupName(_i.uncertainGroup,e),"?")+this.qualifierFormat(ae.groupName(_i.approximateGroup,e),"~")+this.qualifierFormat(ae.groupName(_i.uncertainAndApproximateGroup,e),"%")+di.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[ae.groupName(_i.uncertainAndApproximateGroup,this.name)];return(e[ae.groupName(_i.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[ae.groupName(_i.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Vl="yearValue",Vg="exp",Wg="signif";class Kd extends _i{constructor(){super(Vl,Kd.format())}static format(e=""){return"Y?"+ae.nonCapturingGroup(ae.group(ae.groupName(e,Vg),"[-]?\\d+E\\d+")+"|"+_i.numberFormat(ae.groupName(e,Vl),"+","[-]?")+ae.optionalGroup(ae.groupName(e,Wg),"S\\d+"))}parseGroups(e){const t=e[Vg];if(t){const r=t.indexOf("E"),o=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,o);e[Vl]=c.toString()}const i=e[Wg],n=e[Vl];if(i){const r=parseInt(i.substring(1),10),{valueStr:o,sign:l}=this.getValueAndSign(e);let c="";for(let h=0;h<o.length;h++)c+=h<r?o.charAt(h):"X";e[Vl]=(l<0?"-":"")+c}const s=super.parseGroups(e);return i&&(s.value.estimate=parseInt(n,10)),s}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const Xg="monthValue";class Zd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Xg),"{1,2}",void 0)}constructor(){super(Xg,Zd.format())}}const $g="dayValue";class jd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,$g),"{1,2}",void 0)}constructor(){super($g,jd.format())}}const Yg="hourValue";class Jd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Yg),"{1,2}",void 0)}constructor(){super(Yg,Jd.format())}}const qg="secondValue";class Qd extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,qg),"{1,2}",void 0)}constructor(){super(qg,Qd.format())}}const Kg="minuteValue";class eu extends _i{static format(e=""){return _i.numberFormat(ae.groupName(e,Kg),"{1,2}",void 0)}constructor(){super(Kg,eu.format())}}class ix extends qd{}class ki extends $u{static yearGroup=Li.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",ki.format())}static format(e=""){return ae.group(ae.groupName(e,ki.yearGroup),Kd.format(e))+ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,ki.monthGroup),Zd.format(e)),ae.optionalNonCapturingGroup("-",ae.group(ae.groupName(e,ki.dayGroup),jd.format(e)),ae.optionalNonCapturingGroup("[T ]",ae.group(ae.groupName(e,ki.hourGroup),Jd.format(e)),":",ae.group(ae.groupName(e,ki.minuteGroup),eu.format(e)),ae.optionalNonCapturingGroup(":",ae.group(ae.groupName(e,ki.secondGroup),Qd.format(e)),ae.optionalNonCapturingGroup("[.,]",ae.group(ae.groupName(e,ki.millisecondGroup),"\\d+"))),ae.optionalGroup(ae.groupName(e,ki.timeshiftGroup),ix.format(e)))))}parseGroups(e){const t=e[ki.millisecondGroup],i=t?fo.parseFraction(t):void 0,n=e[ki.secondGroup];let s;n&&(s=Xa.fromString(n,void 0,new Qd),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=e[ki.minuteGroup];let o;r&&(o=Wa.fromString(r,new eu),o.uncertain=o.uncertain||s?.uncertain||!1,o.approximate=o.approximate||s?.approximate||!1);const l=e[ki.hourGroup];let c;l&&(c=Va.fromString(l,new Jd),c.uncertain=c.uncertain||o?.uncertain||!1,c.approximate=c.approximate||o?.approximate||!1);const h=e[ki.dayGroup];let d;h&&(d=Ga.fromString(h,new jd),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[ki.monthGroup];let p;u&&(p=Ha.fromString(u,new Zd),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ki.yearGroup];let g;f&&(g=za.fromString(f,void 0,new Kd),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[ki.timeshiftGroup],v=m?ky.fromString(m,new qd,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:o,second:s,millisecond:i,timeshift:v}}}const Ny=["spring","summer","autumn","winter"],Gf=21,nx=32,sx=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let rx;function ax(){return rx??=new ki}function yo(a){return typeof a?.value=="number"?a.value:void 0}function yd(a){const e=a.trim();if(/^\d{1,2}:/.test(e)){const r=sx.exec(e)?.groups;return r?{year:void 0,month:void 0,day:void 0,hour:Number(r.hour),minute:Number(r.minute),second:r.second?Number(r.second):void 0,raw:e}:void 0}let t;try{t=Aa.fromString(e,ax())}catch{return}const i=yo(t.year),n=yo(t.month),s=n!==void 0&&n>=Gf&&n<=nx;if(!(t.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(t.day||t.hour)))return{year:i,month:s?void 0:n,...s?{season:Ny[(n-Gf)%4]}:{},day:yo(t.day),hour:yo(t.hour),minute:yo(t.minute),second:yo(t.second),raw:e}}function cl(a){if(a.raw!==void 0)return a.raw;if(a.year===void 0){if(a.hour===void 0)return"";let t=`${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`;return a.second!==void 0&&(t+=`:${String(a.second).padStart(2,"0")}`),t}let e=String(a.year).padStart(4,"0");return a.season!==void 0?`${e}-${Gf+Ny.indexOf(a.season)}`:(a.month===void 0||(e+=`-${String(a.month).padStart(2,"0")}`,a.day===void 0)||(e+=`-${String(a.day).padStart(2,"0")}`,a.hour===void 0)||(e+=`T${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`,a.second!==void 0&&(e+=`:${String(a.second).padStart(2,"0")}`)),e)}function Vf(a){if(a.year!==void 0)return Date.UTC(a.year,(a.month??1)-1,a.day??1,a.hour??0,a.minute??0,a.second??0)}function Zg(a){return(((a.day??0)*24+(a.hour??0))*60+(a.minute??0))*6e4+(a.second??0)*1e3}const ox=["year","month","day","hour","minute"],lx=["day","hour","minute"];function jg(a,e){return e.filter(t=>a[t]!==void 0).join(",")}function Tl(a){if(a.durationSeconds!==void 0)return a.durationSeconds*1e3;const e=a.durationText===void 0?void 0:bn.parse(a.durationText);if(e)return e.chosenSeconds*1e3;if(!a.time||!a.endTime)return;const t=a.time.year!==void 0&&a.endTime.year!==void 0,i=t?ox:lx,n=jg(a.time,i);if(!(n===""||n!==jg(a.endTime,i)))return t?Vf(a.endTime)-Vf(a.time):Zg(a.endTime)-Zg(a.time)}function cx(a){if(a.durationSeconds===void 0&&!(!a.time||!a.endTime))return Tl(a)===void 0?"imprecise":void 0}class Yu{constructor(e,t,i,n,s,r,o,l,c=[],h,d,u,p=[],f=[],g=[],m=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=o,this.weather=l,this.decor=c,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=p,this.references=f,this.roads=g,this.traces=m}provenance=wn.empty();loadIssues=[];account;sources;interpretation;sway;lightPollution;observerMap;iso;vehicle;get observerCount(){return 1+this.decor.filter(e=>e.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return Rt.byId(this.instrumentId)}static create(e,t,i){return new Yu({eventType:"sighting",time:e,place:t},new Gu,new Uc,new Bc,new zc,i)}}const hx=0,dx=0;function at(a,e){const t=a.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=a.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:hx,headingDeg:void 0,pitchDeg:dx,fovDeg:Rt.fieldOfViewDeg(a.instrument)}}function hi(a,e){return a.weatherTrack.getInterpolatedWeatherAt(e)??a.weather??Vu}function uh(a,e){return a.weatherTrack.getActualWeatherAt(e)??a.weather??Vu}function Dm(a,e){return a.soundTrack.getInterpolatedSoundAt(e)??m2}class tu{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Es.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;static around(e,t,i,n,s){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Es.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},l=new tu(o,new URL("case.json",s).href),c=l.tracks[0];return c.recording=e,c.base={url:n},l.caseChanged=!0,l}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat();return this.tracks.find(i=>i.kind==="observer"&&i.recording?.id!==void 0&&t.includes(i.recording.id))??this.tracks.find(i=>i.kind==="observer")}keep(e,t,i=!1){e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title)}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))}markExported(e){if(this.caseChanged=!1,!!e)for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording))}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}addReading(e,t,i,n){const s=e.recording;if(!s)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),o=new Set(this.tracks.map(A=>A.event.url)),l=new Set(this.tracks.map(A=>A.recording?.id));let c=this.tracks.filter(A=>A.kind==="reading").length+1;for(;o.has(`interpretation-${r}-${c}.json`)||l.has(`${s.id??r}-interpretation-${c}`);)c++;const h=`interpretation-${r}-${c}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:g,description:m,sources:v,tags:x,timeline:y,milestones:b,interpretation:w,...S}=structuredClone(s),_={version:1,id:`${s.id??r}-interpretation-${c}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},M={type:"event",eventType:"sighting",interpretationOf:s.id??r,time:t,...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],M],this.caseChanged=!0;const T={event:M,url:new URL(M.url,this.url).href,kind:"reading",recording:_};return this.tracks.push(T),T}idsOf(e){return e.recording?.id!==void 0?[e.recording.id]:[]}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(n=>n!==void 0&&t.includes(n)))}addObservation(e,t,i,n){const s=new Set(this.tracks.map(g=>g.event.url)),r=new Set(this.tracks.map(g=>g.recording?.id)),o=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",l=n?"interpretation":"observer";let c=`${l}-${o}.json`,h=e.id??o;for(let g=2;s.has(c)||r.has(h);g++)c=`${l}-${o}-${g}.json`,h=`${e.id??o}-${g}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...n?{interpretationOf:n.account.recording?.id??h}:{},...t!==void 0?{time:t}:{},...n?.by&&n.by.length>0?{by:n.by}:{},...i!==void 0?{title:i}:{},url:u+c};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:n?"reading":"observer",recording:d};return this.tracks.push(f),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(n=>n!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading")return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),n=o=>o.startsWith(i)?o.slice(i.length):o,s=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:n(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
3
3
|
`}));return[{path:decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",content:JSON.stringify(this.json,null,2)+`
|
|
4
|
-
`},...s]}}class Gn{constructor(e,t,i,n="en"){this.parts=e,this.messages=t,this.onChange=i,this.locale=n,this.setMessages(t),e.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),e.picker.addEventListener("change",()=>this.writeFromPicker()),e.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),e.text.addEventListener("blur",()=>this.validate()),e.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";get isPrecise(){return this.precise}setMessages(e,t=this.locale){this.messages=e,this.locale=t,e.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=e.edtfPlaceholder),this.parts.mode.title=e.edtfModeTitle,this.parts.mode.setAttribute("aria-label",e.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(e){this.precise=e,this.parts.picker.hidden=!e,this.parts.text.hidden=e,this.parts.mode.textContent=e?this.messages.datePrecise:this.messages.dateEdtf,this.parts.mode.setAttribute("aria-pressed",String(!e)),this.parts.help&&(this.parts.help.hidden=e),this.showDeduction()}set(e){const{text:t,picker:i}=this.parts;t.value=e?cl(e):"",i.step=Gn.stepFor(e),i.value=Gn.pickerValueOf(e),t.setCustomValidity(""),t.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...e){return e.every(t=>t===void 0||Gn.isPickable(t)&&Gn.qualifierOf(cl(t))==="")}static isPickable(e){return!!e&&e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0}static pickerValueOf(e){if(!Gn.isPickable(e))return"";const t=(n,s=2)=>String(n).padStart(s,"0"),i=e.second?`:${t(e.second)}`:"";return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}T${t(e.hour)}:${t(e.minute)}${i}`}static stepFor(e){return e?.second?"1":"60"}static qualifierOf(e){const t=/[?%]/.test(e),i=/[~%]/.test(e);return t&&i?"%":t?"?":i?"~":""}describe(e){return Gn.describeTime(e,this.messages,this.locale)}static describeTime(e,t,i){const n=cl(e),s=Gn.qualifierOf(n),r=h=>String(h).padStart(2,"0"),o=[];if(e.season!==void 0){const h={spring:t.timeSeasonSpring,summer:t.timeSeasonSummer,autumn:t.timeSeasonAutumn,winter:t.timeSeasonWinter}[e.season];o.push(e.year!==void 0?`${h} ${e.year}`:h)}else if(e.year!==void 0){const h=e.day!==void 0?{...e.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:e.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},d=new Date(Date.UTC(e.year,(e.month??1)-1,e.day??1));o.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(d))}e.hour!==void 0&&o.push(`${r(e.hour)}:${r(e.minute??0)}${e.second!==void 0?`:${r(e.second)}`:""}`);const l=o.join(", "),c=s==="~"?t.timeQualifierApproximate:s==="?"?t.timeQualifierUncertain:s==="%"?t.timeQualifierBoth:"";return c?`${l} — ${c.toLowerCase()}`:l}setHint(e){this.hint=e,this.showDeduction()}showDeduction(){const{text:e}=this.parts,t=e.value.trim();if(this.precise||t===""){e.title=this.hint;return}const i=yd(t);e.title=i?`→ ${this.describe(i)}`:this.messages.edtfInvalid}readText(){const e=this.parts.text.value.trim();if(e===""){this.clean(),this.onChange(void 0);return}const t=yd(e);t&&(this.clean(),this.onChange(t))}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:e,text:t}=this.parts;e.value===""&&e.validity.badInput||(t.value=e.value===""?"":e.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:e}=this.parts,t=e.value.trim();t===""||yd(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}}const ux={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",roll:"Roll",sway:"Sway at rest",swayTitle:"How much the body holding the instrument moves the view when not walking: 1 for a person standing, 0 for a tripod. Blank: 1 (0 if the account says the observer was paralysed)",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",confirmAccept:"Delete",confirmDecline:"Cancel",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelNone:"Built-in shape",decorModelDefault:"Default model",decorModelAdvanced:"Model from an address",decorModelFromCatalogue:"From the catalogue, which the recording names it by. Change a field and it becomes this recording's own address.",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},Il={...ux,oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",shape:"Shape",apparentWidth:"Apparent width",realWidth:"Real width",distance:"Distance",sizeLock:"Hold",lockNone:"nothing",lockApparent:"the apparent width",lockReal:"the real width",lockDistance:"the distance",apparentSize:"{moons}× the Moon",utcOffsetPlaceholder:"from longitude",realSizeBetween:"The scene bounds that width: between {min} and {max} m, from what it crosses",realSizeAtLeast:"The scene bounds that width: at least {min} m, from what it passes behind",realSizeAtMost:"The scene bounds that width: at most {max} m, from what it passes in front of",realSizeUnknown:"Nothing in the scene bounds that width: it is only what the distance implies",realSizeOutside:" — the width above is outside that",blurBound:"Blurred through this lens: nearer than {max} m",blurBoundNoInstrument:"Blur through the naked eye bounds no distance — an eye has no aperture to be out of focus with",blurBoundNotAtInfinity:"Blur bounds a distance only for a lens focused at infinity: this one is focused at {focus} m, which blurs on both sides of it",realSizeContradiction:"Contradiction: the declared crossings cannot all be true",realDistanceHere:" — i.e. between {min} and {max} m here",clearDistanceHypothesis:"Withdraw the distance hypothesis",clearDistanceHypothesisTitle:"Back to what the recording establishes",depthStated:"Drawn at {m} m, as the recording states",depthHypothesis:"Drawn at {m} m: your hypothesis — what the decor hides of it is what a thing that far would lose",depthDerived:"Drawn at {m} m, from the observer's own walk",depthBounded:"Drawn at {m} m, from what it passes behind and in front of",depthConventional:"Drawn at {m} m by convention: nothing in the recording establishes a distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",previousKeyframe:"Previous keyframe",nextKeyframe:"Next keyframe",keyframeMark:"Keyframe",shapesTrack:"shapes",observerTrack:"observer",weatherTrack:"weather",soundTrack:"sound",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.",confirmDeleteMilestone:"Stop naming moment {name}? The recording itself is unchanged.",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",samplingRate:"Sampling rate",currentPosition:"Current position",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Save",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.",importErrorCors:'That address answers, but the browser is not allowed to read it from this page. The file itself is fine — its server needs to send the header "Access-Control-Allow-Origin: *" with it. If it is not your server, that is what to ask its administrator for.',importErrorMixedContent:"A secure page cannot load an address starting with http://. Use https:// if that server offers it.",importErrorUnreachable:"Nothing answered at that address. Check the spelling, and that you are online.",importErrorStatus:"That server answered with an error ({status}). The address is probably wrong, or the file has moved.",importErrorMalformed:"That address answered, but what came back is not a recording.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",sourceAircraft:"Air traffic",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",utcOffsetNoZone:"No time zone reads this offset on that day",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:"unknown",altitudeAboveSeaLevel:"The observer's altitude above sea level — the ground at the location entered sets its floor: an observer in the Alps is not at 0 m.",groundAt:"ground at {m} m",headingPlaceholder:"unknown",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",description:"Description",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Phenomenon",shapesSubgroup:"Shapes",bodiesSubgroup:"Bodies",soundGroup:"Sound",temporalGroup:"Time",fileGroup:"File",fileLoading:"Loading the editor…",fileEditorLabel:"The recording as JSON text",timeQualifierExact:"Exact",durationPrecise:"precise",durationIso:"EDTF",durationModeTitle:"Say the length exactly, or as stated: about, between two lengths",durationInvalid:"Not a duration: PT10M, PT1H30M, PT5M/PT10M…",durationHelpTitle:"What the text takes (EDTF)",durationHelpLines:`PT45S — 45 seconds
|
|
4
|
+
`},...s]}}class Gn{constructor(e,t,i,n="en"){this.parts=e,this.messages=t,this.onChange=i,this.locale=n,this.setMessages(t),e.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),e.picker.addEventListener("change",()=>this.writeFromPicker()),e.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),e.text.addEventListener("blur",()=>this.validate()),e.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";get isPrecise(){return this.precise}setMessages(e,t=this.locale){this.messages=e,this.locale=t,e.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=e.edtfPlaceholder),this.parts.mode.title=e.edtfModeTitle,this.parts.mode.setAttribute("aria-label",e.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(e){this.precise=e,this.parts.picker.hidden=!e,this.parts.text.hidden=e,this.parts.mode.textContent=e?this.messages.datePrecise:this.messages.dateEdtf,this.parts.mode.setAttribute("aria-pressed",String(!e)),this.parts.help&&(this.parts.help.hidden=e),this.showDeduction()}set(e){const{text:t,picker:i}=this.parts;t.value=e?cl(e):"",i.step=Gn.stepFor(e),i.value=Gn.pickerValueOf(e),t.setCustomValidity(""),t.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...e){return e.every(t=>t===void 0||Gn.isPickable(t)&&Gn.qualifierOf(cl(t))==="")}static isPickable(e){return!!e&&e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0}static pickerValueOf(e){if(!Gn.isPickable(e))return"";const t=(n,s=2)=>String(n).padStart(s,"0"),i=e.second?`:${t(e.second)}`:"";return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}T${t(e.hour)}:${t(e.minute)}${i}`}static stepFor(e){return e?.second?"1":"60"}static qualifierOf(e){const t=/[?%]/.test(e),i=/[~%]/.test(e);return t&&i?"%":t?"?":i?"~":""}describe(e){return Gn.describeTime(e,this.messages,this.locale)}static describeTime(e,t,i){const n=cl(e),s=Gn.qualifierOf(n),r=h=>String(h).padStart(2,"0"),o=[];if(e.season!==void 0){const h={spring:t.timeSeasonSpring,summer:t.timeSeasonSummer,autumn:t.timeSeasonAutumn,winter:t.timeSeasonWinter}[e.season];o.push(e.year!==void 0?`${h} ${e.year}`:h)}else if(e.year!==void 0){const h=e.day!==void 0?{...e.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:e.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},d=new Date(Date.UTC(e.year,(e.month??1)-1,e.day??1));o.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(d))}e.hour!==void 0&&o.push(`${r(e.hour)}:${r(e.minute??0)}${e.second!==void 0?`:${r(e.second)}`:""}`);const l=o.join(", "),c=s==="~"?t.timeQualifierApproximate:s==="?"?t.timeQualifierUncertain:s==="%"?t.timeQualifierBoth:"";return c?`${l} — ${c.toLowerCase()}`:l}setHint(e){this.hint=e,this.showDeduction()}showDeduction(){const{text:e}=this.parts,t=e.value.trim();if(this.precise||t===""){e.title=this.hint;return}const i=yd(t);e.title=i?`→ ${this.describe(i)}`:this.messages.edtfInvalid}readText(){const e=this.parts.text.value.trim();if(e===""){this.clean(),this.onChange(void 0);return}const t=yd(e);t&&(this.clean(),this.onChange(t))}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:e,text:t}=this.parts;e.value===""&&e.validity.badInput||(t.value=e.value===""?"":e.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:e}=this.parts,t=e.value.trim();t===""||yd(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}}const ux={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",roll:"Roll",sway:"Sway at rest",swayTitle:"How much the body holding the instrument moves the view when not walking: 1 for a person standing, 0 for a tripod. Blank: 1 (0 if the account says the observer was paralysed)",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelNone:"Built-in shape",decorModelDefault:"Default model",decorModelAdvanced:"Model from an address",decorModelFromCatalogue:"From the catalogue, which the recording names it by. Change a field and it becomes this recording's own address.",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},Il={...ux,oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",shape:"Shape",apparentWidth:"Apparent width",realWidth:"Real width",distance:"Distance",sizeLock:"Hold",lockNone:"nothing",lockApparent:"the apparent width",lockReal:"the real width",lockDistance:"the distance",apparentSize:"{moons}× the Moon",utcOffsetPlaceholder:"from longitude",realSizeBetween:"The scene bounds that width: between {min} and {max} m, from what it crosses",realSizeAtLeast:"The scene bounds that width: at least {min} m, from what it passes behind",realSizeAtMost:"The scene bounds that width: at most {max} m, from what it passes in front of",realSizeUnknown:"Nothing in the scene bounds that width: it is only what the distance implies",realSizeOutside:" — the width above is outside that",blurBound:"Blurred through this lens: nearer than {max} m",blurBoundNoInstrument:"Blur through the naked eye bounds no distance — an eye has no aperture to be out of focus with",blurBoundNotAtInfinity:"Blur bounds a distance only for a lens focused at infinity: this one is focused at {focus} m, which blurs on both sides of it",realSizeContradiction:"Contradiction: the declared crossings cannot all be true",realDistanceHere:" — i.e. between {min} and {max} m here",clearDistanceHypothesis:"Withdraw the distance hypothesis",clearDistanceHypothesisTitle:"Back to what the recording establishes",depthStated:"Drawn at {m} m, as the recording states",depthHypothesis:"Drawn at {m} m: your hypothesis — what the decor hides of it is what a thing that far would lose",depthDerived:"Drawn at {m} m, from the observer's own walk",depthBounded:"Drawn at {m} m, from what it passes behind and in front of",depthConventional:"Drawn at {m} m by convention: nothing in the recording establishes a distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",previousKeyframe:"Previous keyframe",nextKeyframe:"Next keyframe",keyframeMark:"Keyframe",shapesTrack:"shapes",observerTrack:"observer",weatherTrack:"weather",soundTrack:"sound",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",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",samplingRate:"Sampling rate",currentPosition:"Current position",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Save",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.",importErrorCors:'That address answers, but the browser is not allowed to read it from this page. The file itself is fine — its server needs to send the header "Access-Control-Allow-Origin: *" with it. If it is not your server, that is what to ask its administrator for.',importErrorMixedContent:"A secure page cannot load an address starting with http://. Use https:// if that server offers it.",importErrorUnreachable:"Nothing answered at that address. Check the spelling, and that you are online.",importErrorStatus:"That server answered with an error ({status}). The address is probably wrong, or the file has moved.",importErrorMalformed:"That address answered, but what came back is not a recording.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",sourceAircraft:"Air traffic",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",utcOffsetNoZone:"No time zone reads this offset on that day",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:"unknown",altitudeAboveSeaLevel:"The observer's altitude above sea level — the ground at the location entered sets its floor: an observer in the Alps is not at 0 m.",groundAt:"ground at {m} m",headingPlaceholder:"unknown",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",description:"Description",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Phenomenon",shapesSubgroup:"Shapes",bodiesSubgroup:"Bodies",soundGroup:"Sound",temporalGroup:"Time",fileGroup:"File",fileLoading:"Loading the editor…",fileEditorLabel:"The recording as JSON text",timeQualifierExact:"Exact",durationPrecise:"precise",durationIso:"EDTF",durationModeTitle:"Say the length exactly, or as stated: about, between two lengths",durationInvalid:"Not a duration: PT10M, PT1H30M, PT5M/PT10M…",durationHelpTitle:"What the text takes (EDTF)",durationHelpLines:`PT45S — 45 seconds
|
|
5
5
|
PT10M — 10 minutes
|
|
6
6
|
PT1H30M — 1 hour 30 minutes
|
|
7
7
|
PT5M/PT10M — between 5 and 10 minutes
|
|
@@ -12,7 +12,7 @@ End with ? when uncertain, ~ when approximate, % for both
|
|
|
12
12
|
1965-07-01 — a day
|
|
13
13
|
1965-07-01T05:00 — a day and a time
|
|
14
14
|
05:00 — a time, the date unknown
|
|
15
|
-
End with ? when uncertain, ~ when approximate, % for both`,edtfModeTitle:"Type an imprecise date instead: a year alone, a month, a time with no date",locationGroup:"Position",observationGroup:"Summary",weatherWhilePlaying:"Pause the recording to state the weather — while it plays, the instant these would be written at is moving",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't an account: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the observer 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",lightPollutionLookingUp:"Looking up the atlas…",lightPollutionFound:"{artificial} µcd/m² of artificial light,",lightPollutionNatural:"No artificial light here,",lightPollutionOutside:"Beyond the atlas (85°N to 60°S),",lightPollutionFailed:"Atlas unreachable for now",lightPollutionTooEarly:"The atlas describes {atlasYear}; the sky of {year} was darker, give it yourself if it is known",instrumentOutOfPeriod:"{name} — not of this date",unitMillimetres:"mm",unitDegrees:"°",fieldOfViewReadout:"{deg}° of field",soundSrcPlaceholder:"URL of a real recording",referenceGroup:"Pictures",reference:"Picture",referenceTitle:"Name",referenceSrc:"Address",referenceSrcPlaceholder:"https://…/photo.jpg",referenceKind:"Kind",referencePhoto:"Photo",referencePanorama:"Panorama (360°)",referenceCredit:"Credit",referenceCreditUrl:"Credit link",referenceT:"Taken at",referenceDrawing:"Drawn on",referenceOpacity:"Opacity",referenceHeading:"Heading",referencePitch:"Pitch",referenceRoll:"Roll",referenceFov:"Vertical field",referenceUsePose:"Use the observer's pose",addReferenceUrl:"Add from an address",addReferenceFile:"Add a file",deleteReference:"Delete picture",referenceEmbedded:"{kb} kB embedded in the recording — an address would keep it light",referenceUnreachable:"The picture could not be loaded: check the address, and that its site allows other sites to read it",referenceRegisterHint:"Drag to turn the picture, wheel to change its field; “Add a landmark” to point at a detail on the picture, then at the same one in the render",referenceLandmarkPicture:"Landmark {n}: click the point on the picture",referenceLandmarkScene:"Landmark {n}: click the same point in the render",referenceLandmarkOffPicture:"That click is not on the picture",referenceNotLoaded:"The picture has not arrived yet",referenceLandmarksFit:"{n} landmarks — {deg}° off on average",referenceLandmarks:"Landmarks",addReferenceLandmark:"Add a landmark",deleteReferenceLandmark:"Delete landmark",referenceLandmarkLabel:"Name",referenceLandmarkLabelPlaceholder:"Masking tree, fence…",referenceAdoptPose:"Adopt as the observer's pose",referenceAdoptRationale:"Measured on the picture “{title}”: {n} landmarks lined up, {deg}° of residual",referenceStreetSearch:"Street-level pictures nearby",referenceStreetSearching:"Looking for pictures taken nearby…",referenceStreetNone:"No street-level picture within {m} m (Panoramax)",referenceStreetFailed:"Panoramax could not be reached",referenceStreetAdd:"Add",traceImport:"Investigator's lines (KML, KMZ)",trace:"Trace",deleteTrace:"Delete trace",traceTitle:"Name",traceSource:"Source",traceImported:"{n} imported from {name}.",traceSkipped:"Left out: {what}.",traceNone:"No line, place or outline found in this file.",traceFailed:"This file could not be read.",traceKindPoint:"place",traceKindLine:"line",traceKindPolygon:"outline",referenceStreetItem:"{distance} m at {bearing}°, {date}{panorama}",referenceStreetPanorama:" — 360°",referenceStreetTitle:"Street-level picture {distance} m away at {bearing}°, {date}",skyLine:"Sky: {parts}",skyStarsEye:"stars down to magnitude {limit}, which is as faint as an eye went under this sky",skyStarsDeeper:"stars down to magnitude {limit} through a {device} — {gain} magnitudes past the {eye} the observer's own eyes reached",skyStarsShallower:"stars down to magnitude {limit} through a {device} — {gain} magnitudes short of the {eye} the observer's own eyes reached",skyStarsCatalogue:", drawn to {catalogue}, where this project's catalogue stops",skyStarsNone:"no star could be picked out of a sky this bright",skyDetails:"Show the records in full",skyDetailsHide:"Hide the records",skyShowerActive:"{name} — radiant {altitude}° above the horizon, {bearing} — about {rate}/h under this sky, over a sporadic background of {sporadic}/h",skyShowerBelowHorizon:"{name} is active, but its radiant is below the horizon — it can have produced nothing",skyNothingActive:"no meteor shower active on this date — a sporadic background of about {sporadic}/h",showMeteor:"Show me one",skyComet:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}, tail {tail}° long",skyCometNoTail:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyCometBelowHorizon:"{name} was there at magnitude {magnitude}, but below the horizon — nobody here saw it",skyCometInDaylight:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} — but only {elongation}° from the Sun",showComet:"Show me the comet",skyNova:"{name}, a new star of magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyNovaBelowHorizon:"{name} was shining at magnitude {magnitude}, but below the horizon: nobody here saw it",showNova:"Show me the new star",skyEclipsePartial:"Solar eclipse: the Moon hides {percent}% of the Sun at {time}, {altitude}° above the horizon {bearing}",skyEclipseTotal:"Total solar eclipse: the Sun is wholly hidden from {time} for {duration}, {altitude}° above the horizon {bearing}",skySupermoon:"Full Moon at {distance} km: {diameter}° across, {percent}% wider than at its mean distance — a “supermoon”, and no bigger on the horizon than overhead",skyMicromoon:"Full Moon at {distance} km: {diameter}° across, {percent}% narrower than at its mean distance — a “micromoon”, and no smaller on the horizon than overhead",skyRedMoon:"The “lune rousse”: the full Moon of the lunation after Easter, {altitude}° above the horizon {bearing} — low, so reddened by the air it crosses, and no bigger or brighter than another",skySatellitePasses:"{count} satellites crossed this sky bright enough to be seen, the brightest {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatellitePassesOne:"one satellite crossed this sky bright enough to be seen: {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatelliteTrain:"among them a train of {count} Starlinks launched on {date}",skySatellitePassesNone:"by the orbital elements archived for that date, no lit satellite crossed this sky brightly enough to be seen",skySatelliteElementsGap:"no orbital elements archived near that date",skyReentries:"re-entries on record: {list}",skyReentriesMore:"{count} more",skyReentrySeen:"{name} came down at {time}, seen from {place} ({distance} km away)",skyReentryObserved:"{name} came down at {time}, seen",skyReentryOffset:", {minutes} min outside the observation",skyReentryPredicted:"{name} came down around {time} ± {hours} h, where unknown",skyReentryDay:"{name} came down on {date} (UTC), neither hour nor place known",skyFireballs:"{count} fireballs recorded by the Global Meteor Network, the brightest magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",skyFireballsOne:"a fireball recorded by the Global Meteor Network: magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",showFireball:"Show me the fireball",showSatellite:"Show me a satellite",skyOpticsPossible:"ice cloud enough, around the {source}, for {forms}",skyOpticsAlignment:" — everything but the rings needs crystals falling level, stated here at {alignment}% since no record holds it",skyOpticsHalo22:"a {angle}° ring",skyOpticsHalo46:"a {angle}° ring",skyOpticsParhelia:"sundogs {angle}° to either side",skyOpticsTangentArc:"an arc tangent on top of it",skyOpticsParhelicCircle:"a white circle right round the sky at its own height",skyOpticsCircumzenithal:"a circumzenithal arc {angle}° up",skyOpticsCircumhorizontal:"a circumhorizontal arc far below it",skyOpticsPillar:"a pillar standing over it",skyOpticsNoIce:"no ice cloud: no halo and no sundogs",skyOpticsHidden:"ice cloud above, but a lower deck between it and the observer",skyOpticsSun:"Sun",skyOpticsMoon:"Moon",skyBowPossible:"rain and sunlight enough for {forms}",skyBowMoon:"rain under a Moon {lit}% lit, enough for {forms} — a moonbow, which the eye sees as a white arc",skyGlowBand:"the Milky Way {contrast}× the sky behind it, {altitude}° up {bearing}",skyGlowCone:"the zodiacal light {contrast}× the sky behind it, {altitude}° up {bearing}, {elongation}° from the Sun — a faint tilted cone of light with blurred edges, gone within the hour",skyGlowZodiacalBand:"the zodiacal band {contrast}× the sky behind it, {altitude}° up {bearing} — the whole ecliptic faintly alight, which is not the sight people report",skyGlowMoon:"no Milky Way and no zodiacal light: a Moon {lit}% lit held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTwilight:"no Milky Way and no zodiacal light: twilight still held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTowns:"no Milky Way and no zodiacal light: the towns' glow held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowNothingUp:"sky dark enough ({sky} magnitudes a square arcsecond) but neither the galactic plane nor the ecliptic stood high enough in it",skyBowPrimary:"a bow {radius}° across, its top {top}° up",skyBowSecondary:"a second, fainter one at {radius}° with its colours reversed",skyBowSourceTooHigh:"rain, but with the source {altitude}° up no bow could clear the horizon: they stand {radius}° from the point opposite it",skyBowHidden:"rain, but an unbroken deck between it and the light: no bow",skyBowNoSource:"rain, and nothing lit to make a bow of it",skySatellitesLit:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month",skySatellitesLitWith:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month, among them {eras}",skySatellitesShadowed:"the Earth's shadow stood {height} km above the observer: of the {count} tracked objects in orbit that month, nothing in low orbit was lit",skySatellitesNotYet:"nothing had been put in orbit yet",skySatellitesDaylight:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skySatellitesDaylightOne:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skyUnknown:"cannot be worked out without a date and a place",lookAtDecor:"Look at it",addDecor:"Add",deleteDecor:"Delete decor",decorSightingUrl:"Their own recording URL",viewAccount:"View the account",noObserverRecording:"No recording URL set for this observer",masks:"Masks",masksNone:"No phenomenon to mask yet",modelPickerTitle:"Choose a 3D model",modelPickerClose:"Close",modelPickerChoose:"Choose a 3D model",modelPickerUse:"Use this model",modelPickerIncomplete:"Not drawn until the model's name and licence are given",addObserver:"Add observer",narrativePlaceholder:"What the observer reported, in their own words",narrativeSource:"Drafted by",narrativeNeedsSetting:'Fill in "{setting}" ({source}) to generate a reconstruction from the account',narrativeNeedsAsk:"Nothing to send yet",narrativeRemember:"Remember on this device",narrativeDraft:"Generate reconstruction",narrativeStop:"Stop",narrativeWorking:"Reading the account…",narrativeApplied:"{count} fields written into the editor",narrativeUnchanged:"The account states nothing the recording can hold yet",narrativeStated:"What the observer said",narrativeDerived:"Worked out from the account",narrativeAssumed:"Guessed, so the reconstruction runs — check these",narrativeGaps:"What nothing could settle",narrativeErrorCredential:"No key, or one that was refused — check it at console.anthropic.com",narrativeErrorRateLimited:"Too many requests on your account: wait a moment and ask again",narrativeErrorRefused:"The account was not answered. Rephrasing may help; asking again will not",narrativeErrorMalformed:"The answer was not a usable draft — worth asking once more",narrativeErrorUnreachable:"Nothing answered: check the connection",narrativeErrorRejected:"Refused: {detail}",observerAge:"Age then",observerOccupation:"Occupation",accountSource:"Account obtained",accountUrl:"Source (URL)",accountSourceUnknown:"unknown",accountSourceOnSite:"on-site investigation",accountSourceInterview:"interview in person",accountSourceTelephone:"by telephone",accountSourceQuestionnaire:"questionnaire",accountSourceLetter:"the observer wrote it",accountSourceSocialMedia:"the observer posted it online",accountSourcePress:"press or broadcast",accountFollowedUp:"Followed up",accountUnknown:"unknown",accountYes:"yes",accountNo:"no",questionUnanswered:"Nothing in this recording answers one of the questions a reconstruction needs settled",durationRequired:"The observation needs a length to be replayed at all — state one, or an end time, which may be approximate",questionsUnanswered:"{count} of the questions a full reconstruction answers are unanswered here"},px=Object.freeze(Object.defineProperty({__proto__:null,sightingEditorMessages_en:Il},Symbol.toStringTag,{value:"Module"})),iu="rr0-date-input",fx=`
|
|
15
|
+
End with ? when uncertain, ~ when approximate, % for both`,edtfModeTitle:"Type an imprecise date instead: a year alone, a month, a time with no date",locationGroup:"Position",observationGroup:"Summary",weatherWhilePlaying:"Pause the recording to state the weather — while it plays, the instant these would be written at is moving",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't an account: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the observer 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",lightPollutionLookingUp:"Looking up the atlas…",lightPollutionFound:"{artificial} µcd/m² of artificial light,",lightPollutionNatural:"No artificial light here,",lightPollutionOutside:"Beyond the atlas (85°N to 60°S),",lightPollutionFailed:"Atlas unreachable for now",lightPollutionTooEarly:"The atlas describes {atlasYear}; the sky of {year} was darker, give it yourself if it is known",instrumentOutOfPeriod:"{name} — not of this date",unitMillimetres:"mm",unitDegrees:"°",fieldOfViewReadout:"{deg}° of field",soundSrcPlaceholder:"URL of a real recording",referenceGroup:"Pictures",reference:"Picture",referenceTitle:"Name",referenceSrc:"Address",referenceSrcPlaceholder:"https://…/photo.jpg",referenceKind:"Kind",referencePhoto:"Photo",referencePanorama:"Panorama (360°)",referenceCredit:"Credit",referenceCreditUrl:"Credit link",referenceT:"Taken at",referenceDrawing:"Drawn on",referenceOpacity:"Opacity",referenceHeading:"Heading",referencePitch:"Pitch",referenceRoll:"Roll",referenceFov:"Vertical field",referenceUsePose:"Use the observer's pose",addReferenceUrl:"Add from an address",addReferenceFile:"Add a file",deleteReference:"Delete picture",referenceEmbedded:"{kb} kB embedded in the recording — an address would keep it light",referenceUnreachable:"The picture could not be loaded: check the address, and that its site allows other sites to read it",referenceRegisterHint:"Drag to turn the picture, wheel to change its field; “Add a landmark” to point at a detail on the picture, then at the same one in the render",referenceLandmarkPicture:"Landmark {n}: click the point on the picture",referenceLandmarkScene:"Landmark {n}: click the same point in the render",referenceLandmarkOffPicture:"That click is not on the picture",referenceNotLoaded:"The picture has not arrived yet",referenceLandmarksFit:"{n} landmarks — {deg}° off on average",referenceLandmarks:"Landmarks",addReferenceLandmark:"Add a landmark",deleteReferenceLandmark:"Delete landmark",referenceLandmarkLabel:"Name",referenceLandmarkLabelPlaceholder:"Masking tree, fence…",referenceAdoptPose:"Adopt as the observer's pose",referenceAdoptRationale:"Measured on the picture “{title}”: {n} landmarks lined up, {deg}° of residual",referenceStreetSearch:"Street-level pictures nearby",referenceStreetSearching:"Looking for pictures taken nearby…",referenceStreetNone:"No street-level picture within {m} m (Panoramax)",referenceStreetFailed:"Panoramax could not be reached",referenceStreetAdd:"Add",traceImport:"Investigator's lines (KML, KMZ)",trace:"Trace",deleteTrace:"Delete trace",traceTitle:"Name",traceSource:"Source",traceImported:"{n} imported from {name}.",traceSkipped:"Left out: {what}.",traceNone:"No line, place or outline found in this file.",traceFailed:"This file could not be read.",traceKindPoint:"place",traceKindLine:"line",traceKindPolygon:"outline",referenceStreetItem:"{distance} m at {bearing}°, {date}{panorama}",referenceStreetPanorama:" — 360°",referenceStreetTitle:"Street-level picture {distance} m away at {bearing}°, {date}",skyLine:"Sky: {parts}",skyStarsEye:"stars down to magnitude {limit}, which is as faint as an eye went under this sky",skyStarsDeeper:"stars down to magnitude {limit} through a {device} — {gain} magnitudes past the {eye} the observer's own eyes reached",skyStarsShallower:"stars down to magnitude {limit} through a {device} — {gain} magnitudes short of the {eye} the observer's own eyes reached",skyStarsCatalogue:", drawn to {catalogue}, where this project's catalogue stops",skyStarsNone:"no star could be picked out of a sky this bright",skyDetails:"Show the records in full",skyDetailsHide:"Hide the records",skyShowerActive:"{name} — radiant {altitude}° above the horizon, {bearing} — about {rate}/h under this sky, over a sporadic background of {sporadic}/h",skyShowerBelowHorizon:"{name} is active, but its radiant is below the horizon — it can have produced nothing",skyNothingActive:"no meteor shower active on this date — a sporadic background of about {sporadic}/h",showMeteor:"Show me one",skyComet:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}, tail {tail}° long",skyCometNoTail:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyCometBelowHorizon:"{name} was there at magnitude {magnitude}, but below the horizon — nobody here saw it",skyCometInDaylight:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} — but only {elongation}° from the Sun",showComet:"Show me the comet",skyNova:"{name}, a new star of magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyNovaBelowHorizon:"{name} was shining at magnitude {magnitude}, but below the horizon: nobody here saw it",showNova:"Show me the new star",skyEclipsePartial:"Solar eclipse: the Moon hides {percent}% of the Sun at {time}, {altitude}° above the horizon {bearing}",skyEclipseTotal:"Total solar eclipse: the Sun is wholly hidden from {time} for {duration}, {altitude}° above the horizon {bearing}",skySupermoon:"Full Moon at {distance} km: {diameter}° across, {percent}% wider than at its mean distance — a “supermoon”, and no bigger on the horizon than overhead",skyMicromoon:"Full Moon at {distance} km: {diameter}° across, {percent}% narrower than at its mean distance — a “micromoon”, and no smaller on the horizon than overhead",skyRedMoon:"The “lune rousse”: the full Moon of the lunation after Easter, {altitude}° above the horizon {bearing} — low, so reddened by the air it crosses, and no bigger or brighter than another",skySatellitePasses:"{count} satellites crossed this sky bright enough to be seen, the brightest {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatellitePassesOne:"one satellite crossed this sky bright enough to be seen: {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatelliteTrain:"among them a train of {count} Starlinks launched on {date}",skySatellitePassesNone:"by the orbital elements archived for that date, no lit satellite crossed this sky brightly enough to be seen",skySatelliteElementsGap:"no orbital elements archived near that date",skyReentries:"re-entries on record: {list}",skyReentriesMore:"{count} more",skyReentrySeen:"{name} came down at {time}, seen from {place} ({distance} km away)",skyReentryObserved:"{name} came down at {time}, seen",skyReentryOffset:", {minutes} min outside the observation",skyReentryPredicted:"{name} came down around {time} ± {hours} h, where unknown",skyReentryDay:"{name} came down on {date} (UTC), neither hour nor place known",skyFireballs:"{count} fireballs recorded by the Global Meteor Network, the brightest magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",skyFireballsOne:"a fireball recorded by the Global Meteor Network: magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",showFireball:"Show me the fireball",showSatellite:"Show me a satellite",skyOpticsPossible:"ice cloud enough, around the {source}, for {forms}",skyOpticsAlignment:" — everything but the rings needs crystals falling level, stated here at {alignment}% since no record holds it",skyOpticsHalo22:"a {angle}° ring",skyOpticsHalo46:"a {angle}° ring",skyOpticsParhelia:"sundogs {angle}° to either side",skyOpticsTangentArc:"an arc tangent on top of it",skyOpticsParhelicCircle:"a white circle right round the sky at its own height",skyOpticsCircumzenithal:"a circumzenithal arc {angle}° up",skyOpticsCircumhorizontal:"a circumhorizontal arc far below it",skyOpticsPillar:"a pillar standing over it",skyOpticsNoIce:"no ice cloud: no halo and no sundogs",skyOpticsHidden:"ice cloud above, but a lower deck between it and the observer",skyOpticsSun:"Sun",skyOpticsMoon:"Moon",skyBowPossible:"rain and sunlight enough for {forms}",skyBowMoon:"rain under a Moon {lit}% lit, enough for {forms} — a moonbow, which the eye sees as a white arc",skyGlowBand:"the Milky Way {contrast}× the sky behind it, {altitude}° up {bearing}",skyGlowCone:"the zodiacal light {contrast}× the sky behind it, {altitude}° up {bearing}, {elongation}° from the Sun — a faint tilted cone of light with blurred edges, gone within the hour",skyGlowZodiacalBand:"the zodiacal band {contrast}× the sky behind it, {altitude}° up {bearing} — the whole ecliptic faintly alight, which is not the sight people report",skyGlowMoon:"no Milky Way and no zodiacal light: a Moon {lit}% lit held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTwilight:"no Milky Way and no zodiacal light: twilight still held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTowns:"no Milky Way and no zodiacal light: the towns' glow held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowNothingUp:"sky dark enough ({sky} magnitudes a square arcsecond) but neither the galactic plane nor the ecliptic stood high enough in it",skyBowPrimary:"a bow {radius}° across, its top {top}° up",skyBowSecondary:"a second, fainter one at {radius}° with its colours reversed",skyBowSourceTooHigh:"rain, but with the source {altitude}° up no bow could clear the horizon: they stand {radius}° from the point opposite it",skyBowHidden:"rain, but an unbroken deck between it and the light: no bow",skyBowNoSource:"rain, and nothing lit to make a bow of it",skySatellitesLit:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month",skySatellitesLitWith:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month, among them {eras}",skySatellitesShadowed:"the Earth's shadow stood {height} km above the observer: of the {count} tracked objects in orbit that month, nothing in low orbit was lit",skySatellitesNotYet:"nothing had been put in orbit yet",skySatellitesDaylight:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skySatellitesDaylightOne:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skyUnknown:"cannot be worked out without a date and a place",lookAtDecor:"Look at it",addDecor:"Add",deleteDecor:"Delete decor",undo:"Undo",redo:"Redo",decorSightingUrl:"Their own recording URL",viewAccount:"View the account",noObserverRecording:"No recording URL set for this observer",masks:"Masks",masksNone:"No phenomenon to mask yet",modelPickerTitle:"Choose a 3D model",modelPickerClose:"Close",modelPickerChoose:"Choose a 3D model",modelPickerUse:"Use this model",modelPickerIncomplete:"Not drawn until the model's name and licence are given",addObserver:"Add observer",narrativePlaceholder:"What the observer reported, in their own words",narrativeSource:"Drafted by",narrativeNeedsSetting:'Fill in "{setting}" ({source}) to generate a reconstruction from the account',narrativeNeedsAsk:"Nothing to send yet",narrativeRemember:"Remember on this device",narrativeDraft:"Generate reconstruction",narrativeStop:"Stop",narrativeWorking:"Reading the account…",narrativeApplied:"{count} fields written into the editor",narrativeUnchanged:"The account states nothing the recording can hold yet",narrativeStated:"What the observer said",narrativeDerived:"Worked out from the account",narrativeAssumed:"Guessed, so the reconstruction runs — check these",narrativeGaps:"What nothing could settle",narrativeErrorCredential:"No key, or one that was refused — check it at console.anthropic.com",narrativeErrorRateLimited:"Too many requests on your account: wait a moment and ask again",narrativeErrorRefused:"The account was not answered. Rephrasing may help; asking again will not",narrativeErrorMalformed:"The answer was not a usable draft — worth asking once more",narrativeErrorUnreachable:"Nothing answered: check the connection",narrativeErrorRejected:"Refused: {detail}",observerAge:"Age then",observerOccupation:"Occupation",accountSource:"Account obtained",accountUrl:"Source (URL)",accountSourceUnknown:"unknown",accountSourceOnSite:"on-site investigation",accountSourceInterview:"interview in person",accountSourceTelephone:"by telephone",accountSourceQuestionnaire:"questionnaire",accountSourceLetter:"the observer wrote it",accountSourceSocialMedia:"the observer posted it online",accountSourcePress:"press or broadcast",accountFollowedUp:"Followed up",accountUnknown:"unknown",accountYes:"yes",accountNo:"no",questionUnanswered:"Nothing in this recording answers one of the questions a reconstruction needs settled",durationRequired:"The observation needs a length to be replayed at all — state one, or an end time, which may be approximate",questionsUnanswered:"{count} of the questions a full reconstruction answers are unanswered here"},px=Object.freeze(Object.defineProperty({__proto__:null,sightingEditorMessages_en:Il},Symbol.toStringTag,{value:"Module"})),iu="rr0-date-input",fx=`
|
|
16
16
|
rr0-date-input { position: relative; display: inline-flex; align-items: center; gap: .3em; }
|
|
17
17
|
rr0-date-input .edtf-field { position: relative; display: inline-flex; align-items: center; }
|
|
18
18
|
rr0-date-input .edtf-field input[type="text"] { padding-right: 1.6em; }
|
|
@@ -59,7 +59,7 @@ rr0-date-input [hidden] { display: none !important; }
|
|
|
59
59
|
${i("instance-density","instanceDensity","0","2")}
|
|
60
60
|
${i("instance-darkness","darkness","0","1","layerDarkness")}
|
|
61
61
|
</div><p data-text="individualHelp">${e.individualHelp}</p></details>
|
|
62
|
-
<p id="cloud-status" role="status"></p></div>`}static localize(e,t){for(const i of e.querySelectorAll("[data-text]"))i.textContent=t[i.dataset.text];for(const i of e.querySelectorAll("[data-placeholder]"))i.placeholder=t[i.dataset.placeholder]}}const Hc=["en","fr","es","it"],yx={en:()=>je(()=>Promise.resolve().then(()=>Zx),void 0,import.meta.url).then(a=>a.ufoMessages_en),fr:()=>je(()=>import("./UfoMessages_fr-bJNAf-AU.js"),[],import.meta.url).then(a=>a.ufoMessages_fr),es:()=>je(()=>import("./UfoMessages_es-LFW_B5H2.js"),[],import.meta.url).then(a=>a.ufoMessages_es),it:()=>je(()=>import("./UfoMessages_it-B-jnc4M-.js"),[],import.meta.url).then(a=>a.ufoMessages_it)};function Mx(a){return yx[a]()}const wx={en:()=>je(()=>Promise.resolve().then(()=>px),void 0,import.meta.url).then(a=>a.sightingEditorMessages_en),fr:()=>je(()=>import("./SightingEditorMessages_fr-DcRPYz1n.js"),[],import.meta.url).then(a=>a.sightingEditorMessages_fr),es:()=>je(()=>import("./SightingEditorMessages_es-SrV-tb46.js"),[],import.meta.url).then(a=>a.sightingEditorMessages_es),it:()=>je(()=>import("./SightingEditorMessages_it-DcmpHfvU.js"),[],import.meta.url).then(a=>a.sightingEditorMessages_it)};function Hy(a){return wx[a]()}function xx(a){switch(a){case"fr":return je(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr);case"es":return je(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(e=>e.tagNames_es);case"it":return je(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(e=>e.tagNames_it);default:return Promise.resolve({})}}const Sx={en:()=>je(()=>import("./BodyEditorMessages_en-D6h_2jc7.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_en),fr:()=>je(()=>import("./BodyEditorMessages_fr-CG8xnMzM.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_fr),es:()=>je(()=>import("./BodyEditorMessages_es-DfSa9Yth.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_es),it:()=>je(()=>import("./BodyEditorMessages_it-CIClW1lP.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_it)},Ex={en:()=>je(()=>Promise.resolve().then(()=>L6),void 0,import.meta.url).then(a=>a.caseEditorMessages_en),fr:()=>je(()=>import("./CaseEditorMessages_fr-WW3gM38H.js"),[],import.meta.url).then(a=>a.caseEditorMessages_fr),es:()=>je(()=>import("./CaseEditorMessages_es-D5DtN8Q1.js"),[],import.meta.url).then(a=>a.caseEditorMessages_es),it:()=>je(()=>import("./CaseEditorMessages_it-CN6g0t9U.js"),[],import.meta.url).then(a=>a.caseEditorMessages_it)};function _x(a){return Ex[a]()}function N6(a){return Sx[a]()}function Gy(a){switch(a){case"fr":return je(()=>import("./SceneNames_fr-BFN6x9Z7.js"),[],import.meta.url).then(e=>e.sceneNames_fr);case"es":return je(()=>import("./SceneNames_es-BuZsPlTw.js"),[],import.meta.url).then(e=>e.sceneNames_es);case"it":return je(()=>import("./SceneNames_it-BOuH3VIw.js"),[],import.meta.url).then(e=>e.sceneNames_it);default:return Promise.resolve(void 0)}}function Ax(a){switch(a){case"fr":return je(()=>import("./CloudEditorMessages_fr-CpKSij1v.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_fr);case"es":return je(()=>import("./CloudEditorMessages_es-ozb6J7KN.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_es);case"it":return je(()=>import("./CloudEditorMessages_it-CPHBLAsn.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_it);default:return Promise.resolve(void 0)}}class tn{static CHROME="2.6em";static UNBOUNDED=9999;static fit(e){const t=[...e.querySelectorAll('input[type="number"]')];for(const i of t)i.style.width=`calc(${tn.charsFor(i)}ch + ${tn.CHROME})`,tn.hold(i,!0),i.dataset.held!==""&&(i.dataset.held="",i.addEventListener("input",()=>tn.hold(i)),i.addEventListener("change",()=>tn.hold(i,!0)));return t.length}static hold(e,t=!1){const i=tn.heldValue(e.value,e,t);i!==e.value&&(e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})))}static heldValue(e,t,i=!1){if(e===""||!/^-?\d+(\.\d+)?$/.test(e))return e;const n=tn.wholeOnly(t.step)?0:tn.decimalsOf(t.step),s=e.indexOf("."),r=s>=0&&e.length-s-1>n?n===0?e.slice(0,s):e.slice(0,s+n+1):e,o=Number(r),l=t.min===""?void 0:Number(t.min),c=t.max===""?void 0:Number(t.max);return c!==void 0&&o>c?String(c):i&&l!==void 0&&o<l?String(l):r}static charsFor(e){const t=o=>o===""?void 0:Math.abs(Number(o)),i=Math.max(t(e.max)??tn.UNBOUNDED,t(e.min)??0),n=String(Math.floor(Number.isFinite(i)?i:tn.UNBOUNDED)).length,s=e.min!==""&&Number(e.min)<0?1:0,r=tn.wholeOnly(e.step)?0:tn.decimalsOf(e.step);return n+s+(r>0?r+1:0)}static decimalsOf(e){if(e===""||e==="any")return 2;const t=e.indexOf(".");return Math.max(2,t<0?0:e.length-t-1)}static wholeOnly(e){return e!==""&&e!=="any"&&!e.includes(".")}}function Tx(a,e,t,i,n="en"){let s=zy;a.innerHTML=tv.html(s),tn.fit(a);const r=A=>a.querySelector("#"+A),o=A=>Number(r(A).value),l=a.querySelector("#cloud-layer"),c=a.querySelector("#cloud-instance"),h=a.querySelector("#cloud-status"),d=()=>r("cloud-scope").value,u=()=>Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime))[Number(l.value)],p=["east","north","base","thickness","width","depth","rotation","density","darkness"],f=()=>{const A=u()?.instances?.find(C=>C.id===c.value);for(const C of p)r(`instance-${C}`).disabled=!A;if(a.querySelector("#cloud-instance-delete").disabled=!A,a.querySelector("#cloud-instance-point").disabled=!A,!A)return;const R=[A.eastM,A.northM,A.baseM,A.thicknessM,A.widthM,A.depthM,A.rotationDeg,A.density,A.darkness];p.forEach((C,k)=>{r(`instance-${C}`).value=R[k]===void 0?"":String(Math.round(R[k]*100)/100)})};let g=-1;const m=()=>{const A=e.ufoElement.currentTime,R=a.getRootNode().activeElement;if(A===g&&R instanceof HTMLInputElement&&a.contains(R))return;g=A;const C=Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime)),k=l.selectedOptions[0]?.dataset.layerId;l.replaceChildren(...C.map((V,Z)=>{const K=new Option(`${Z+1} · ${V.type} · ${Math.round(V.baseM)} m`,String(Z));return K.dataset.layerId=V.id,K}));const z=C.findIndex(V=>V.id===k);l.value=String(Math.max(0,z));const L=u();for(const V of["cloud-type","cloud-base","cloud-thickness","cloud-cover","cloud-size","cloud-density","cloud-darkness","cloud-crystal-alignment","cloud-wind-direction","cloud-wind-speed","cloud-seed","cloud-layer-delete","cloud-instance-add"])a.querySelector("#"+V).disabled=!L;if(r("cloud-crystal-alignment").closest("label").hidden=L?.type!=="cirrus",!L){c.replaceChildren(new Option("—","")),f();return}r("cloud-type").value=L.type;for(const[V,Z]of Object.entries({base:L.baseM,thickness:L.thicknessM,cover:L.coverage*100,size:L.sizeM,density:L.density}))r(`cloud-${V}`).value=String(Math.round(Z*100)/100);r("cloud-darkness").value=String(Math.round((L.darkness??hi(e.ufoElement.sighting,A).cloudDarkness)*100)/100);const N=r("cloud-crystal-alignment");N.value=String(Math.round((L.iceCrystalAlignment??Od)*100)/100),r("cloud-wind-direction").value=L.windDirectionDeg===void 0?"":String(Math.round(L.windDirectionDeg*10)/10),r("cloud-wind-speed").value=L.windSpeed===void 0?"":String(Math.round(L.windSpeed*100)/100),r("cloud-seed").value=L.seed===void 0?"":String(L.seed);const F=c.value;c.replaceChildren(new Option(s.none,""),...(L.instances??[]).map((V,Z)=>new Option(`${s.cloud} ${Z+1}`,V.id))),c.value=L.instances?.some(V=>V.id===F)?F:"",f()},v=(A,R=!0)=>{if(!u())return;e.ufoElement.pause(),t(R);const C=e.ufoElement.currentTime,k=e.ufoElement.sighting;gx(k.weatherTrack,hi(k,C),C,u().id,A,d()),e.ufoElement.refresh(),h.textContent=d()==="observation"?s.savedAcrossObservation:`${(C/1e3).toFixed(1)} s · ${s.savedAtThisTime}`};a.addEventListener("focusin",()=>e.ufoElement.pause()),l.addEventListener("change",()=>{c.value="",m()}),c.addEventListener("change",f);const x=A=>{e.ufoElement.pause(),t();const R=e.ufoElement.sighting,C=e.ufoElement.currentTime;Uy(R.weatherTrack,hi(R,C),C,A,d()),e.ufoElement.refresh(),m()};a.querySelector("#cloud-layer-add").addEventListener("click",()=>{const A=hi(e.ufoElement.sighting,e.ufoElement.currentTime),R={id:crypto.randomUUID(),type:"cumulus",baseM:1500,thicknessM:800,coverage:.5,sizeM:1400,density:1,darkness:A.cloudDarkness};x(C=>[...C,R]),l.value=String(Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime)).findIndex(C=>C.id===R.id)),m()}),a.querySelector("#cloud-layer-delete").addEventListener("click",()=>{const A=u()?.id;A&&x(R=>R.filter(C=>C.id!==A))});const y=e.ufoElement.canvasElement,b=r("cloud-manipulate");let w;const S=A=>{const R=y.getBoundingClientRect();return{x:(A.clientX-R.left)/R.width*2-1,y:1-(A.clientY-R.top)/R.height*2}};b.addEventListener("change",()=>{y.style.touchAction=b.checked?"none":"",y.style.cursor=b.checked?"crosshair":""}),y.addEventListener("click",A=>{b.checked&&(A.preventDefault(),A.stopImmediatePropagation())},!0),y.addEventListener("pointerdown",A=>{if(!b.checked||A.button!==0)return;A.preventDefault(),A.stopImmediatePropagation(),e.ufoElement.pause();const R=S(A),C=e.pickCloudAt(R.x,R.y);if(!C){h.textContent=s.noCloudHere;return}const k=Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime));l.value=String(k.findIndex(N=>N.id===C.layerId)),m(),c.value=C.instanceId,f();const L=(d()==="observation"?e.ufoElement.sighting.weatherTrack.allKeyframes.map(N=>N.weather):[hi(e.ufoElement.sighting,e.ufoElement.currentTime)]).flatMap(N=>Ks(N).filter(F=>F.id===C.layerId).flatMap(F=>(F.instances??[]).filter(V=>V.id===C.instanceId).map(V=>V.baseM)));w={minBase:Math.min(...L),pointerId:A.pointerId,id:C.instanceId,center:C.center,ray:e.cloudDirectionAt(R.x,R.y),delta:{x:0,y:0,z:0}},y.setPointerCapture(A.pointerId),y.style.cursor="grabbing",h.textContent=s.cloudSelected},!0),y.addEventListener("pointermove",A=>{if(!w||A.pointerId!==w.pointerId)return;A.preventDefault(),A.stopImmediatePropagation();const R=S(A),C=bx(w.ray,e.cloudDirectionAt(R.x,R.y),w.center);if(!C)return;C.y=Math.max(C.y,-w.minBase);const k=w.delta,z=w.id;v(L=>({...L,instances:L.instances?.map(N=>N.id!==z?N:{...N,eastM:N.eastM+C.x-k.x,northM:N.northM-C.z+k.z,baseM:N.baseM+C.y-k.y})})),w.delta=C,f()},!0);const _=A=>{!w||A.pointerId!==w.pointerId||(w=void 0,y.hasPointerCapture(A.pointerId)&&y.releasePointerCapture(A.pointerId),y.style.cursor=b.checked?"crosshair":"")};y.addEventListener("pointerup",_),y.addEventListener("pointercancel",_),y.addEventListener("lostpointercapture",_);const M={"cloud-type":"type","cloud-base":"baseM","cloud-thickness":"thicknessM","cloud-cover":"coverage","cloud-size":"sizeM","cloud-density":"density","cloud-darkness":"darkness","cloud-crystal-alignment":"iceCrystalAlignment"};for(const[A,R]of Object.entries(M)){const C=()=>{if(r(A).value===""||!r(A).validity.valid)return;const k=A==="cloud-type"?r(A).value:o(A)/(A==="cloud-cover"?100:1);v(z=>({...z,[R]:k}),A!=="cloud-crystal-alignment")};r(A).addEventListener(A==="cloud-type"?"change":"input",C)}for(const[A,R]of[["cloud-wind-direction","windDirectionDeg"],["cloud-wind-speed","windSpeed"],["cloud-seed","seed"]])r(A).addEventListener("input",()=>{r(A).validity.valid&&v(C=>({...C,[R]:r(A).value===""?void 0:o(A)}))});a.querySelector("#cloud-instance-add").addEventListener("click",()=>{const A=u();if(!A)return;const R=crypto.randomUUID(),C=e.ufoElement.sighting,k=e.ufoElement.currentTime,z=at(C,k),L=su(k,C.weatherTrack,hi(C,0),at(C,0),z,A.id),N=e.cloudDirectionAt(0,0),F=A.baseM+A.thicknessM*.4-(z?.elevationM??0)-1.6,V=F*N.y>0?Math.max(500,Math.min(2e4,F/N.y)):5e3,Z={id:R,eastM:L.x+N.x*V,northM:-(L.z+N.z*V),baseM:A.baseM,thicknessM:A.thicknessM,widthM:1800,depthM:1200,rotationDeg:0,density:1,darkness:A.darkness};v(K=>({...K,instances:[...K.instances??[],Z]})),m(),c.value=R,f(),h.textContent+=s.cloudAdded}),a.querySelector("#cloud-instance-delete").addEventListener("click",()=>{const A=c.value;A&&(v(R=>({...R,instances:R.instances?.filter(C=>C.id!==A)})),m())}),a.querySelector("#cloud-instance-point").addEventListener("click",()=>{const A=u(),R=A?.instances?.find(K=>K.id===c.value);if(!R)return;e.ufoElement.pause();const C=e.ufoElement.sighting,k=e.ufoElement.currentTime,z=at(C,k),L=su(k,C.weatherTrack,hi(C,0),at(C,0),z,A.id),N=R.eastM-L.x,F=R.northM+L.z,V=Math.hypot(N,F),Z=R.baseM+R.thicknessM/2-(z?.elevationM??0)-1.6-V**2/(2*6371e3);V===0&&Z===0||i((Math.atan2(N,F)*180/Math.PI+360)%360,Math.atan2(Z,V)*180/Math.PI)}),n!=="en"&&Ax(n).then(A=>{A&&(s=A,tv.localize(a,s),g=-1,m())});const T=["eastM","northM","baseM","thicknessM","widthM","depthM","rotationDeg","density","darkness"];return p.forEach((A,R)=>r(`instance-${A}`).addEventListener("input",()=>{const C=c.value,k=r(`instance-${A}`);if(!C||!k.validity.valid||k.value===""&&A!=="darkness")return;const z=T[R],L=k.value===""?void 0:o(`instance-${A}`);v(N=>({...N,instances:N.instances?.map(F=>F.id!==C?F:{...F,[z]:L})}))})),{sync:m,stopManipulation(){w=void 0,b.checked=!1,y.style.touchAction="",y.style.cursor=""},reset(){w=void 0,b.checked=!1,y.style.cursor="",y.style.touchAction="",c.value="",g=-1,m()}}}const Vy=["nw","n","ne","e","se","s","sw","w"],Ix=24,ta=8,Wy=3,Dx=8;function mc(a,e,t){const i=a.x-e.x,n=a.y-e.y,s=Math.cos(t),r=Math.sin(t);return{x:e.x+i*s-n*r,y:e.y+i*r+n*s}}function Ta(a){return{x:a.x+a.width/2,y:a.y+a.height/2}}const Rx={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 Tt{static handlePointsFor(e){const{x:t,y:i,width:n,height:s}=e.bounds,r={nw:{x:t,y:i},n:{x:t+n/2,y:i},ne:{x:t+n,y:i},e:{x:t+n,y:i+s/2},se:{x:t+n,y:i+s},s:{x:t+n/2,y:i+s},sw:{x:t,y:i+s},w:{x:t,y:i+s/2},rotate:{x:t+n/2,y:i-Ix}},o=Ta(e.bounds),l={};for(const c of Object.keys(r))l[c]=mc(r[c],o,e.angle);return l}static hitTestHandle(e,t,i=8,n=[...Vy,"rotate"]){const s=Tt.handlePointsFor(e);for(const r of n)if(Math.hypot(t.x-s[r].x,t.y-s[r].y)<=i)return r}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 n=((Tt.HANDLE_DIRECTION_DEG[e]+t*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(e,t,i,n){const s=Ta(e),r=mc(n,s,-t),{x:o,y:l,width:c,height:h}=e,d=Rx[i];let u=o,p=l,f=o+c,g=l+h;return d.left&&(u=Math.min(r.x,f-ta)),d.right&&(f=Math.max(r.x,u+ta)),d.top&&(p=Math.min(r.y,g-ta)),d.bottom&&(g=Math.max(r.y,p+ta)),{x:u,y:p,width:f-u,height:g-p}}static resizeShape(e,t,i){if(t==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=e.bounds,r=Tt.resizeBounds(e.bounds,e.angle,t,i);if(e.kind==="oval")return{...e,bounds:r};const o=n===0?1:r.width/n,l=s===0?1:r.height/s;return{...e,bounds:r,points:e.points.map(c=>({x:c.x*o,y:c.y*l}))}}static rotateShape(e,t){const i=Ta(e.bounds),n=Math.atan2(t.y-i.y,t.x-i.x)+Math.PI/2;return{...e,angle:n}}static groupBoundsFor(e){const t=Math.min(...e.map(r=>r.x)),i=Math.min(...e.map(r=>r.y)),n=Math.max(...e.map(r=>r.x+r.width)),s=Math.max(...e.map(r=>r.y+r.height));return{x:t,y:i,width:n-t,height:s-i}}static vertexPointsFor(e){const t=Ta(e.bounds);return e.points.map(i=>mc({x:e.bounds.x+i.x,y:e.bounds.y+i.y},t,e.angle))}static hitTestVertex(e,t,i=Dx){const n=Tt.vertexPointsFor(e);let s,r=i;return n.forEach((o,l)=>{const c=Math.hypot(t.x-o.x,t.y-o.y);c<=r&&(r=c,s=l)}),s}static toLocalPoint(e,t){const i=Ta(e.bounds),n=mc(t,i,-e.angle);return{x:n.x-e.bounds.x,y:n.y-e.bounds.y}}static moveVertex(e,t,i){const n=e.points.map((d,u)=>u===t?Tt.toLocalPoint(e,i):d),s=Math.min(...n.map(d=>d.x)),r=Math.min(...n.map(d=>d.y)),o=Math.max(...n.map(d=>d.x)),l=Math.max(...n.map(d=>d.y)),c={x:e.bounds.x+s,y:e.bounds.y+r,width:o-s,height:l-r},h=n.map(d=>({x:d.x-s,y:d.y-r}));return{...e,bounds:c,points:h}}static insertVertexNear(e,t){const i=Tt.toLocalPoint(e,t),{points:n}=e;let s=n.length-1,r=1/0;for(let l=0;l<n.length;l++){const c=n[l],h=n[(l+1)%n.length],d=Tt.distanceToSegment(i,c,h);d<r&&(r=d,s=l)}const o=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...e,points:o}}static distanceToSegment(e,t,i){const n=i.x-t.x,s=i.y-t.y,r=n*n+s*s,o=r===0?0:Math.max(0,Math.min(1,((e.x-t.x)*n+(e.y-t.y)*s)/r)),l=t.x+o*n,c=t.y+o*s;return Math.hypot(e.x-l,e.y-c)}static deleteVertex(e,t){return e.points.length<=Wy?e:{...e,points:e.points.filter((i,n)=>n!==t)}}}class dp{constructor(e){this.members=e}bounds(){return Tt.groupBoundsFor(this.members.map(e=>e.shape.bounds))}scaleTo(e){const t=this.bounds(),i=t.width===0?1:e.width/t.width,n=t.height===0?1:e.height/t.height;return this.members.map(({sourceId:s,shape:r})=>{const o=Math.max(r.bounds.width*i,ta),l=Math.max(r.bounds.height*n,ta),c=e.x+(r.bounds.x-t.x)*i,h=e.y+(r.bounds.y-t.y)*n,d={x:c,y:h,width:o,height:l};return r.kind==="oval"?{sourceId:s,shape:{...r,bounds:d}}:{sourceId:s,shape:{...r,bounds:d,points:r.points.map(u=>({x:u.x*i,y:u.y*n}))}}})}resize(e,t){return this.scaleTo(Tt.resizeBounds(this.bounds(),0,e,t))}rotate(e,t){const i=Ta(this.bounds()),n=r=>Math.atan2(r.y-i.y,r.x-i.x),s=n(e)-n(t);return this.members.map(({sourceId:r,shape:o})=>{const l=Ta(o.bounds),c=mc(l,i,s),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:r,shape:{...o,bounds:h,angle:o.angle+s}}})}}const Wf=6,ph=Wf/2,iv=20,Xf=24,nv=9,sv=6,rv=7,av=6,Os=4;class Gc{constructor(e){this.ctx=e}starPoints=0;roll=0;clear(e,t){this.ctx.clearRect(0,0,e,t)}static paintExtent(e){const{x:t,y:i,width:n,height:s}=e.bounds,r=t+n/2,o=i+s/2,l=e.angle%(2*Math.PI)!==0,c=Math.hypot(n,s)/2,h=l?c:n/2,d=l?c:s/2,u=Math.max(n,s)/2,p=e.brightness??0,f=p>0?Math.max(u*(1+nv*p),av*p)-u:0,g=p>0?u*(1+rv*p)-u:0,m=3*Xf*(e.blur??0)+1.5*iv*e.haloScale,v=Math.max(f,g,0)+m+2;return{x:r-h-v,y:o-d-v,width:2*(h+v),height:2*(d+v)}}paintInto(e,t,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-t.x,-t.y);const s=e.selected?{...e,selected:!1}:e;n?this.paintGhost(s,1.5):this.paintShape(s),this.ctx.restore()}paintShape(e){this.ctx.save(),this.ctx.globalAlpha=1-e.transparency;const t=e.blur??0;t>0&&(this.ctx.filter=`blur(${(Xf*t).toFixed(2)}px)`);const i=e.brightness??0;i>0&&this.paintDazzle(e,i),e.haloScale>0&&this.paintHalo(e),this.paintBase(e),this.ctx.restore(),e.selected&&this.paintSelectionHandles(e)}setStarPoints(e){this.starPoints=Math.max(0,Math.floor(e))}setRoll(e){this.roll=e}paintDazzle(e,t){const{x:i,y:n,width:s,height:r}=e.bounds,o=i+s/2,l=n+r/2,c=Math.max(s,r)/2,h=Math.max(c*(1+nv*t),av*t);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const d=this.ctx.createRadialGradient(o,l,0,o,l,h);for(let u=0;u<=sv;u++){const p=u/sv,f=1/(1+24*p*p);this.ctx.globalAlpha=1,d.addColorStop(p,this.withAlpha(e.color,f*t*.55))}if(this.ctx.fillStyle=d,this.ctx.beginPath(),this.ctx.arc(o,l,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const u=c*(1+rv*t);this.ctx.lineWidth=Math.max(1,c*.12),this.ctx.lineCap="round";for(let p=0;p<this.starPoints;p++){const f=p/this.starPoints*Math.PI*2+this.roll,g=o+Math.cos(f)*u,m=l+Math.sin(f)*u,v=this.ctx.createLinearGradient(o,l,g,m);v.addColorStop(0,this.withAlpha(e.color,t*.55)),v.addColorStop(.35,this.withAlpha(e.color,t*.22)),v.addColorStop(1,this.withAlpha(e.color,0)),this.ctx.strokeStyle=v,this.ctx.beginPath(),this.ctx.moveTo(o,l),this.ctx.lineTo(g,m),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(e,t){if(t<=0)return e.color;const i=/^#([0-9a-f]{6})$/i.exec(e.color.trim());if(!i)return e.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*t);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(e,t){const i=Math.max(0,Math.min(1,t)),n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!n)return e;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(e){this.ctx.fillStyle=this.dazzledFill(e,e.brightness??0),this.tracePath(e),this.ctx.fill()}paintGhost(e,t){this.ctx.save(),this.tracePath(e),this.ctx.setLineDash([t*3,t*2]),this.ctx.lineWidth=t,this.ctx.strokeStyle=e.color,this.ctx.stroke(),this.ctx.restore()}tracePath(e){if(this.ctx.beginPath(),e.kind==="oval"){const{x:t,y:i,width:n,height:s}=e.bounds,r=n/2,o=s/2;this.ctx.ellipse(t+r,i+o,r,o,e.angle,0,2*Math.PI)}else{const{x:t,y:i,width:n,height:s}=e.bounds;this.ctx.save(),this.ctx.translate(t+n/2,i+s/2),this.ctx.rotate(e.angle),this.ctx.translate(-n/2,-s/2),e.points.forEach((r,o)=>{o===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(e){this.ctx.save(),this.ctx.shadowColor=e.color,this.ctx.shadowBlur=iv*e.haloScale,this.paintBase(e),this.ctx.restore()}paintSelectionHandles(e){this.paintHandleFrame(Tt.handlePointsFor(e),{includeRotate:!0}),e.kind==="polygon"&&this.paintVertexHandles(e)}paintVertexHandles(e){this.ctx.fillStyle="#39f";for(const t of Tt.vertexPointsFor(e))this.ctx.beginPath(),this.ctx.ellipse(t.x,t.y,Os,Os,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(e){this.paintOutline(Tt.handlePointsFor(e))}paintSelectionOnly(e){this.paintSelectionHandles(e)}paintPictureFrame(e,t,i){const n=this.ctx;if(n.save(),e&&e.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of t){const r=Gc.landmarkColour(s.residualDeg),o=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=o+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Os+2,Os+2,0,0,2*Math.PI),n.stroke()),s.scene&&(n.strokeStyle=r,n.lineWidth=1,n.beginPath(),n.moveTo(s.picture.x,s.picture.y),n.lineTo(s.scene.x,s.scene.y),n.stroke(),n.fillStyle=r,n.beginPath(),n.ellipse(s.scene.x,s.scene.y,Os,Os,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=o,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Os+2,Os+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Os+5,s.picture.y-Os-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}static landmarkColour(e){return e===void 0?"#ffb000":e<=1?"#3c3":e<=3?"#ffb000":"#f33"}paintLabel(e,t,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const o=r.measureText(e).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(t-3,i-2,o+6,s+4),r.fillStyle=n,r.fillText(e,t,i),r.restore()}paintGroupHandles(e){this.paintHandleFrame(Tt.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 i of Vy){const n=e[i];this.ctx.fillRect(n.x-ph,n.y-ph,Wf,Wf)}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,ph+1,ph+1,0,0,2*Math.PI),this.ctx.fill())}}class Bn extends Error{constructor(e,t,i){const n=e==="rejected"&&typeof t=="string"?t:void 0,s=e==="rejected"?i:t;super(n??e,s===void 0?void 0:{cause:s}),this.kind=e,this.name="NarrativeError",this.detail=n}detail}class ru{static KNOWN_TAGS=["landing","trace","aerial observation","project sign","paralysis","contact","occupants","close encounter","photograph","radar","electromagnetic effect"];static RULES=[{draft:`Sizes are ANGULAR, in degrees, and never metric — the format stores no physical size, because an
|
|
62
|
+
<p id="cloud-status" role="status"></p></div>`}static localize(e,t){for(const i of e.querySelectorAll("[data-text]"))i.textContent=t[i.dataset.text];for(const i of e.querySelectorAll("[data-placeholder]"))i.placeholder=t[i.dataset.placeholder]}}const Hc=["en","fr","es","it"],yx={en:()=>je(()=>Promise.resolve().then(()=>Zx),void 0,import.meta.url).then(a=>a.ufoMessages_en),fr:()=>je(()=>import("./UfoMessages_fr-bJNAf-AU.js"),[],import.meta.url).then(a=>a.ufoMessages_fr),es:()=>je(()=>import("./UfoMessages_es-LFW_B5H2.js"),[],import.meta.url).then(a=>a.ufoMessages_es),it:()=>je(()=>import("./UfoMessages_it-B-jnc4M-.js"),[],import.meta.url).then(a=>a.ufoMessages_it)};function Mx(a){return yx[a]()}const wx={en:()=>je(()=>Promise.resolve().then(()=>px),void 0,import.meta.url).then(a=>a.sightingEditorMessages_en),fr:()=>je(()=>import("./SightingEditorMessages_fr-CvRVAmAa.js"),[],import.meta.url).then(a=>a.sightingEditorMessages_fr),es:()=>je(()=>import("./SightingEditorMessages_es-BTlk4NH4.js"),[],import.meta.url).then(a=>a.sightingEditorMessages_es),it:()=>je(()=>import("./SightingEditorMessages_it--JZErvoc.js"),[],import.meta.url).then(a=>a.sightingEditorMessages_it)};function Hy(a){return wx[a]()}function xx(a){switch(a){case"fr":return je(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr);case"es":return je(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(e=>e.tagNames_es);case"it":return je(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(e=>e.tagNames_it);default:return Promise.resolve({})}}const Sx={en:()=>je(()=>import("./BodyEditorMessages_en-D6h_2jc7.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_en),fr:()=>je(()=>import("./BodyEditorMessages_fr-CG8xnMzM.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_fr),es:()=>je(()=>import("./BodyEditorMessages_es-DfSa9Yth.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_es),it:()=>je(()=>import("./BodyEditorMessages_it-CIClW1lP.js"),[],import.meta.url).then(a=>a.bodyEditorMessages_it)},Ex={en:()=>je(()=>Promise.resolve().then(()=>L6),void 0,import.meta.url).then(a=>a.caseEditorMessages_en),fr:()=>je(()=>import("./CaseEditorMessages_fr-WW3gM38H.js"),[],import.meta.url).then(a=>a.caseEditorMessages_fr),es:()=>je(()=>import("./CaseEditorMessages_es-D5DtN8Q1.js"),[],import.meta.url).then(a=>a.caseEditorMessages_es),it:()=>je(()=>import("./CaseEditorMessages_it-CN6g0t9U.js"),[],import.meta.url).then(a=>a.caseEditorMessages_it)};function _x(a){return Ex[a]()}function N6(a){return Sx[a]()}function Gy(a){switch(a){case"fr":return je(()=>import("./SceneNames_fr-BFN6x9Z7.js"),[],import.meta.url).then(e=>e.sceneNames_fr);case"es":return je(()=>import("./SceneNames_es-BuZsPlTw.js"),[],import.meta.url).then(e=>e.sceneNames_es);case"it":return je(()=>import("./SceneNames_it-BOuH3VIw.js"),[],import.meta.url).then(e=>e.sceneNames_it);default:return Promise.resolve(void 0)}}function Ax(a){switch(a){case"fr":return je(()=>import("./CloudEditorMessages_fr-CpKSij1v.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_fr);case"es":return je(()=>import("./CloudEditorMessages_es-ozb6J7KN.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_es);case"it":return je(()=>import("./CloudEditorMessages_it-CPHBLAsn.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_it);default:return Promise.resolve(void 0)}}class tn{static CHROME="2.6em";static UNBOUNDED=9999;static fit(e){const t=[...e.querySelectorAll('input[type="number"]')];for(const i of t)i.style.width=`calc(${tn.charsFor(i)}ch + ${tn.CHROME})`,tn.hold(i,!0),i.dataset.held!==""&&(i.dataset.held="",i.addEventListener("input",()=>tn.hold(i)),i.addEventListener("change",()=>tn.hold(i,!0)));return t.length}static hold(e,t=!1){const i=tn.heldValue(e.value,e,t);i!==e.value&&(e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})))}static heldValue(e,t,i=!1){if(e===""||!/^-?\d+(\.\d+)?$/.test(e))return e;const n=tn.wholeOnly(t.step)?0:tn.decimalsOf(t.step),s=e.indexOf("."),r=s>=0&&e.length-s-1>n?n===0?e.slice(0,s):e.slice(0,s+n+1):e,o=Number(r),l=t.min===""?void 0:Number(t.min),c=t.max===""?void 0:Number(t.max);return c!==void 0&&o>c?String(c):i&&l!==void 0&&o<l?String(l):r}static charsFor(e){const t=o=>o===""?void 0:Math.abs(Number(o)),i=Math.max(t(e.max)??tn.UNBOUNDED,t(e.min)??0),n=String(Math.floor(Number.isFinite(i)?i:tn.UNBOUNDED)).length,s=e.min!==""&&Number(e.min)<0?1:0,r=tn.wholeOnly(e.step)?0:tn.decimalsOf(e.step);return n+s+(r>0?r+1:0)}static decimalsOf(e){if(e===""||e==="any")return 2;const t=e.indexOf(".");return Math.max(2,t<0?0:e.length-t-1)}static wholeOnly(e){return e!==""&&e!=="any"&&!e.includes(".")}}function Tx(a,e,t,i,n="en"){let s=zy;a.innerHTML=tv.html(s),tn.fit(a);const r=A=>a.querySelector("#"+A),o=A=>Number(r(A).value),l=a.querySelector("#cloud-layer"),c=a.querySelector("#cloud-instance"),h=a.querySelector("#cloud-status"),d=()=>r("cloud-scope").value,u=()=>Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime))[Number(l.value)],p=["east","north","base","thickness","width","depth","rotation","density","darkness"],f=()=>{const A=u()?.instances?.find(C=>C.id===c.value);for(const C of p)r(`instance-${C}`).disabled=!A;if(a.querySelector("#cloud-instance-delete").disabled=!A,a.querySelector("#cloud-instance-point").disabled=!A,!A)return;const R=[A.eastM,A.northM,A.baseM,A.thicknessM,A.widthM,A.depthM,A.rotationDeg,A.density,A.darkness];p.forEach((C,k)=>{r(`instance-${C}`).value=R[k]===void 0?"":String(Math.round(R[k]*100)/100)})};let g=-1;const m=()=>{const A=e.ufoElement.currentTime,R=a.getRootNode().activeElement;if(A===g&&R instanceof HTMLInputElement&&a.contains(R))return;g=A;const C=Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime)),k=l.selectedOptions[0]?.dataset.layerId;l.replaceChildren(...C.map((V,Z)=>{const K=new Option(`${Z+1} · ${V.type} · ${Math.round(V.baseM)} m`,String(Z));return K.dataset.layerId=V.id,K}));const z=C.findIndex(V=>V.id===k);l.value=String(Math.max(0,z));const L=u();for(const V of["cloud-type","cloud-base","cloud-thickness","cloud-cover","cloud-size","cloud-density","cloud-darkness","cloud-crystal-alignment","cloud-wind-direction","cloud-wind-speed","cloud-seed","cloud-layer-delete","cloud-instance-add"])a.querySelector("#"+V).disabled=!L;if(r("cloud-crystal-alignment").closest("label").hidden=L?.type!=="cirrus",!L){c.replaceChildren(new Option("—","")),f();return}r("cloud-type").value=L.type;for(const[V,Z]of Object.entries({base:L.baseM,thickness:L.thicknessM,cover:L.coverage*100,size:L.sizeM,density:L.density}))r(`cloud-${V}`).value=String(Math.round(Z*100)/100);r("cloud-darkness").value=String(Math.round((L.darkness??hi(e.ufoElement.sighting,A).cloudDarkness)*100)/100);const N=r("cloud-crystal-alignment");N.value=String(Math.round((L.iceCrystalAlignment??Od)*100)/100),r("cloud-wind-direction").value=L.windDirectionDeg===void 0?"":String(Math.round(L.windDirectionDeg*10)/10),r("cloud-wind-speed").value=L.windSpeed===void 0?"":String(Math.round(L.windSpeed*100)/100),r("cloud-seed").value=L.seed===void 0?"":String(L.seed);const F=c.value;c.replaceChildren(new Option(s.none,""),...(L.instances??[]).map((V,Z)=>new Option(`${s.cloud} ${Z+1}`,V.id))),c.value=L.instances?.some(V=>V.id===F)?F:"",f()},v=(A,R=!0)=>{if(!u())return;e.ufoElement.pause(),t(R);const C=e.ufoElement.currentTime,k=e.ufoElement.sighting;gx(k.weatherTrack,hi(k,C),C,u().id,A,d()),e.ufoElement.refresh(),h.textContent=d()==="observation"?s.savedAcrossObservation:`${(C/1e3).toFixed(1)} s · ${s.savedAtThisTime}`};a.addEventListener("focusin",()=>e.ufoElement.pause()),l.addEventListener("change",()=>{c.value="",m()}),c.addEventListener("change",f);const x=A=>{e.ufoElement.pause(),t();const R=e.ufoElement.sighting,C=e.ufoElement.currentTime;Uy(R.weatherTrack,hi(R,C),C,A,d()),e.ufoElement.refresh(),m()};a.querySelector("#cloud-layer-add").addEventListener("click",()=>{const A=hi(e.ufoElement.sighting,e.ufoElement.currentTime),R={id:crypto.randomUUID(),type:"cumulus",baseM:1500,thicknessM:800,coverage:.5,sizeM:1400,density:1,darkness:A.cloudDarkness};x(C=>[...C,R]),l.value=String(Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime)).findIndex(C=>C.id===R.id)),m()}),a.querySelector("#cloud-layer-delete").addEventListener("click",()=>{const A=u()?.id;A&&x(R=>R.filter(C=>C.id!==A))});const y=e.ufoElement.canvasElement,b=r("cloud-manipulate");let w;const S=A=>{const R=y.getBoundingClientRect();return{x:(A.clientX-R.left)/R.width*2-1,y:1-(A.clientY-R.top)/R.height*2}};b.addEventListener("change",()=>{y.style.touchAction=b.checked?"none":"",y.style.cursor=b.checked?"crosshair":""}),y.addEventListener("click",A=>{b.checked&&(A.preventDefault(),A.stopImmediatePropagation())},!0),y.addEventListener("pointerdown",A=>{if(!b.checked||A.button!==0)return;A.preventDefault(),A.stopImmediatePropagation(),e.ufoElement.pause();const R=S(A),C=e.pickCloudAt(R.x,R.y);if(!C){h.textContent=s.noCloudHere;return}const k=Ks(hi(e.ufoElement.sighting,e.ufoElement.currentTime));l.value=String(k.findIndex(N=>N.id===C.layerId)),m(),c.value=C.instanceId,f();const L=(d()==="observation"?e.ufoElement.sighting.weatherTrack.allKeyframes.map(N=>N.weather):[hi(e.ufoElement.sighting,e.ufoElement.currentTime)]).flatMap(N=>Ks(N).filter(F=>F.id===C.layerId).flatMap(F=>(F.instances??[]).filter(V=>V.id===C.instanceId).map(V=>V.baseM)));w={minBase:Math.min(...L),pointerId:A.pointerId,id:C.instanceId,center:C.center,ray:e.cloudDirectionAt(R.x,R.y),delta:{x:0,y:0,z:0}},y.setPointerCapture(A.pointerId),y.style.cursor="grabbing",h.textContent=s.cloudSelected},!0),y.addEventListener("pointermove",A=>{if(!w||A.pointerId!==w.pointerId)return;A.preventDefault(),A.stopImmediatePropagation();const R=S(A),C=bx(w.ray,e.cloudDirectionAt(R.x,R.y),w.center);if(!C)return;C.y=Math.max(C.y,-w.minBase);const k=w.delta,z=w.id;v(L=>({...L,instances:L.instances?.map(N=>N.id!==z?N:{...N,eastM:N.eastM+C.x-k.x,northM:N.northM-C.z+k.z,baseM:N.baseM+C.y-k.y})})),w.delta=C,f()},!0);const _=A=>{!w||A.pointerId!==w.pointerId||(w=void 0,y.hasPointerCapture(A.pointerId)&&y.releasePointerCapture(A.pointerId),y.style.cursor=b.checked?"crosshair":"")};y.addEventListener("pointerup",_),y.addEventListener("pointercancel",_),y.addEventListener("lostpointercapture",_);const M={"cloud-type":"type","cloud-base":"baseM","cloud-thickness":"thicknessM","cloud-cover":"coverage","cloud-size":"sizeM","cloud-density":"density","cloud-darkness":"darkness","cloud-crystal-alignment":"iceCrystalAlignment"};for(const[A,R]of Object.entries(M)){const C=()=>{if(r(A).value===""||!r(A).validity.valid)return;const k=A==="cloud-type"?r(A).value:o(A)/(A==="cloud-cover"?100:1);v(z=>({...z,[R]:k}),A!=="cloud-crystal-alignment")};r(A).addEventListener(A==="cloud-type"?"change":"input",C)}for(const[A,R]of[["cloud-wind-direction","windDirectionDeg"],["cloud-wind-speed","windSpeed"],["cloud-seed","seed"]])r(A).addEventListener("input",()=>{r(A).validity.valid&&v(C=>({...C,[R]:r(A).value===""?void 0:o(A)}))});a.querySelector("#cloud-instance-add").addEventListener("click",()=>{const A=u();if(!A)return;const R=crypto.randomUUID(),C=e.ufoElement.sighting,k=e.ufoElement.currentTime,z=at(C,k),L=su(k,C.weatherTrack,hi(C,0),at(C,0),z,A.id),N=e.cloudDirectionAt(0,0),F=A.baseM+A.thicknessM*.4-(z?.elevationM??0)-1.6,V=F*N.y>0?Math.max(500,Math.min(2e4,F/N.y)):5e3,Z={id:R,eastM:L.x+N.x*V,northM:-(L.z+N.z*V),baseM:A.baseM,thicknessM:A.thicknessM,widthM:1800,depthM:1200,rotationDeg:0,density:1,darkness:A.darkness};v(K=>({...K,instances:[...K.instances??[],Z]})),m(),c.value=R,f(),h.textContent+=s.cloudAdded}),a.querySelector("#cloud-instance-delete").addEventListener("click",()=>{const A=c.value;A&&(v(R=>({...R,instances:R.instances?.filter(C=>C.id!==A)})),m())}),a.querySelector("#cloud-instance-point").addEventListener("click",()=>{const A=u(),R=A?.instances?.find(K=>K.id===c.value);if(!R)return;e.ufoElement.pause();const C=e.ufoElement.sighting,k=e.ufoElement.currentTime,z=at(C,k),L=su(k,C.weatherTrack,hi(C,0),at(C,0),z,A.id),N=R.eastM-L.x,F=R.northM+L.z,V=Math.hypot(N,F),Z=R.baseM+R.thicknessM/2-(z?.elevationM??0)-1.6-V**2/(2*6371e3);V===0&&Z===0||i((Math.atan2(N,F)*180/Math.PI+360)%360,Math.atan2(Z,V)*180/Math.PI)}),n!=="en"&&Ax(n).then(A=>{A&&(s=A,tv.localize(a,s),g=-1,m())});const T=["eastM","northM","baseM","thicknessM","widthM","depthM","rotationDeg","density","darkness"];return p.forEach((A,R)=>r(`instance-${A}`).addEventListener("input",()=>{const C=c.value,k=r(`instance-${A}`);if(!C||!k.validity.valid||k.value===""&&A!=="darkness")return;const z=T[R],L=k.value===""?void 0:o(`instance-${A}`);v(N=>({...N,instances:N.instances?.map(F=>F.id!==C?F:{...F,[z]:L})}))})),{sync:m,stopManipulation(){w=void 0,b.checked=!1,y.style.touchAction="",y.style.cursor=""},reset(){w=void 0,b.checked=!1,y.style.cursor="",y.style.touchAction="",c.value="",g=-1,m()}}}const Vy=["nw","n","ne","e","se","s","sw","w"],Ix=24,ta=8,Wy=3,Dx=8;function mc(a,e,t){const i=a.x-e.x,n=a.y-e.y,s=Math.cos(t),r=Math.sin(t);return{x:e.x+i*s-n*r,y:e.y+i*r+n*s}}function Ta(a){return{x:a.x+a.width/2,y:a.y+a.height/2}}const Rx={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 Tt{static handlePointsFor(e){const{x:t,y:i,width:n,height:s}=e.bounds,r={nw:{x:t,y:i},n:{x:t+n/2,y:i},ne:{x:t+n,y:i},e:{x:t+n,y:i+s/2},se:{x:t+n,y:i+s},s:{x:t+n/2,y:i+s},sw:{x:t,y:i+s},w:{x:t,y:i+s/2},rotate:{x:t+n/2,y:i-Ix}},o=Ta(e.bounds),l={};for(const c of Object.keys(r))l[c]=mc(r[c],o,e.angle);return l}static hitTestHandle(e,t,i=8,n=[...Vy,"rotate"]){const s=Tt.handlePointsFor(e);for(const r of n)if(Math.hypot(t.x-s[r].x,t.y-s[r].y)<=i)return r}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 n=((Tt.HANDLE_DIRECTION_DEG[e]+t*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(e,t,i,n){const s=Ta(e),r=mc(n,s,-t),{x:o,y:l,width:c,height:h}=e,d=Rx[i];let u=o,p=l,f=o+c,g=l+h;return d.left&&(u=Math.min(r.x,f-ta)),d.right&&(f=Math.max(r.x,u+ta)),d.top&&(p=Math.min(r.y,g-ta)),d.bottom&&(g=Math.max(r.y,p+ta)),{x:u,y:p,width:f-u,height:g-p}}static resizeShape(e,t,i){if(t==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=e.bounds,r=Tt.resizeBounds(e.bounds,e.angle,t,i);if(e.kind==="oval")return{...e,bounds:r};const o=n===0?1:r.width/n,l=s===0?1:r.height/s;return{...e,bounds:r,points:e.points.map(c=>({x:c.x*o,y:c.y*l}))}}static rotateShape(e,t){const i=Ta(e.bounds),n=Math.atan2(t.y-i.y,t.x-i.x)+Math.PI/2;return{...e,angle:n}}static groupBoundsFor(e){const t=Math.min(...e.map(r=>r.x)),i=Math.min(...e.map(r=>r.y)),n=Math.max(...e.map(r=>r.x+r.width)),s=Math.max(...e.map(r=>r.y+r.height));return{x:t,y:i,width:n-t,height:s-i}}static vertexPointsFor(e){const t=Ta(e.bounds);return e.points.map(i=>mc({x:e.bounds.x+i.x,y:e.bounds.y+i.y},t,e.angle))}static hitTestVertex(e,t,i=Dx){const n=Tt.vertexPointsFor(e);let s,r=i;return n.forEach((o,l)=>{const c=Math.hypot(t.x-o.x,t.y-o.y);c<=r&&(r=c,s=l)}),s}static toLocalPoint(e,t){const i=Ta(e.bounds),n=mc(t,i,-e.angle);return{x:n.x-e.bounds.x,y:n.y-e.bounds.y}}static moveVertex(e,t,i){const n=e.points.map((d,u)=>u===t?Tt.toLocalPoint(e,i):d),s=Math.min(...n.map(d=>d.x)),r=Math.min(...n.map(d=>d.y)),o=Math.max(...n.map(d=>d.x)),l=Math.max(...n.map(d=>d.y)),c={x:e.bounds.x+s,y:e.bounds.y+r,width:o-s,height:l-r},h=n.map(d=>({x:d.x-s,y:d.y-r}));return{...e,bounds:c,points:h}}static insertVertexNear(e,t){const i=Tt.toLocalPoint(e,t),{points:n}=e;let s=n.length-1,r=1/0;for(let l=0;l<n.length;l++){const c=n[l],h=n[(l+1)%n.length],d=Tt.distanceToSegment(i,c,h);d<r&&(r=d,s=l)}const o=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...e,points:o}}static distanceToSegment(e,t,i){const n=i.x-t.x,s=i.y-t.y,r=n*n+s*s,o=r===0?0:Math.max(0,Math.min(1,((e.x-t.x)*n+(e.y-t.y)*s)/r)),l=t.x+o*n,c=t.y+o*s;return Math.hypot(e.x-l,e.y-c)}static deleteVertex(e,t){return e.points.length<=Wy?e:{...e,points:e.points.filter((i,n)=>n!==t)}}}class dp{constructor(e){this.members=e}bounds(){return Tt.groupBoundsFor(this.members.map(e=>e.shape.bounds))}scaleTo(e){const t=this.bounds(),i=t.width===0?1:e.width/t.width,n=t.height===0?1:e.height/t.height;return this.members.map(({sourceId:s,shape:r})=>{const o=Math.max(r.bounds.width*i,ta),l=Math.max(r.bounds.height*n,ta),c=e.x+(r.bounds.x-t.x)*i,h=e.y+(r.bounds.y-t.y)*n,d={x:c,y:h,width:o,height:l};return r.kind==="oval"?{sourceId:s,shape:{...r,bounds:d}}:{sourceId:s,shape:{...r,bounds:d,points:r.points.map(u=>({x:u.x*i,y:u.y*n}))}}})}resize(e,t){return this.scaleTo(Tt.resizeBounds(this.bounds(),0,e,t))}rotate(e,t){const i=Ta(this.bounds()),n=r=>Math.atan2(r.y-i.y,r.x-i.x),s=n(e)-n(t);return this.members.map(({sourceId:r,shape:o})=>{const l=Ta(o.bounds),c=mc(l,i,s),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:r,shape:{...o,bounds:h,angle:o.angle+s}}})}}const Wf=6,ph=Wf/2,iv=20,Xf=24,nv=9,sv=6,rv=7,av=6,Os=4;class Gc{constructor(e){this.ctx=e}starPoints=0;roll=0;clear(e,t){this.ctx.clearRect(0,0,e,t)}static paintExtent(e){const{x:t,y:i,width:n,height:s}=e.bounds,r=t+n/2,o=i+s/2,l=e.angle%(2*Math.PI)!==0,c=Math.hypot(n,s)/2,h=l?c:n/2,d=l?c:s/2,u=Math.max(n,s)/2,p=e.brightness??0,f=p>0?Math.max(u*(1+nv*p),av*p)-u:0,g=p>0?u*(1+rv*p)-u:0,m=3*Xf*(e.blur??0)+1.5*iv*e.haloScale,v=Math.max(f,g,0)+m+2;return{x:r-h-v,y:o-d-v,width:2*(h+v),height:2*(d+v)}}paintInto(e,t,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-t.x,-t.y);const s=e.selected?{...e,selected:!1}:e;n?this.paintGhost(s,1.5):this.paintShape(s),this.ctx.restore()}paintShape(e){this.ctx.save(),this.ctx.globalAlpha=1-e.transparency;const t=e.blur??0;t>0&&(this.ctx.filter=`blur(${(Xf*t).toFixed(2)}px)`);const i=e.brightness??0;i>0&&this.paintDazzle(e,i),e.haloScale>0&&this.paintHalo(e),this.paintBase(e),this.ctx.restore(),e.selected&&this.paintSelectionHandles(e)}setStarPoints(e){this.starPoints=Math.max(0,Math.floor(e))}setRoll(e){this.roll=e}paintDazzle(e,t){const{x:i,y:n,width:s,height:r}=e.bounds,o=i+s/2,l=n+r/2,c=Math.max(s,r)/2,h=Math.max(c*(1+nv*t),av*t);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const d=this.ctx.createRadialGradient(o,l,0,o,l,h);for(let u=0;u<=sv;u++){const p=u/sv,f=1/(1+24*p*p);this.ctx.globalAlpha=1,d.addColorStop(p,this.withAlpha(e.color,f*t*.55))}if(this.ctx.fillStyle=d,this.ctx.beginPath(),this.ctx.arc(o,l,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const u=c*(1+rv*t);this.ctx.lineWidth=Math.max(1,c*.12),this.ctx.lineCap="round";for(let p=0;p<this.starPoints;p++){const f=p/this.starPoints*Math.PI*2+this.roll,g=o+Math.cos(f)*u,m=l+Math.sin(f)*u,v=this.ctx.createLinearGradient(o,l,g,m);v.addColorStop(0,this.withAlpha(e.color,t*.55)),v.addColorStop(.35,this.withAlpha(e.color,t*.22)),v.addColorStop(1,this.withAlpha(e.color,0)),this.ctx.strokeStyle=v,this.ctx.beginPath(),this.ctx.moveTo(o,l),this.ctx.lineTo(g,m),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(e,t){if(t<=0)return e.color;const i=/^#([0-9a-f]{6})$/i.exec(e.color.trim());if(!i)return e.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*t);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(e,t){const i=Math.max(0,Math.min(1,t)),n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!n)return e;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(e){this.ctx.fillStyle=this.dazzledFill(e,e.brightness??0),this.tracePath(e),this.ctx.fill()}paintGhost(e,t){this.ctx.save(),this.tracePath(e),this.ctx.setLineDash([t*3,t*2]),this.ctx.lineWidth=t,this.ctx.strokeStyle=e.color,this.ctx.stroke(),this.ctx.restore()}tracePath(e){if(this.ctx.beginPath(),e.kind==="oval"){const{x:t,y:i,width:n,height:s}=e.bounds,r=n/2,o=s/2;this.ctx.ellipse(t+r,i+o,r,o,e.angle,0,2*Math.PI)}else{const{x:t,y:i,width:n,height:s}=e.bounds;this.ctx.save(),this.ctx.translate(t+n/2,i+s/2),this.ctx.rotate(e.angle),this.ctx.translate(-n/2,-s/2),e.points.forEach((r,o)=>{o===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(e){this.ctx.save(),this.ctx.shadowColor=e.color,this.ctx.shadowBlur=iv*e.haloScale,this.paintBase(e),this.ctx.restore()}paintSelectionHandles(e){this.paintHandleFrame(Tt.handlePointsFor(e),{includeRotate:!0}),e.kind==="polygon"&&this.paintVertexHandles(e)}paintVertexHandles(e){this.ctx.fillStyle="#39f";for(const t of Tt.vertexPointsFor(e))this.ctx.beginPath(),this.ctx.ellipse(t.x,t.y,Os,Os,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(e){this.paintOutline(Tt.handlePointsFor(e))}paintSelectionOnly(e){this.paintSelectionHandles(e)}paintPictureFrame(e,t,i){const n=this.ctx;if(n.save(),e&&e.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of t){const r=Gc.landmarkColour(s.residualDeg),o=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=o+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Os+2,Os+2,0,0,2*Math.PI),n.stroke()),s.scene&&(n.strokeStyle=r,n.lineWidth=1,n.beginPath(),n.moveTo(s.picture.x,s.picture.y),n.lineTo(s.scene.x,s.scene.y),n.stroke(),n.fillStyle=r,n.beginPath(),n.ellipse(s.scene.x,s.scene.y,Os,Os,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=o,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Os+2,Os+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Os+5,s.picture.y-Os-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}static landmarkColour(e){return e===void 0?"#ffb000":e<=1?"#3c3":e<=3?"#ffb000":"#f33"}paintLabel(e,t,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const o=r.measureText(e).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(t-3,i-2,o+6,s+4),r.fillStyle=n,r.fillText(e,t,i),r.restore()}paintGroupHandles(e){this.paintHandleFrame(Tt.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 i of Vy){const n=e[i];this.ctx.fillRect(n.x-ph,n.y-ph,Wf,Wf)}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,ph+1,ph+1,0,0,2*Math.PI),this.ctx.fill())}}class Bn extends Error{constructor(e,t,i){const n=e==="rejected"&&typeof t=="string"?t:void 0,s=e==="rejected"?i:t;super(n??e,s===void 0?void 0:{cause:s}),this.kind=e,this.name="NarrativeError",this.detail=n}detail}class ru{static KNOWN_TAGS=["landing","trace","aerial observation","project sign","paralysis","contact","occupants","close encounter","photograph","radar","electromagnetic effect"];static RULES=[{draft:`Sizes are ANGULAR, in degrees, and never metric — the format stores no physical size, because an
|
|
63
63
|
observer perceives an angle and a size only follows from a distance nobody measured. Convert the
|
|
64
64
|
comparisons an account gives: the full Moon and the Sun are both about 0.5 degrees across, a
|
|
65
65
|
thumbnail at arm's length about 1.5, a fist about 10. Where the account gives no comparison, work
|
|
@@ -204,6 +204,11 @@ ${e.ask}`,"Answer by calling draft_recording."),t.join(`
|
|
|
204
204
|
<button class="group-tab" type="button" aria-controls="group-reference" aria-expanded="false"><span id="label-reference-group">Pictures</span></button>
|
|
205
205
|
<button class="group-tab" type="button" aria-controls="group-shape" aria-expanded="false"><span id="label-shape-group">Phenomenon</span></button>
|
|
206
206
|
<button class="group-tab" type="button" aria-controls="group-file" aria-expanded="false"><span id="label-file-group">File</span></button>
|
|
207
|
+
<!-- Step back and forward through what was edited, whichever group it was edited in: the File group's text editor keeps the history (see SightingEditorElement.undo). -->
|
|
208
|
+
<span class="history" role="group">
|
|
209
|
+
<button id="undo" type="button" class="icon-btn" title="Undo" aria-label="Undo" disabled>↶</button>
|
|
210
|
+
<button id="redo" type="button" class="icon-btn" title="Redo" aria-label="Redo" disabled>↷</button>
|
|
211
|
+
</span>
|
|
207
212
|
<!-- What an element that holds this editor puts after the last tab (see CaseEditorElement): a mark of its own, which takes its room whether it shows or not. -->
|
|
208
213
|
<slot name="tab-status"></slot>
|
|
209
214
|
</div>
|
|
@@ -772,20 +777,6 @@ ${e.ask}`,"Answer by calling draft_recording."),t.join(`
|
|
|
772
777
|
SightingEditorElement.refreshParamSummary); a value a data source supplied rather than the
|
|
773
778
|
author is marked, which is the one thing the form itself never showed at a glance. -->
|
|
774
779
|
<div id="param-summary" class="param-summary"></div>
|
|
775
|
-
<!-- The editor's own confirmation, NOT window.confirm(). A native dialog is suppressed outright in
|
|
776
|
-
several of the places this component is meant to run — a sandboxed iframe without allow-modals,
|
|
777
|
-
an embedded browser view — and a suppressed confirm() returns FALSE, which is indistinguishable
|
|
778
|
-
from the reader declining. Deleting a shape then did nothing at all, silently, with no way for
|
|
779
|
-
the page to know. Built from ordinary DOM, so nothing can decide not to show it. -->
|
|
780
|
-
<div id="confirm-overlay" class="confirm-overlay" hidden role="alertdialog" aria-modal="true" aria-labelledby="confirm-message">
|
|
781
|
-
<div class="confirm-box">
|
|
782
|
-
<p id="confirm-message"></p>
|
|
783
|
-
<div class="confirm-actions">
|
|
784
|
-
<button id="confirm-cancel" type="button">Cancel</button>
|
|
785
|
-
<button id="confirm-ok" type="button">Delete</button>
|
|
786
|
-
</div>
|
|
787
|
-
</div>
|
|
788
|
-
</div>
|
|
789
780
|
<div id="context-menu" class="context-menu" hidden role="menu">
|
|
790
781
|
<button id="context-group" type="button" role="menuitem">Group</button>
|
|
791
782
|
<button id="context-ungroup" type="button" role="menuitem">Ungroup</button>
|
|
@@ -1122,6 +1113,15 @@ select.weather-field:disabled {
|
|
|
1122
1113
|
gap: 0.35em;
|
|
1123
1114
|
margin-bottom: 0.5em;
|
|
1124
1115
|
}
|
|
1116
|
+
.history {
|
|
1117
|
+
display: inline-flex;
|
|
1118
|
+
gap: 0.2em;
|
|
1119
|
+
margin-inline-start: auto;
|
|
1120
|
+
}
|
|
1121
|
+
.history .icon-btn:disabled {
|
|
1122
|
+
opacity: 0.35;
|
|
1123
|
+
cursor: default;
|
|
1124
|
+
}
|
|
1125
1125
|
.group-tab, .subgroup-tab {
|
|
1126
1126
|
font: inherit;
|
|
1127
1127
|
font-weight: 600;
|
|
@@ -1552,42 +1552,6 @@ select.weather-field:disabled {
|
|
|
1552
1552
|
/* position:fixed (viewport-relative), left/top set from the triggering pointer event's own
|
|
1553
1553
|
clientX/clientY in JS — works the same regardless of which shadow tree this menu lives in or
|
|
1554
1554
|
how the page has scrolled, unlike an absolutely-positioned element nested under this host. */
|
|
1555
|
-
.confirm-overlay {
|
|
1556
|
-
position: fixed;
|
|
1557
|
-
inset: 0;
|
|
1558
|
-
z-index: 20;
|
|
1559
|
-
display: flex;
|
|
1560
|
-
align-items: center;
|
|
1561
|
-
justify-content: center;
|
|
1562
|
-
background: rgba(0, 0, 0, 0.45);
|
|
1563
|
-
}
|
|
1564
|
-
/* Same trap as .context-menu[hidden] below, and for the same reason: a class selector setting its
|
|
1565
|
-
own display outranks the UA sheet's [hidden] rule. */
|
|
1566
|
-
.confirm-overlay[hidden] {
|
|
1567
|
-
display: none;
|
|
1568
|
-
}
|
|
1569
|
-
.confirm-box {
|
|
1570
|
-
max-width: 26em;
|
|
1571
|
-
padding: 1.2em;
|
|
1572
|
-
background: light-dark(#fff, #1e1f22);
|
|
1573
|
-
color: light-dark(#222, #e6e6e6);
|
|
1574
|
-
border-radius: 6px;
|
|
1575
|
-
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
|
|
1576
|
-
font-size: 0.95em;
|
|
1577
|
-
}
|
|
1578
|
-
.confirm-box p {
|
|
1579
|
-
margin: 0 0 1em;
|
|
1580
|
-
}
|
|
1581
|
-
.confirm-actions {
|
|
1582
|
-
display: flex;
|
|
1583
|
-
justify-content: flex-end;
|
|
1584
|
-
gap: 0.6em;
|
|
1585
|
-
}
|
|
1586
|
-
.confirm-actions button {
|
|
1587
|
-
padding: 0.4em 1em;
|
|
1588
|
-
font: inherit;
|
|
1589
|
-
cursor: pointer;
|
|
1590
|
-
}
|
|
1591
1555
|
.context-menu {
|
|
1592
1556
|
position: fixed;
|
|
1593
1557
|
z-index: 10;
|
|
@@ -2836,7 +2800,7 @@ canvas[data-cursor="rotate"] {
|
|
|
2836
2800
|
`;class ul{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||t.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(t.length===0){const i=e.event.place?.[0];if(!i)return;t.push({t:0,lat:i.lat,lng:i.lng})}return new ul(t)}static TRAVEL_M=50;get travels(){return this.spanM>ul.TRAVEL_M}get moved(){return this.spanM>ul.STATIONARY_M}get spanM(){const e=this.box,t=(e.south+e.north)/2,i=(e.west+e.east)/2;return Math.max(Math.abs(ci(t,e.east,t,e.west).x),Math.abs(ci(e.north,i,e.south,i).z))}get center(){const e=this.box;return{lat:(e.south+e.north)/2,lng:(e.west+e.east)/2}}boundsAround(e,t){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+t),e)/2;return{north:Zn(0,-s,i,n).lat,south:Zn(0,s,i,n).lat,east:Zn(s,0,i,n).lng,west:Zn(-s,0,i,n).lng}}get box(){const e=this.points.map(i=>i.lat),t=this.points.map(i=>i.lng);return{south:Math.min(...e),north:Math.max(...e),west:Math.min(...t),east:Math.max(...t)}}}class ts{constructor(e,t){this.rotationPassed=e,this.scale=t}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(e){const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>ts.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new ts(Math.max(1-(e.instrument.stabilization??0),ts.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,n=(d,u)=>Math.sin(2*Math.PI*d*t+u),[s,r,o,l,c,h]=ts.HZ;return{eastM:i*ts.SWAY_M*(.7*n(s,.3)+.3*n(l,1.9)),northM:i*ts.SWAY_M*(.6*n(o,2.2)+.4*n(c,.8)),upM:i*ts.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*ts.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(l,2.7)),pitchDeg:i*this.rotationPassed*ts.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(o,.4)),rollDeg:i*this.rotationPassed*ts.DRIFT_ROLL_DEG*n(s,2.9)}}}class Ft{constructor(e,t){this.stretches=e,this.rotationPassed=t}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(e){const t=ul.of(e);if(!t||t.points.length<2)return;const i=[];let n=0;for(let s=1;s<t.points.length;s++){const r=t.points[s-1],o=t.points[s],l=(o.t-r.t)/1e3;if(l<=0)continue;const c=ci(o.lat,o.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),p=u/l,f=Ft.stepHzFor(p);i.push({startMs:r.t,endMs:o.t,speedMPerS:p,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:f,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=f*l}for(let s=0;s<i.length;s++){const r=i[s-1],o=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=o===void 0||o.stepHz===0}if(i.some(s=>s.stepHz>0))return new Ft(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=Ft.of(e)?.offsetAt(t)??Ft.STILL;return i?n:Ft.add(n,ts.of(e)?.offsetAt(t))}static stepHzFor(e){return e<Ft.SLOWEST_WALK_M_PER_S||e>Ft.FASTEST_WALK_M_PER_S?0:Ft.REFERENCE_STEP_HZ*Math.pow(e/Ft.REFERENCE_SPEED_M_PER_S,Ft.CADENCE_EXPONENT)}offsetAt(e){return Ft.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/Ft.REFERENCE_SPEED_M_PER_S,n=(o,l,c,h)=>{if(o<0||o>Ft.JOLT_LASTS_MS)return;const d=o/1e3,u=Math.exp(-d/Ft.JOLT_DECAY_S)*Math.sin(2*Math.PI*Ft.JOLT_HZ*d),p=h*l*i*u;return{eastM:p*t.eastUnit,northM:p*t.northUnit,upM:-Math.abs(p)*.3,rollDeg:0,pitchDeg:-h*c*i*u*this.rotationPassed,yawDeg:0}},s=t.rampsOut?n(e-t.endMs,Ft.STOP_LURCH_M,Ft.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,Ft.START_LURCH_M,Ft.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(l=>e>=l.startMs&&e<=l.endMs);if(!t||t.stepHz===0)return Ft.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=Ft.SWAY_M*s*Math.cos(n/2),o=s*this.rotationPassed*t.speedMPerS/Ft.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:Ft.RISE_M_PER_M_PER_S*t.speedMPerS*s*Math.cos(n),rollDeg:Ft.HEAD_ROLL_DEG*o*Math.cos(n/2),pitchDeg:-1.25*o*Math.cos(n),yawDeg:Ft.HEAD_YAW_DEG*o*Math.cos(n/2)}}amplitudeAt(e,t){const i=1e3/e.stepHz,n=Math.min(i,(e.endMs-e.startMs)/2);if(n<=0)return 1;const s=t-e.startMs,r=e.endMs-t,o=Math.min(e.rampsIn?s/n:1,e.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(o,0)))/2}}class Vx{constructor(e,t){this.timeline=e,this.onFrame=t}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}this.onFrame(e,t)}}class to{static sessionDeclared=!1;static unlock(e){if(to.declarePlayback(),e.state!=="running")try{Promise.resolve(e.resume()).catch(()=>{});const t=e.createBufferSource();t.buffer=e.createBuffer(1,1,22050),t.connect(e.destination),t.start(0)}catch{}}static declarePlayback(){if(!(to.sessionDeclared||typeof navigator>"u")){to.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const uv=.05,pv=.08,fv=2,mv=3,Wx=14,Xx=.02;class $x{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}to.unlock(this.context)}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const i=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,i):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const i=this.context;if(!e||!i)return;const n=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,n,uv);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,uv)}buildSynthesizedVoice(e,t){const i=this.context;if(i)switch(e.kind){case"hum":return this.buildHum(i,t);case"whistle":return this.buildWhistle(i,t);case"rumble":return this.buildRumble(i,t);case"crackle":return this.buildCrackle(i,t);default:return}}buildHum(e,t){const i=e.createOscillator();i.type="sawtooth";const n=e.createOscillator();n.type="sawtooth";const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(e)),i.start(),n.start(),{key:t,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:n.frequency,ratio:1.006},{param:s.frequency,ratio:6}]}}buildWhistle(e,t){const i=e.createOscillator();i.type="sine";const n=e.createOscillator();n.type="sine",n.frequency.value=5;const s=e.createGain(),r=e.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(e)),i.start(),n.start(),{key:t,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=e.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(e)),i.start(),{key:t,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=e.createGain();s.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const o=e.createGain();return o.gain.value=0,r.connect(o).connect(s.gain),i.connect(n).connect(s).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[n,s,o],sources:[i,r],volumeParam:o.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(e)}catch(l){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",l);return}if(i!==this.voiceToken||!this.context)return;const r=n.createBufferSource();r.buffer=s,r.loop=!0;const o=n.createGain();o.gain.value=0,r.connect(o).connect(this.output(n)),r.start(),this.voice={key:t,nodes:[o],sources:[r],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 i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*fv),e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*fv),e.sampleRate),i=t.getChannelData(0);let n=0,s=0;for(let r=0;r<i.length;r++)n=(n+.02*(Math.random()*2-1))/1.02,i[r]=n,s=Math.max(s,Math.abs(n));if(s>0)for(let r=0;r<i.length;r++)i[r]/=s;return t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*mv),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(Xx*e.sampleRate)),s=Math.round(mv*Wx);for(let r=0;r<s;r++){const o=Math.floor(Math.random()*i.length),l=.4+Math.random()*.6;for(let c=0;c<n&&o+c<i.length;c++)i[o+c]=Math.max(i[o+c],l*(1-c/n))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const i=t.currentTime;e.volumeParam.cancelScheduledValues(i),e.volumeParam.setTargetAtTime(0,i,pv/3);const n=i+pv;for(const s of e.sources){s.onended=()=>{s.disconnect();for(const r of e.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of e.nodes)r.disconnect()}}}}class Xe{static svg(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="currentColor"/></svg>`}static outline(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}static solid(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="currentColor" fill-rule="evenodd"/></svg>`}static BOOKMARK="M6 3.5h12a.5.5 0 0 1 .5.5v16.5L12 16.8l-6.5 3.7V4a.5.5 0 0 1 .5-.5z";static PICTURE="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z";static PICTURE_HILLS="M4.5 17.5l4.5-6 3 4 2.5-3 5 5z";static PIN="M12 21.5s-6.5-5.7-6.5-10.8a6.5 6.5 0 0 1 13 0c0 5.1-6.5 10.8-6.5 10.8z";static PIN_HOLE="M12 8.4a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8z";static MILESTONES_OFF=Xe.outline(Xe.BOOKMARK);static MILESTONES_ON=Xe.solid(Xe.BOOKMARK);static PICTURES_OFF=Xe.outline(`${Xe.PICTURE}${Xe.PICTURE_HILLS}`);static PICTURES_ON=Xe.solid(`${Xe.PICTURE}${Xe.PICTURE_HILLS}`);static TRACE_LINE="M3 19.5l2.2-2.2 1.4 1.4L4.4 20.9zM8 14.5l2.2-2.2 1.4 1.4-2.2 2.2zM13 9.5l2.2-2.2 1.4 1.4-2.2 2.2z";static TRACE_MARK="M18.5 2.5l3.5 3.5-3.5 3.5-3.5-3.5z";static TRACES_OFF=Xe.outline(`${Xe.TRACE_LINE}${Xe.TRACE_MARK}`);static TRACES_ON=Xe.solid(`${Xe.TRACE_LINE}${Xe.TRACE_MARK}`);static MAP_OFF=Xe.outline(`${Xe.PIN}${Xe.PIN_HOLE}`);static MAP_ON=Xe.solid(`${Xe.PIN}${Xe.PIN_HOLE}`);static SHARE=Xe.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static FOLDED=Xe.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Xe.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Xe.svg("M7.4 5v14l11-7z");static PAUSE=Xe.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Xe.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zm12.5 2.5A4 4 0 0 0 12.5 8.5v7A4 4 0 0 0 14.5 12zM12.5 4.2v2.1a6.5 6.5 0 0 1 0 11.4v2.1a8.6 8.6 0 0 0 0-15.6z");static MUTED=Xe.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zM15 9.8l1.4-1.4 2.6 2.6 2.6-2.6 1.4 1.4-2.6 2.6 2.6 2.6-1.4 1.4-2.6-2.6-2.6 2.6-1.4-1.4 2.6-2.6z");static ENTER_FULLSCREEN=Xe.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Xe.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}function io(a){return[...a].sort((e,t)=>e.t-t.t)}function up(a,e){let t;for(const i of io(a)){if(i.t>e)break;t=i}return t}const pp=Math.PI/180,gh=180/Math.PI;class Ts{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*pp/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new Ts(e.projection,t,i)}degToPx(e){const t=e*pp;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*gh:2*Math.atan(e/(2*this.focalPx))*gh}angleDegToRadiusPx(e){const t=e*pp;return this.kind==="equidistant"?this.focalPx*t:this.focalPx*Math.tan(t)}halfWidthAngleDeg(e){return this.radiusPxToAngleDeg(this.canvasHeightPx*e/2)}radiusPxToAngleDeg(e){return this.kind==="equidistant"?e/this.focalPx*gh:Math.atan(e/this.focalPx)*gh}ofBounds(e){return{widthDeg:this.pxToDeg(e.width),heightDeg:this.pxToDeg(e.height)}}toBoundsSize(e){return{width:this.degToPx(e.widthDeg),height:this.degToPx(e.heightDeg)}}widthPx(e){return this.degToPx(lt.angularWidthDeg(e))}}class Ui{static fovOf(e,t){return at(e,t)?.fovDeg??Rt.fieldOfViewDeg(e.instrument)}static toAngular(e){this.eachKeyframe(e,(t,i)=>({...t,angular:i.ofBounds(t.bounds)}))}static toBounds(e){this.eachKeyframe(e,(t,i)=>{if(!t.angular)return t;const{width:n,height:s}=i.toBoundsSize(t.angular),r={x:t.bounds.x+(t.bounds.width-n)/2,y:t.bounds.y+(t.bounds.height-s)/2,width:n,height:s};if(t.kind!=="polygon")return{...t,bounds:r};const o=t.bounds.width===0?1:n/t.bounds.width,l=t.bounds.height===0?1:s/t.bounds.height;return{...t,bounds:r,points:t.points.map(c=>({x:c.x*o,y:c.y*l}))}})}static toAim(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);if(s&&Math.abs(s.x-t.bounds.x)<Ui.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<Ui.UNMOVED_PX)return t;const r=this.aimFrom(e,i,n,t.bounds);return r?{...t,aim:r}:t})}static UNMOVED_PX=.01;static aimOf(e,t,i){const n=Ts.of(e.instrument,lt.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,at(e,t),i)}static aimFrom(e,t,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(e),r=t.radiusPxToAngleDeg(n.x+n.width/2-s.x),o=t.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+o}}static toPosition(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);return s?{...t,bounds:{...t.bounds,...s}}:t})}static positionOf(e,t,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(e),o=this.shortestArc(t.azimuthDeg-s.headingDeg),l=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,o)-i.width/2,y:r.y-this.offAxisPx(n,l)-i.height/2}}static frameCentre(e){return{x:Rt.frameWidthPx(e.instrument,lt.CANVAS_HEIGHT_PX)/2,y:lt.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=Ui.OFF_CANVAS_DEG?Math.sign(t)*Ui.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=Rt.frameWidthPx(t,lt.CANVAS_HEIGHT_PX)/2,s=Rt.frameWidthPx(e.instrument,lt.CANVAS_HEIGHT_PX)/2,r=lt.CANVAS_HEIGHT_PX/2;for(const o of[...e.timeline.allKeyframes]){const l=this.fovOf(e,o.t),c=i?.get(o.t)??l,h=Ts.of(t,lt.CANVAS_HEIGHT_PX,c),d=Ts.of(e.instrument,lt.CANVAS_HEIGHT_PX,l);e.timeline.addKeyframe(o.t,o.shapes.map(u=>{const{bounds:p}=u.shape,f=p.x+p.width/2-n,g=p.y+p.height/2-r,m=Math.hypot(f,g),v=m===0?1:d.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,x={...p,x:s+f*v-p.width/2,y:r+g*v-p.height/2};return{...u,shape:{...u.shape,bounds:x}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=at(e,n.t),r=this.fovOf(e,n.t),o=Ts.of(e.instrument,lt.CANVAS_HEIGHT_PX,r);i.addKeyframe(n.t,n.shapes.map(l=>({...l,shape:t(l.shape,o,s)})))}}}function Yx(a){return wn.restore(Zf(a),a.provenance)}function Zf(a){return Ui.toAngular(a),Ui.toAim(a),{version:1,id:a.id,time:a.event.time,endTime:a.event.endTime,durationSeconds:a.event.durationSeconds,durationText:a.event.durationText,utcOffsetHours:a.event.utcOffsetHours,timeZone:a.event.timeZone,place:a.event.place,observer:a.observer,account:a.account,sources:a.sources?.length?a.sources:void 0,sway:a.sway,vehicle:a.vehicle,description:a.event.description,tags:a.event.tags,timeline:a.timeline.toJSON(),observerTrack:a.observerTrack.toJSON(),weatherTrack:a.weatherTrack.toJSON(),soundTrack:a.soundTrack.toJSON(),weather:a.weather,decor:a.decor,milestones:a.milestones.length>0?a.milestones:void 0,references:a.references.length>0?a.references:void 0,roads:a.roads.length>0?a.roads:void 0,traces:a.traces.length>0?a.traces:void 0,weatherSource:a.weatherSource,instrument:a.instrumentId,exposureSeconds:a.exposureSeconds,iso:a.iso,lightPollution:a.lightPollution,observerMap:a.observerMap,interpretation:a.interpretation}}function qx(a){const{recording:e,provenance:t}=wn.strip(a),i=Kx(e);return i.provenance=t,i}function Kx(a){const e=[],t=new Yu({eventType:"sighting",time:a.time,endTime:a.endTime,durationSeconds:a.durationSeconds,durationText:a.durationText,utcOffsetHours:a.utcOffsetHours,timeZone:a.timeZone,place:a.place,description:a.description,tags:a.tags},Gu.fromJSON(a.timeline,e),a.observerTrack?Uc.fromJSON(a.observerTrack):new Uc,a.weatherTrack?Bc.fromJSON(a.weatherTrack):new Bc,a.soundTrack?zc.fromJSON(a.soundTrack):new zc,a.observer&&{id:a.observer.id,title:a.observer.title,lastName:a.observer.lastName,firstNames:a.observer.firstNames},a.id,a.weather,a.decor??[],a.weatherSource,a.instrument,a.exposureSeconds??a.observerTrack?.keyframes.map(i=>i.pose.exposureSeconds).find(i=>i!==void 0),io(a.milestones??[]),a.references??[],a.roads??[],a.traces??[]);return t.account=a.account,t.sources=a.sources,t.sway=a.sway,t.iso=a.iso,t.lightPollution=a.lightPollution,t.observerMap=a.observerMap,t.vehicle=a.vehicle,t.interpretation=a.interpretation,t.loadIssues=e,Ui.toBounds(t),Ui.toPosition(t),t}class Dl{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(e,t=Dl.EN){return t[e.kind].replace("{path}",e.path).replace("{expected}",e.expected??"").replace("{found}",e.found??"")}static warn(e,t){if(e.length===0)return;const i=e.map(n=>` ${Dl.text(n)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
2837
2801
|
${i.join(`
|
|
2838
2802
|
`)}`)}}class gs{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,n){if(!gs.isObject(e)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:gs.typeOf(e)});return}for(const[s,r]of Object.entries(e)){const o=i?`${i}.${s}`:s,l=t[s];l?this.field(r,l,o,n):n.push({kind:"unknown-key",path:o})}}field(e,t,i,n){if(gs.isStated(e)){this.field(e.value,t,i,n);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&n.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,n):gs.isObject(e)||n.push({kind:"wrong-type",path:i,expected:"object",found:gs.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((s,r)=>{const o=gs.isStated(s)?s.value:s;this.object(o,t.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:gs.typeOf(e)});return;default:typeof e!==t.type&&n.push({kind:"wrong-type",path:i,expected:t.type,found:gs.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return gs.isObject(e)&&"value"in e&&Object.keys(e).every(t=>t==="value"||t==="basis"||t==="rationale")}static typeOf(e){return Array.isArray(e)?"array":e===null?"null":typeof e}}class xs{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(e,t){const i=Number.isFinite(t)?Math.max(0,t):0,n=Math.max(0,e-i*1e3),s=Math.max(0,e-n);return{fromMs:n,toMs:e,ms:s,seconds:s/1e3}}static instants(e,t,i,n,s){if(!(n>0))return 1;const r=s>0?xs.travelDegOver(e,t,i,i+n*1e3)/s/xs.PIXELS_PER_INSTANT:0,o=xs.flashesOver(e,n)*xs.INSTANTS_PER_FLASH,l=Math.ceil(Math.max(r,o));return l<2?1:Math.min(xs.MAX_INSTANTS,l)}static travelDegOver(e,t,i,n){let s=0;for(const r of e){if(!r.track||r.track.length<2)continue;const o=xs.directionAt(r,t,i),l=xs.directionAt(r,t,n),c=Math.min(1,Math.max(-1,o.x*l.x+o.y*l.y+o.z*l.z));s=Math.max(s,Math.acos(c)*180/Math.PI)}return s}static flashesOver(e,t){let i=0;for(const n of e)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const n=tr(e,i),s=n.eastM,r=n.altitudeM-t,o=n.northM,l=Math.hypot(s,r,o);return l===0?{x:0,y:1,z:0}:{x:s/l,y:r/l,z:o/l}}}const qy={play:"Play",pause:"Pause",noDuration:"No observation duration",currentPosition:"Current position",duration:"Duration",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",mute:"Mute",unmute:"Unmute",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:Dl.EN},Zx=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:qy},Symbol.toStringTag,{value:"Module"})),Ky=Math.PI/180,jx=180/Math.PI,Jx=256,Zy=19,Qx=1.25;function jy(a,e){return 156543.03392*Math.cos(a*Ky)/2**e}function Jy(a,e){return jy(a,e)*Jx}function eS(a,e){let t=0;for(;t<Zy&&Jy(a,t+1)>=e;)t++;return t}function Qy(a,e){return Jy(a,e)}function tS(a,e){const t=e*Qx;let i=0;for(;i<Zy&&jy(a,i)>t;)i++;return i}function wd(a){const e=a*Ky;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function eM(a,e,t){const i=2**t;return{x:(a+180)/360*i,y:wd(e)*i}}function tM(a,e,t){const i=wd(a.north),n=wd(a.south);return{x:(e-a.west)/(a.east-a.west),y:(wd(t)-i)/(n-i)}}function iS(a,e,t){const{x:i,y:n}=eM(a,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function nS(a){const e=2**a.z,t=a.x/e*360-180,i=(a.x+1)/e*360-180,n=gv(a.y,e);return{south:gv(a.y+1,e),north:n,west:t,east:i}}function gv(a,e){const t=a/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*jx}function iM(a,e,t,i){const n=iS(a,e,t),s=Math.floor(i/2),r=[];for(let c=-s;c<=s;c++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+c,z:t});const o=r.map(nS),l={south:Math.min(...o.map(c=>c.south)),north:Math.max(...o.map(c=>c.north)),west:Math.min(...o.map(c=>c.west)),east:Math.max(...o.map(c=>c.east))};return{tiles:r,bounds:l}}const sS="#2ec4ff";class Ia{constructor(e){this.ctx=e}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(e,t){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-e,s.y-t);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(e){const{ctx:t}=this;t.save(),this.targets=[],t.clearRect(0,0,this.width,this.height),this.paintGround(e),this.paintNight(e.nightFraction),this.paintPath(e),this.paintTraces(e),e.position?(this.paintCone(e,e.position),this.paintDecor(e),this.paintMarkers(e),this.paintObserver(e,e.position)):(this.paintDecor(e),this.paintMarkers(e)),this.paintNorth(),this.paintFooter(e.bounds,e.attribution),t.restore()}toCanvas(e,t,i){const n=tM(e,i,t);return{x:n.x*this.width,y:n.y*this.height}}paintGround(e){const{ctx:t}=this;t.fillStyle="#1d2321",t.fillRect(0,0,this.width,this.height);const i=e.imagery;if(!i)return;const n=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(e=0){if(e<=0)return;const{ctx:t}=this;t.save(),t.fillStyle=`rgba(6, 12, 30, ${Math.min(e,1)*.78})`,t.fillRect(0,0,this.width,this.height),t.restore()}paintDecor(e){const{ctx:t}=this;for(const i of e.decor){const n=this.toCanvas(e.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:n.x,y:n.y,radius:7}),t.beginPath(),t.rect(n.x-3.5,n.y-3.5,7,7),t.fillStyle="rgba(120, 220, 255, 0.85)",t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.7)",t.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(n.x,n.y),t.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.6)",t.stroke(),t.lineWidth=1.5,t.strokeStyle="rgba(120, 220, 255, 0.9)",t.stroke()}}paintPath(e){if(!e.path.moved)return;const{ctx:t}=this,i=e.path.points.map(n=>this.toCanvas(e.bounds,n.lat,n.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))t.lineTo(n.x,n.y);t.lineJoin="round",t.lineCap="round",t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=5,t.stroke(),t.strokeStyle="rgba(255, 255, 255, 0.9)",t.lineWidth=2,t.stroke()}paintTraces(e){const{ctx:t}=this;for(const i of e.traces??[]){const n=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??sS;if(i.kind==="point")t.beginPath(),t.moveTo(n[0].x,n[0].y-6),t.lineTo(n[0].x+6,n[0].y),t.lineTo(n[0].x,n[0].y+6),t.lineTo(n[0].x-6,n[0].y),t.closePath(),t.fillStyle=s,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))t.lineTo(r.x,r.y);i.kind==="polygon"&&t.closePath(),t.lineJoin="round",t.setLineDash([]),t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=4.5,t.stroke(),t.setLineDash([9,5]),t.strokeStyle=s,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=n[0];if(i.kind==="line"&&e.position){const o=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=n.reduce((l,c)=>Math.hypot(c.x-o.x,c.y-o.y)>Math.hypot(l.x-o.x,l.y-o.y)?c:l)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:n}=e;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),o=Math.hypot(this.width,this.height),l=(i-90)*Math.PI/180,c=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,o,l-c,l+c),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,o);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(e){const{ctx:t}=this;t.textAlign="center",t.textBaseline="middle",t.font="bold 10px sans-serif";for(const i of[...e.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(e.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:Ia.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,Ia.MARKER_RADIUS_PX,0,Math.PI*2),t.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",t.fill(),t.lineWidth=2,t.strokeStyle="rgba(255, 255, 255, 0.9)",t.stroke(),t.fillStyle=i.current?"#1d2321":"#fff",t.fillText(i.label,n.x,n.y)}}paintObserver(e,t){const{ctx:i}=this,n=this.toCanvas(e.bounds,t.lat,t.lng);e.observerLabel&&this.targets.push({kind:"observer",label:e.observerLabel,lat:t.lat,lng:t.lng,x:n.x,y:n.y,radius:8});const s=e.markers.some(r=>{if(!r.current)return!1;const o=ci(r.lat,r.lng,t.lat,t.lng);return Math.hypot(o.x,o.z)<=Ia.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Ia.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:e}=this,t=this.width-14,i=16;e.beginPath(),e.moveTo(t,i-9),e.lineTo(t-4.5,i+5),e.lineTo(t,i+2),e.lineTo(t+4.5,i+5),e.closePath(),e.fillStyle="rgba(255, 255, 255, 0.92)",e.strokeStyle="rgba(0, 0, 0, 0.6)",e.lineWidth=1,e.fill(),e.stroke(),e.font="bold 9px sans-serif",e.textAlign="center",e.textBaseline="top",e.strokeText("N",t,i+6),e.fillText("N",t,i+6)}paintFooter(e,t){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=t?this.wrap(t,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const p of n.slice().reverse())this.paintOutlinedText(p,this.width-6,s),s-=11;const r=(e.south+e.north)/2,l=Math.abs(ci(r,e.east,r,e.west).x)/this.width,c=Ia.SCALE_STEPS_M.find(p=>p/l<=this.width/3);if(c===void 0)return;const h=c/l,d=8,u=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(d,u),i.lineTo(d+h,u),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(c>=1e3?`${c/1e3} km`:`${c} m`,d,u-3)}paintOutlinedText(e,t,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(e,t,i),n.fillStyle="#fff",n.fillText(e,t,i)}wrap(e,t){const i=[];let n="";for(const s of e.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>t?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class li{static MIN_ZOOM=.25;static MAX_ZOOM=64;zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(e,t,i){const n=Math.min(li.MAX_ZOOM,Math.max(li.MIN_ZOOM,this.zoom*i)),s=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=s-(e-.5)/n,this.centerY=r-(t-.5)/n,this.zoom=n}panBy(e,t){this.centerX-=e/this.zoom,this.centerY-=t/this.zoom}refit(e,t){if(!this.changed)return;const i=this.boundsWithin(e),n=li.mercatorY01(t.north),s=li.mercatorY01(t.south),r=li.mercatorY01(i.north),o=li.mercatorY01(i.south);this.zoom=(t.east-t.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-t.west)/(t.east-t.west),this.centerY=((r+o)/2-n)/(s-n)}keepInView(e,t,i){if(!this.changed)return!1;const n=this.boundsWithin(e),s=li.mercatorY01(n.north),r=li.mercatorY01(n.south),o=(t.lng-n.west)/(n.east-n.west),l=(li.mercatorY01(t.lat)-s)/(r-s);return o>=i&&o<=1-i&&l>=i&&l<=1-i?!1:(this.panBy(.5-o,.5-l),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=li.mercatorY01(e.north),n=li.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:li.latitudeAt(i+(this.centerY-t)*(n-i)),south:li.latitudeAt(i+(this.centerY+t)*(n-i))}}static including(e,t,i=3){const n=(e.north+e.south)/2,s=(e.east+e.west)/2,r=ci(n,e.east,n,s).x;let o=r;for(const l of t){const{x:c,z:h}=ci(l.lat,l.lng,n,s),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(o=Math.max(o,d*1.15))}return o<=r?e:{north:Zn(0,-o,n,s).lat,south:Zn(0,o,n,s).lat,east:Zn(o,0,n,s).lng,west:Zn(-o,0,n,s).lng}}static expand(e,t){const i=e.east-e.west,n=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-n*t,north:e.north+n*t}}static pointAt(e,t,i){const n=li.mercatorY01(e.north),s=li.mercatorY01(e.south);return{lat:li.latitudeAt(n+i*(s-n)),lng:e.west+t*(e.east-e.west)}}static mercatorY01(e){const t=e*Math.PI/180;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}static latitudeAt(e){return Math.atan(Math.sinh(Math.PI*(1-2*e)))*180/Math.PI}}const Qn=256,vv=3,rS=32768;class nM{fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(e,t){const i=(e.south+e.north)/2,n=(e.west+e.east)/2,s=Math.abs(ci(i,e.east,i,e.west).x),r=Math.abs(ci(e.north,n,e.south,n).z),o=eS(i,Math.max(s,r)),{tiles:l}=iM(n,i,o,vv),c=vv*Qn,h=new Float32Array(c*c),d=l[0];await Promise.all(l.map(p=>this.decodeTileInto(p,d,h,c)));const u=new Float32Array(t.width*t.height);for(let p=0;p<t.height;p++){const f=e.north+(e.south-e.north)*(p/(t.height-1));for(let g=0;g<t.width;g++){const m=e.west+(e.east-e.west)*(g/(t.width-1));u[p*t.width+g]=this.sampleAt(f,m,o,d,h,c)}}return{heights:u,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,n){const s=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const o=await createImageBitmap(await r.blob()),l=document.createElement("canvas");l.width=Qn,l.height=Qn;const c=l.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(o,0,0);const{data:h}=c.getImageData(0,0,Qn,Qn),d=(e.x-t.x)*Qn,u=(e.y-t.y)*Qn;for(let p=0;p<Qn;p++)for(let f=0;f<Qn;f++){const g=(p*Qn+f)*4,m=h[g]*256+h[g+1]+h[g+2]/256-rS,v=d+f,x=u+p;i[x*n+v]=m}}sampleAt(e,t,i,n,s,r){const{x:o,y:l}=eM(t,e,i),c=(o-n.x)*Qn,h=(l-n.y)*Qn,d=Math.max(0,Math.min(r-1,Math.floor(c))),u=Math.max(0,Math.min(r-1,Math.floor(h))),p=Math.min(r-1,d+1),f=Math.min(r-1,u+1),g=c-d,m=h-u,v=s[u*r+d],x=s[u*r+p],y=s[f*r+d],b=s[f*r+p],w=v+(x-v)*g,S=y+(b-y)*g;return w+(S-w)*m}}const xd=256,aS=5;async function sM(a,e,t,i){const n=(a.south+a.north)/2,s=(a.west+a.east)/2,r=Math.abs(ci(n,a.east,n,a.west).x),o=Math.abs(ci(a.north,s,a.south,s).z),l=Math.max(r,o),{zoom:c,gridSize:h}=oS(n,l,Math.max(e.width,e.height)),{tiles:d,bounds:u}=iM(s,n,c,h),p=h*xd,f=document.createElement("canvas");f.width=p,f.height=p;const g=f.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=d[0];await Promise.all(d.map(async b=>{const w=t(b),S=await i(w);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${w}`);const _=await createImageBitmap(await S.blob());g.drawImage(_,(b.x-m.x)*xd,(b.y-m.y)*xd)}));const v=Math.min(Math.max(e.width,e.height),p);if(v===p)return{source:f,width:p,height:p,bounds:u};const x=document.createElement("canvas");x.width=v,x.height=v;const y=x.getContext("2d");if(!y)throw new Error("2D canvas context unavailable");return y.drawImage(f,0,0,p,p,0,0,v,v),{source:x,width:v,height:v,bounds:u}}function oS(a,e,t){let i=tS(a,e/Math.max(1,t)),n=bv(a,i,e);for(;n>aS&&i>0;)i--,n=bv(a,i,e);return{zoom:i,gridSize:n,mPerPixel:Qy(a,i)/xd}}function bv(a,e,t){const i=Math.ceil(t/2/Qy(a,e));return Math.max(3,2*i+1)}class rM{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(e,t){return sM(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class vs{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints??vs.ENDPOINTS}static queue=Promise.resolve();static RETRY_MS=4e3;async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${vs.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.queued(()=>this.ask(i)))}waysFrom(e){const t=[];for(const i of e.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||t.push({id:`osm-${i.id??t.length}`,name:s.name,surface:vs.surfaceOf(s),widthM:vs.widthOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}queued(e){const t=vs.queue.then(e,e);return vs.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints)for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`);if(s.ok)return await s.json();if(t=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){t=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,vs.RETRY_MS))}throw t??new Error("No Overpass instance answered")}static widthOf(e){const t=Number.parseFloat(e.width??e.est_width??"");if(Number.isFinite(t)&&t>0)return t;const i=Number.parseInt(e.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:vs.WIDTH_M[e.highway]??vs.DEFAULT_WIDTH_M}static surfaceOf(e){const t=e.surface;return t==="dirt"||t==="earth"||t==="mud"?"dirt":t==="gravel"||t==="fine_gravel"||t==="compacted"||t==="ground"||t==="sand"||t==="unpaved"?"gravel":t?"paved":e.highway==="track"?"gravel":"paved"}}const fp="https://ufoathome.org/roads/index.json";class Jo{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Jo.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRoads(e);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(e){let t;try{t=await this.load()}catch{return}const i=t.find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
2839
|
-
`);let t=Jo.shared.get(e);return t||(t=this.fetchFirstAvailable(),Jo.shared.set(e,t),t.then(i=>{i.length===0&&Jo.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.104.1")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==fp?[t,fp]:[fp]).map(i=>i+e)}}function lS(){return{elevation:new nM,imagery:aM(),roads:cS()}}function aM(){return new rM}function cS(){return new Jo({fallback:new vs})}const hS=new Set,pl="show-observer-map",fl="hide-milestones";class vt extends HTMLElement{static get observedAttributes(){return["src",pl,fl]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new li;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Yu.create();issues=[];issueCheck=0;sightingAudio=new $x;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>vt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=qy;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(s)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");vt.setIcon(this.moreButton,e?Xe.UNFOLDED:Xe.FOLDED);const t=e?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,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`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<vt.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=li.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=li.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},vt.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=li.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Gx}</style>${Hx}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Gc(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",t=>{t.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Ia(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",t=>{t.key!=="Enter"&&t.key!==" "||(t.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>this.player.seek(this.snapSeekToMark(Number(this.seekInput.value)))),this.seekInput.addEventListener("pointerdown",t=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(t),this.beginTouchScrub(t)}),this.seekInput.addEventListener("pointerup",t=>{this.seekSnapArmed=!1,this.endTouchScrub(t)}),this.seekInput.addEventListener("pointercancel",t=>this.endTouchScrub(t)),this.seekInput.addEventListener("pointermove",t=>{this.nameMarkUnder(t),this.hoverSeek(t),this.touchScrub(t)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const t of["touchend","click"])this.stageElement.addEventListener(t,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",t=>{if(this.enableClickToPlay){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}t.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",t=>{this.enableClickToPlay&&(t.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===pl&&this.applyObserverMapDefault(),e===fl&&this.setMilestonesShown(!this.hasAttribute(fl))}async loadFromSrc(e){this.sightingData=await Nc.json(e)}get sightingData(){return Yx(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=qx(e),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await je(async()=>{const{default:r}=await import("./sightingSchema-5AlscPkV.js");return{default:r}},[],import.meta.url);n=new gs(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],Dl.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(dS,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=this.messages.recordingIssues.replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Dl.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0;return}this.togglePlayPause()}}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get 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(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of t)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity));for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const n=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),n=this.said.read(t.title)??t.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),o=document.createElement("input");o.type="checkbox",o.checked=i.shown;const l=document.createElement("span");l.textContent=n,l.title=n,r.append(o,l);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages.referenceOpacity,c.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),c.disabled=!i.shown,o.addEventListener("change",()=>{i.shown=o.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),s.append(r,c),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),vt.setIcon(this.referencesButton,i?Xe.PICTURES_ON:Xe.PICTURES_OFF);const n=t?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),vt.setIcon(this.tracesButton,this.tracesShownState?Xe.TRACES_ON:Xe.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?io(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),o=r?`${s} — ${r}`:s;return n.title=o,n.setAttribute("aria-label",o),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",o=this.said.read(i.note);return s.textContent=o?`${r} — ${o}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=e!==void 0&&Number(n.dataset.t)===e.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const n=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,o)=>r-o):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(l,c),s.push(o),this.seekSegmentList.push({start:n[r],end:n[r+1],element:o,played:c,hover:l})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,n=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=vt.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=vt.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const o=this.milestonesShown?this.sighting.milestones:[],l=o.length>0?up(o,s):void 0,c=l?this.said.read(l.label)??"":"",h=l?this.said.read(l.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const n=vt.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const o=Number(r.dataset.t);Math.abs(o-e)>n||(!s||Math.abs(o-e)<Math.abs(s.t-e))&&(s={t:o,name:r.title})}return s}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=(e.clientX-t.left)/t.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?up(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const n=this.said.read(t.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(e=this.currentTime){const t=xs.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<vt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(vt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/vt.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/vt.EXPOSURE_STEP_PX),s=Math.min(vt.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let o=0;o<s;o++)r.push(t.fromMs+t.ms*o/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,o]of i){const l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(o.bounds.y+o.bounds.height/2);s=Math.max(s,Math.hypot(c,h))}return s}shapeAt(e,t,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,e,t,i);if(s)return s}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=Rt.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:hS;this.canvasRenderer.setStarPoints(Rt.starPointsOf(this.sighting.instrument));const n=(at(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of s)for(const[,l]of o.shapes){const c=o.share,h=c===1?l:{...l,transparency:1-(1-l.transparency)*c};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,l]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));if(this.selectionShown&&i.size>1){const o=Tt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(Dm(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new Vx(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*vt.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold;return}else this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Xe.PLAY:Xe.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){vt.icons.get(e)!==t&&(vt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},vt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,vt.setIcon(this.playPauseButton,e?Xe.PAUSE:Xe.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(pl),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;vt.setIcon(this.observerMapButton,e?Xe.MAP_ON:Xe.MAP_OFF);const t=e?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);const i=[[this.mapZoomInButton,this.messages.zoomMapIn],[this.mapZoomOutButton,this.messages.zoomMapOut],[this.mapFitButton,this.messages.fitMap]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=ul.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=li.including(this.observerPath.boundsAround(vt.OBSERVER_MAP_MIN_SPAN_M,vt.OBSERVER_MAP_MARGIN),t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||!this.observerMapImageryNeededFor(e))return;const t=this.observerMapView.changed,i=t?li.expand(e,vt.OBSERVER_MAP_IMAGERY_AHEAD):e,n=vt.OBSERVER_MAP_IMAGERY_PX*(t?1+2*vt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=aM();try{const r=await s.getImageryTexture(i,{width:n,height:n});if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=s.attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=this.observerMapView.changed?li.expand(e,vt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=vt.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(l||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,n=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*n,bottom:(e.bottom-t.top)*n}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=at(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},vt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?up(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?io(this.currentSighting.milestones):[]){const o=at(this.currentSighting,r.t);o?.lat===void 0||o.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:o.lat,lng:o.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Ts.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Rt.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,io(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages.moments,vt.setIcon(this.milestonesButton,this.milestonesShown?Xe.MILESTONES_ON:Xe.MILESTONES_OFF);const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=at(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=tr(i,e),{lat:s,lng:r}=Zn(n.eastM,-n.northM,t.lat,t.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const n=at(this.currentSighting,this.currentTime),s=Ts.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Ft.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=vt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;if(this.muteButton.disabled=e,this.volumeInput.hidden=e,e){vt.setIcon(this.muteButton,Xe.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}vt.setIcon(this.muteButton,this.mutedState?Xe.MUTED:Xe.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=t,this.muteButton.setAttribute("aria-label",t),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;vt.setIcon(this.fullscreenButton,e?Xe.EXIT_FULLSCREEN:Xe.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new qn(hs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fc(hs.preferencesFor(this),Hc);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await Mx(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=this.messages.currentPosition+t,this.timeEndLabel.title=this.messages.duration+t,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=Tl(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Vf(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return vh(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?Mv(yv(this.realStartMs+i)):vh(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?vh(this.currentSighting.timeline.duration):this.canShowClockTime?Mv(yv(this.realStartMs+this.realDurationMs)):vh(this.realDurationMs)}}function yv(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function Mv(a){if(a.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return a.second?`${e(a.hour)}:${e(a.minute??0)}:${e(a.second)}`:`${e(a.hour)}:${e(a.minute??0)}`}function vh(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const jf="rr0-ufo";function qu(){customElements.get(jf)||customElements.define(jf,vt)}const dS="recordingissues";class Sc{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((s,r)=>s.t-r.t):[],n=`${t}|${i.map(s=>`${s.kind}:${s.t}:${s.label}`).join("|")}`;n!==this.drawn&&(this.drawn=n,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(s=>{const r=document.createElement("span");return r.className=`timeline-mark ${s.kind}`,r.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+Sc.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Sc.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Sc.SNAP_PX/t*this.duration;let n;for(const s of this.marks)Math.abs(s.t-e)>i||(!n||Math.abs(s.t-e)<Math.abs(n.t-e)||s.t===n.t&&s.kind==="milestone")&&(n=s);return n}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Qo{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const n=e.event.place?.[0],s=e.observerTrack;if(!n)return 0;const r=g=>{const m=s.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=ci(m.lat,m.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg}},o=r(t-Qo.HALF_SPAN_MS),l=r(t+Qo.HALF_SPAN_MS),c=r(t);if(!o||!l||!c)return 0;const h=Math.hypot(l.eastM-o.eastM,l.northM-o.northM),d=2*Qo.HALF_SPAN_MS/1e3;if(h/d<Qo.MIN_SPEED_MS)return 0;const u=i.heightAt(l.eastM,l.northM)-i.heightAt(o.eastM,o.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(l.eastM-o.eastM,l.northM-o.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const uS=.08,wv=.15,xv=2,pS=2e3;class fS{context;noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}to.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);this.context?.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<pS),i=new Set(t.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of t){const s=this.voices.get(n.id)??this.build(e,n.id);this.retarget(e,s,n)}}build(e,t){const i=e.createGain();i.gain.value=0;const n=e.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(e));const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const o=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(o).connect(n);const c=()=>{const w=e.createBufferSource();return w.buffer=this.noise(e),w.loop=!0,w.loopStart=Math.random()*xv*.5,w},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const g=e.createGain();p.connect(f).connect(g).connect(n);const m=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const x=e.createGain();m.connect(v).connect(x).connect(n);const y=[s,r,h,p,m];for(const w of y)w.start();const b={nodes:[i,n,o,l,d,u,f,g,v,x,...y],sources:y,firing:s,crank:r,knock:d,engineGain:o,knockGain:u,roadGain:g,windGain:x,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:o,distanceM:l}){const c=e.currentTime,h=(x,y)=>x.setTargetAtTime(y,c,uS),d=n.rpm/60,u=d*i.cylinders/2,p=Math.min(1,n.rpm/i.shiftUpRpm),f=Math.min(1.5,n.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const g=!r||o;h(t.windGain.gain,f**2*(g?.5:.06));const m=r?o?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const v=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,v*s)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,wv/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},wv*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*xv,e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Vc{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Vc.BY_KIND[e??"generic"]??Vc.BY_KIND.generic}}class $a{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,n){const s=$a.SAMPLE_MS,r=[];for(let c=i;c<=n+s/2;c+=s){const h=t(c-s/2),d=t(c+s/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(s/1e3))}const o=[];let l=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*s/1e3);if(h<$a.STANDING_MPS){l=1,o.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&p(l)>e.shiftUpRpm;)l++;for(;l>1&&p(l)<e.shiftDownRpm;)l--;const f=Math.max(p(l),e.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,g+d/2.5):d<-.3?.05:g;o.push({speedMps:h,rpm:f,load:m,gear:l})}return new $a(o,i)}at(e){const t=(e-this.startMs)/$a.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class du{drives=new Map;at(e,t){const i=[],n=e.event.place?.[0],s=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??n?.lat,u=h?.lng??n?.lng;if(d===void 0||u===void 0||!n)return;const p=ci(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),o=e.vehicle;if(o){const c=Vc.of(o.kind),h=this.drive(`observer:${o.kind}`,du.trackKey(e),()=>$a.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Vc.of(c.engine.kind),d=g=>{const m=tr(c,g);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,du.decorKey(c,r),()=>$a.of(h,d,0,r));if(!u)continue;const p=tr(c,t),f=Math.hypot(p.eastM-l.eastM,p.northM-l.northM,p.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}return i}drive(e,t,i){const n=this.drives.get(e);if(n&&n.key===t)return n.drive;const s=i();return this.drives.set(e,{key:t,drive:s}),s}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const mS=`
|
|
2803
|
+
`);let t=Jo.shared.get(e);return t||(t=this.fetchFirstAvailable(),Jo.shared.set(e,t),t.then(i=>{i.length===0&&Jo.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.105.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==fp?[t,fp]:[fp]).map(i=>i+e)}}function lS(){return{elevation:new nM,imagery:aM(),roads:cS()}}function aM(){return new rM}function cS(){return new Jo({fallback:new vs})}const hS=new Set,pl="show-observer-map",fl="hide-milestones";class vt extends HTMLElement{static get observedAttributes(){return["src",pl,fl]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new li;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Yu.create();issues=[];issueCheck=0;sightingAudio=new $x;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>vt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=qy;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(s)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");vt.setIcon(this.moreButton,e?Xe.UNFOLDED:Xe.FOLDED);const t=e?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,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`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<vt.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=li.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=li.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},vt.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=li.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Gx}</style>${Hx}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Gc(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",t=>{t.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Ia(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",t=>{t.key!=="Enter"&&t.key!==" "||(t.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>this.player.seek(this.snapSeekToMark(Number(this.seekInput.value)))),this.seekInput.addEventListener("pointerdown",t=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(t),this.beginTouchScrub(t)}),this.seekInput.addEventListener("pointerup",t=>{this.seekSnapArmed=!1,this.endTouchScrub(t)}),this.seekInput.addEventListener("pointercancel",t=>this.endTouchScrub(t)),this.seekInput.addEventListener("pointermove",t=>{this.nameMarkUnder(t),this.hoverSeek(t),this.touchScrub(t)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const t of["touchend","click"])this.stageElement.addEventListener(t,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",t=>{if(this.enableClickToPlay){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}t.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",t=>{this.enableClickToPlay&&(t.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===pl&&this.applyObserverMapDefault(),e===fl&&this.setMilestonesShown(!this.hasAttribute(fl))}async loadFromSrc(e){this.sightingData=await Nc.json(e)}get sightingData(){return Yx(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=qx(e),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await je(async()=>{const{default:r}=await import("./sightingSchema-5AlscPkV.js");return{default:r}},[],import.meta.url);n=new gs(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],Dl.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(dS,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=this.messages.recordingIssues.replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Dl.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0;return}this.togglePlayPause()}}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get 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(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of t)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity));for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const n=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),n=this.said.read(t.title)??t.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),o=document.createElement("input");o.type="checkbox",o.checked=i.shown;const l=document.createElement("span");l.textContent=n,l.title=n,r.append(o,l);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages.referenceOpacity,c.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),c.disabled=!i.shown,o.addEventListener("change",()=>{i.shown=o.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),s.append(r,c),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),vt.setIcon(this.referencesButton,i?Xe.PICTURES_ON:Xe.PICTURES_OFF);const n=t?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),vt.setIcon(this.tracesButton,this.tracesShownState?Xe.TRACES_ON:Xe.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?io(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),o=r?`${s} — ${r}`:s;return n.title=o,n.setAttribute("aria-label",o),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",o=this.said.read(i.note);return s.textContent=o?`${r} — ${o}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=e!==void 0&&Number(n.dataset.t)===e.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const n=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,o)=>r-o):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(l,c),s.push(o),this.seekSegmentList.push({start:n[r],end:n[r+1],element:o,played:c,hover:l})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,n=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=vt.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=vt.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const o=this.milestonesShown?this.sighting.milestones:[],l=o.length>0?up(o,s):void 0,c=l?this.said.read(l.label)??"":"",h=l?this.said.read(l.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const n=vt.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const o=Number(r.dataset.t);Math.abs(o-e)>n||(!s||Math.abs(o-e)<Math.abs(s.t-e))&&(s={t:o,name:r.title})}return s}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=(e.clientX-t.left)/t.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?up(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const n=this.said.read(t.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(e=this.currentTime){const t=xs.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<vt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(vt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/vt.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/vt.EXPOSURE_STEP_PX),s=Math.min(vt.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let o=0;o<s;o++)r.push(t.fromMs+t.ms*o/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,o]of i){const l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(o.bounds.y+o.bounds.height/2);s=Math.max(s,Math.hypot(c,h))}return s}shapeAt(e,t,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,e,t,i);if(s)return s}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=Rt.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:hS;this.canvasRenderer.setStarPoints(Rt.starPointsOf(this.sighting.instrument));const n=(at(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of s)for(const[,l]of o.shapes){const c=o.share,h=c===1?l:{...l,transparency:1-(1-l.transparency)*c};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,l]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));if(this.selectionShown&&i.size>1){const o=Tt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(Dm(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new Vx(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*vt.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold;return}else this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Xe.PLAY:Xe.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){vt.icons.get(e)!==t&&(vt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},vt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,vt.setIcon(this.playPauseButton,e?Xe.PAUSE:Xe.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(pl),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;vt.setIcon(this.observerMapButton,e?Xe.MAP_ON:Xe.MAP_OFF);const t=e?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);const i=[[this.mapZoomInButton,this.messages.zoomMapIn],[this.mapZoomOutButton,this.messages.zoomMapOut],[this.mapFitButton,this.messages.fitMap]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=ul.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=li.including(this.observerPath.boundsAround(vt.OBSERVER_MAP_MIN_SPAN_M,vt.OBSERVER_MAP_MARGIN),t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||!this.observerMapImageryNeededFor(e))return;const t=this.observerMapView.changed,i=t?li.expand(e,vt.OBSERVER_MAP_IMAGERY_AHEAD):e,n=vt.OBSERVER_MAP_IMAGERY_PX*(t?1+2*vt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=aM();try{const r=await s.getImageryTexture(i,{width:n,height:n});if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=s.attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=this.observerMapView.changed?li.expand(e,vt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=vt.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(l||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,n=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*n,bottom:(e.bottom-t.top)*n}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=at(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},vt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?up(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?io(this.currentSighting.milestones):[]){const o=at(this.currentSighting,r.t);o?.lat===void 0||o.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:o.lat,lng:o.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Ts.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Rt.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,io(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages.moments,vt.setIcon(this.milestonesButton,this.milestonesShown?Xe.MILESTONES_ON:Xe.MILESTONES_OFF);const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=at(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=tr(i,e),{lat:s,lng:r}=Zn(n.eastM,-n.northM,t.lat,t.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const n=at(this.currentSighting,this.currentTime),s=Ts.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Ft.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=vt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;if(this.muteButton.disabled=e,this.volumeInput.hidden=e,e){vt.setIcon(this.muteButton,Xe.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}vt.setIcon(this.muteButton,this.mutedState?Xe.MUTED:Xe.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=t,this.muteButton.setAttribute("aria-label",t),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;vt.setIcon(this.fullscreenButton,e?Xe.EXIT_FULLSCREEN:Xe.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new qn(hs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fc(hs.preferencesFor(this),Hc);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await Mx(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=this.messages.currentPosition+t,this.timeEndLabel.title=this.messages.duration+t,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=Tl(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Vf(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return vh(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?Mv(yv(this.realStartMs+i)):vh(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?vh(this.currentSighting.timeline.duration):this.canShowClockTime?Mv(yv(this.realStartMs+this.realDurationMs)):vh(this.realDurationMs)}}function yv(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function Mv(a){if(a.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return a.second?`${e(a.hour)}:${e(a.minute??0)}:${e(a.second)}`:`${e(a.hour)}:${e(a.minute??0)}`}function vh(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const jf="rr0-ufo";function qu(){customElements.get(jf)||customElements.define(jf,vt)}const dS="recordingissues";class Sc{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((s,r)=>s.t-r.t):[],n=`${t}|${i.map(s=>`${s.kind}:${s.t}:${s.label}`).join("|")}`;n!==this.drawn&&(this.drawn=n,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(s=>{const r=document.createElement("span");return r.className=`timeline-mark ${s.kind}`,r.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+Sc.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Sc.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Sc.SNAP_PX/t*this.duration;let n;for(const s of this.marks)Math.abs(s.t-e)>i||(!n||Math.abs(s.t-e)<Math.abs(n.t-e)||s.t===n.t&&s.kind==="milestone")&&(n=s);return n}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Qo{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const n=e.event.place?.[0],s=e.observerTrack;if(!n)return 0;const r=g=>{const m=s.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=ci(m.lat,m.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg}},o=r(t-Qo.HALF_SPAN_MS),l=r(t+Qo.HALF_SPAN_MS),c=r(t);if(!o||!l||!c)return 0;const h=Math.hypot(l.eastM-o.eastM,l.northM-o.northM),d=2*Qo.HALF_SPAN_MS/1e3;if(h/d<Qo.MIN_SPEED_MS)return 0;const u=i.heightAt(l.eastM,l.northM)-i.heightAt(o.eastM,o.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(l.eastM-o.eastM,l.northM-o.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const uS=.08,wv=.15,xv=2,pS=2e3;class fS{context;noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}to.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);this.context?.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<pS),i=new Set(t.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of t){const s=this.voices.get(n.id)??this.build(e,n.id);this.retarget(e,s,n)}}build(e,t){const i=e.createGain();i.gain.value=0;const n=e.createBiquadFilter();n.type="lowpass",n.connect(i).connect(this.masterOf(e));const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const o=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(o).connect(n);const c=()=>{const w=e.createBufferSource();return w.buffer=this.noise(e),w.loop=!0,w.loopStart=Math.random()*xv*.5,w},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const g=e.createGain();p.connect(f).connect(g).connect(n);const m=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const x=e.createGain();m.connect(v).connect(x).connect(n);const y=[s,r,h,p,m];for(const w of y)w.start();const b={nodes:[i,n,o,l,d,u,f,g,v,x,...y],sources:y,firing:s,crank:r,knock:d,engineGain:o,knockGain:u,roadGain:g,windGain:x,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:o,distanceM:l}){const c=e.currentTime,h=(x,y)=>x.setTargetAtTime(y,c,uS),d=n.rpm/60,u=d*i.cylinders/2,p=Math.min(1,n.rpm/i.shiftUpRpm),f=Math.min(1.5,n.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const g=!r||o;h(t.windGain.gain,f**2*(g?.5:.06));const m=r?o?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const v=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,v*s)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,wv/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},wv*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*xv,e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Vc{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Vc.BY_KIND[e??"generic"]??Vc.BY_KIND.generic}}class $a{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,n){const s=$a.SAMPLE_MS,r=[];for(let c=i;c<=n+s/2;c+=s){const h=t(c-s/2),d=t(c+s/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(s/1e3))}const o=[];let l=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*s/1e3);if(h<$a.STANDING_MPS){l=1,o.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&p(l)>e.shiftUpRpm;)l++;for(;l>1&&p(l)<e.shiftDownRpm;)l--;const f=Math.max(p(l),e.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,g+d/2.5):d<-.3?.05:g;o.push({speedMps:h,rpm:f,load:m,gear:l})}return new $a(o,i)}at(e){const t=(e-this.startMs)/$a.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class du{drives=new Map;at(e,t){const i=[],n=e.event.place?.[0],s=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??n?.lat,u=h?.lng??n?.lng;if(d===void 0||u===void 0||!n)return;const p=ci(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),o=e.vehicle;if(o){const c=Vc.of(o.kind),h=this.drive(`observer:${o.kind}`,du.trackKey(e),()=>$a.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Vc.of(c.engine.kind),d=g=>{const m=tr(c,g);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,du.decorKey(c,r),()=>$a.of(h,d,0,r));if(!u)continue;const p=tr(c,t),f=Math.hypot(p.eastM-l.eastM,p.northM-l.northM,p.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}return i}drive(e,t,i){const n=this.drives.get(e);if(n&&n.key===t)return n.drive;const s=i();return this.drives.set(e,{key:t,drive:s}),s}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const mS=`
|
|
2840
2804
|
<div class="stage" id="stage">
|
|
2841
2805
|
<div class="frame" id="frame">
|
|
2842
2806
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -8988,7 +8952,7 @@ ${Ce.OUTPUT_PROJECTION_GLSL}`)}}class mn{constructor(e,t){this.width=e,this.heig
|
|
|
8988
8952
|
gl_FragColor = vec4(iceHaloLight(dir, ice), 1.0);
|
|
8989
8953
|
}
|
|
8990
8954
|
`,transparent:!0,blending:Bi,depthWrite:!1,side:ni,fog:!1}),this.object=new Ae(new yi(Xi.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(e){this.hostedByDeck=e,this.show(this.shown)}show(e){this.shown=e,this.object.visible=e&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=e?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(e){this.urgent=e}set onReady(e){this.onRepaint=e}update(e,t,i,n,s,r){const o=this.material.uniforms;if(i<=0){o.uStrength.value=0,this.show(!1),this.stopWork();return}o.uSource.value.set(e.x,e.y,e.z).normalize(),o.uStrength.value=i,o.uTint.value.set(n[0],n[1],n[2]),o.uIceCover.value=s.cover,o.uIceHeight.value=s.layerHeight,this.show(this.everDisplayed),this.requestMap(t,r)}requestMap(e,t){if(!(!(Math.abs(e-this.mappedAltitudeDeg)<Xi.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<Xi.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(e,t)){this.next=void 0;return}if(!(!(Math.abs(e-this.pendingAltitudeDeg)<Xi.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<Xi.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:e,alignment:t};return}}this.next=void 0,this.pendingAltitudeDeg=e,this.pendingAlignment=t,this.stopWork(),this.tracing=!0,this.startTracing(e,t)}startTracing(e,t){const i=++this.ticket,n=()=>{i!==this.ticket||!this.tracing||(this.sky.begin(e,t),this.scheduleWork())};ea.with(s=>{i!==this.ticket||!this.tracing||(this.job=s.trace(e,t,Xi.RAYS,r=>{this.job=void 0,this.texels.set(r),this.display(),this.finishTracing()},n))},n)}ticket=0;job;pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;next;tracingFor(e,t){return this.tracing&&Math.abs(e-this.pendingAltitudeDeg)<Xi.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<Xi.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const e=()=>{if(this.workHandle=void 0,!this.tracing)return;const t=performance.now(),i=this.urgent?Xi.URGENT_BUDGET_MS:Xi.BUDGET_MS;do this.sky.trace(Xi.RAYS_PER_BATCH);while(this.sky.tracedRays<Xi.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=Xi.RAYS){this.publish(),this.finishTracing();return}this.workHandle=requestAnimationFrame(e)};this.workHandle=requestAnimationFrame(e)}finishTracing(){this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment;const e=this.next;e&&this.requestMap(e.sourceAltitudeDeg,e.alignment)}stopWork(){this.ticket++,this.job?.cancel(),this.job=void 0,this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){F4.fromRadiance(this.sky.harvest().data,this.texels),this.display()}display(){this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class Wi{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=Wi.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Wi.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const e=Wi.MAX_CONCURRENT*Wi.SEGMENTS*Wi.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new ct;t.setAttribute("position",new tt(this.positions,3)),t.setAttribute("color",new tt(this.colors,3)),t.setDrawRange(0,0),this.object=new Ae(t,cs.material()),this.object.frustumCulled=!1,cs.track(this.object)}get schedule(){return this.meteors}setShower(e,t,i){this.meteors=e,this.radiantAltitudeDeg=t,this.radiantAzimuthDeg=i}update(e){const t=this.object.geometry;if(this.meteors.length===0){t.setDrawRange(0,0);return}const i=ro.aliveAt(this.meteors,e).slice(0,Wi.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const o=this.radiantOf(s);if(!o)continue;const l=jt(o.altitudeDeg,o.azimuthDeg,1),[c,h]=this.basisAround(l),d=s.fromRadiantDeg+r*s.lengthDeg,u=Math.max(s.fromRadiantDeg,d-s.lengthDeg*.6),p=Math.min(1,(1-r)*2.5),f=this.turn(c,h,s.bearingDeg),g=(.15+.85*s.brightness)*p,m=y=>g*y**1.6,v=y=>this.onSphere(l,f,u+(d-u)*y),x=y=>Wi.RADIUS*((Wi.MIN_HALF_WIDTH_DEG+Wi.BRIGHT_HALF_WIDTH_DEG*s.brightness*y)*Math.PI/180);for(let y=1;y<Wi.POINTS;y++){const b=(y-1)/Wi.SEGMENTS,w=y/Wi.SEGMENTS;n=this.pushRibbon(n,v(b),v(w),x(b),x(w),m(b),m(w))}}t.setDrawRange(0,n),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}midpointOf(e){const t=this.radiantOf(e);if(!t)return;const i=jt(t.altitudeDeg,t.azimuthDeg,1),[n,s]=this.basisAround(i),r=this.turn(n,s,e.bearingDeg),o=this.onSphere(i,r,e.fromRadiantDeg+e.lengthDeg/2),l=Math.hypot(o.x,o.y,o.z)||1;return{altitudeDeg:Math.asin(o.y/l)*180/Math.PI,azimuthDeg:(Math.atan2(o.x,-o.z)*180/Math.PI+360)%360}}radiantOf(e){return e.radiant?e.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(e,t,i,n,s,r,o){const l=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Wi.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,l,n,h),p=this.across(i,l,s,h),f=this.across(t,l,n,d),g=this.across(i,l,s,d),m=(v,x)=>v===0?x:0;e=this.push(e,u,m(h,r)),e=this.push(e,p,m(h,o)),e=this.push(e,f,m(d,r)),e=this.push(e,p,m(h,o)),e=this.push(e,g,m(d,o)),e=this.push(e,f,m(d,r))}return e}across(e,t,i,n){return{x:e.x+t.x*i*n,y:e.y+t.y*i*n,z:e.z+t.z*i*n}}push(e,t,i){const n=e*3;this.positions[n]=t.x,this.positions[n+1]=t.y,this.positions[n+2]=t.z;const s=Ie.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.9,this.colors[n+1]=s*.95,this.colors[n+2]=s,e+1}turn(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:e.x*s+t.x*r,y:e.y*s+t.y*r,z:e.z*s+t.z*r}}onSphere(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:(e.x*s+t.x*r)*Wi.RADIUS,y:(e.y*s+t.y*r)*Wi.RADIUS,z:(e.z*s+t.z*r)*Wi.RADIUS}}basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(e,t));return[i,this.normalise(this.cross(e,i))]}subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class Zt{constructor(e,t={}){this.size=e,this.span=Math.min(e.lengthM,Math.max(0,t.spanM??e.lengthM)),this.bank=(e.lengthM-this.span)/2,this.deck=Math.min(e.heightM,t.deckThicknessM??Zt.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??Zt.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??Zt.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??Zt.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(e){const t=Math.abs(e)-this.span/2;return t<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-t/this.bank))}build(){const{widthM:e,heightM:t}=this.size,i=this.span/2,n=[];if(this.span>0){n.push(Zt.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const l of[-1,1]){const c=t-this.deck;c>0&&this.bank>0&&n.push(Zt.box(e+1,c,Zt.ABUTMENT_THICKNESS_M,0,c/2,l*(i-Zt.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(Zt.box(e,.04,this.span,0,t+.02,0));const r=[];for(const l of[-1,1])this.bank<=0||(r.push(this.embankment(l)),s.push(this.bankRoad(l)));const o=[];for(const l of[-1,1])o.push(...this.railing(l*(e/2-Zt.POST_SIDE_M)));return{concrete:Zt.merge(n),road:Zt.merge(s),earth:Zt.merge(r),railing:Zt.merge(o)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),n=[],s=(c,h,d,u)=>{n.push(c.x,c.y,c.z,h.x,h.y,h.z,d.x,d.y,d.z,c.x,c.y,c.z,d.x,d.y,d.z,u.x,u.y,u.z)},r=c=>{const h=this.roadAt(c),d=t+Zt.BANK_SLOPE*h;return{leftFoot:new D(-d,0,c),leftTop:new D(-t,h,c),rightTop:new D(t,h,c),rightFoot:new D(d,0,c)}};for(let c=1;c<i.length;c++){const h=r(i[c-1]),d=r(i[c]),u=e>0,p=(f,g,m,v)=>u?s(f,g,m,v):s(v,m,g,f);p(h.leftFoot,h.leftTop,d.leftTop,d.leftFoot),p(h.leftTop,h.rightTop,d.rightTop,d.leftTop),p(h.rightTop,h.rightFoot,d.rightFoot,d.rightTop)}const o=r(i[0]);e>0?s(o.leftFoot,o.rightFoot,o.rightTop,o.leftTop):s(o.leftTop,o.rightTop,o.rightFoot,o.leftFoot);const l=new ct;return l.setAttribute("position",new wt(n,3)),l.computeVertexNormals(),l}bankRoad(e){const t=this.size.widthM/2,i=this.stations(e),n=[];for(let r=1;r<i.length;r++){const o=i[r-1],l=i[r],c=this.roadAt(o)+.02,h=this.roadAt(l)+.02,d=e>0?[[-t,c,o],[t,c,o],[t,h,l],[-t,h,l]]:[[-t,h,l],[t,h,l],[t,c,o],[-t,c,o]];for(const u of[0,2,1,0,3,2])n.push(...d[u])}const s=new ct;return s.setAttribute("position",new wt(n,3)),s.computeVertexNormals(),s}stations(e){const t=[];for(let i=0;i<=Zt.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/Zt.BANK_STATIONS));return t}railing(e){const t=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),n=[];for(let o=0;o<=i;o++)n.push(-t+this.size.lengthM*o/i);const s=[],r=Zt.POST_SIDE_M;for(const o of n)s.push(Zt.box(r,this.railHeight,r,e,this.roadAt(o)+this.railHeight/2,o));for(let o=1;o<=this.rails;o++){const l=this.railHeight*o/this.rails-Zt.RAIL_HEIGHT_M/2;for(let c=1;c<n.length;c++){const h=new D(e,this.roadAt(n[c-1])+l,n[c-1]),d=new D(e,this.roadAt(n[c])+l,n[c]);s.push(Zt.beam(h,d))}}return s}static box(e,t,i,n,s,r){return new Zi(e,t,i).translate(n,s,r)}static beam(e,t){const i=new D().subVectors(t,e),n=new Zi(Zt.RAIL_DEPTH_M,Zt.RAIL_HEIGHT_M,i.length()),s=new dn().setFromUnitVectors(new D(0,0,1),i.clone().normalize()),r=new D().addVectors(e,t).multiplyScalar(.5);return n.applyMatrix4(new it().compose(r,s,new D(1,1,1)))}static merge(e){const t=e.map(l=>l.getIndex()?l.toNonIndexed():l),i=t.reduce((l,c)=>l+c.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const l of t){const c=l.getAttribute("position"),h=l.getAttribute("normal");n.set(c.array,r*3),h&&s.set(h.array,r*3),r+=c.count}const o=new ct;o.setAttribute("position",new wt(n,3)),o.setAttribute("normal",new wt(s,3));for(const l of e)l.dispose();for(const l of t)l.dispose();return o}}class ja{constructor(e,t={}){this.size=e,this.structure=t}static DEFAULT_DIAMETER_M=.008;static POLE_RADIUS_M=.13;static POLE_ABOVE_M=.5;static NATURAL_SIZE=Object.freeze({widthM:1,lengthM:30,heightM:5});get strands(){const e=this.structure.strands;return!e||e.length===0?[{heightM:this.size.heightM,acrossM:0}]:e.map(t=>({heightM:t.heightM,acrossM:t.acrossM??0}))}get poleStations(){const e=this.size.lengthM/2;switch(this.structure.poles??"both"){case"start":return[e];case"end":return[-e];case"none":return[];default:return[-e,e]}}get poleHeightM(){return this.structure.poleHeightM??Math.max(...this.strands.map(e=>e.heightM))+ja.POLE_ABOVE_M}build(){const e=this.structure.diameterM??ja.DEFAULT_DIAMETER_M,t=this.strands.map(n=>{const s=new us(e/2,e/2,this.size.lengthM,6);return s.rotateX(Math.PI/2),s.translate(n.acrossM,n.heightM,0),s}),i=this.poleStations.map(n=>{const s=new us(ja.POLE_RADIUS_M*.8,ja.POLE_RADIUS_M,this.poleHeightM,8);return s.translate(0,this.poleHeightM/2,n),s});return{strands:t,poles:i}}}const af=Math.PI/180;function Pt(a,e,t,i,n=!1){const s=n?new On({color:new se(...t)}):new Nl({color:new se(...t)}),r=new Ae(e,s);return r.position.y=i,r.userData={emissive:n},r.castShadow=!n,r.receiveShadow=!n,a.add(r),r}const of=.25,U4=.002,B4=100,z4=1500,H4=.25,G4=1e3,V4=.15;function W4(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return[1,1,1];const t=parseInt(e[1],16);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}const X4=[.32,.32,.3],Ew=[1,.85,.5],$4=[.25,.25,.25],_w=[1,.97,.85],Y4=[.55,.68,.72],q4=.12,Xs=.03,$s=.05,Aw={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function yn(a,e){return a?.[e]}function Ys(a,e,t,i,n,s,r,o){if(o===void 0)return;const l=new On({color:new se(...Y4).multiplyScalar(q4),transparent:!0,opacity:o/100,depthWrite:!1}),c=new Ae(new Zi(e,t,i),l);c.position.set(n,s,r),c.renderOrder=2,a.add(c)}const ns=.05,lf=[.6,.58,.53],db=[.5,.5,.48];function rl(a,e,t,i,n,s,r,o){const l=new Nl({color:new se(...o),side:ni}),c=new Ae(new Zi(e,t,i),l);c.position.set(n,s,r),a.add(c)}function K4(a,e,t,i,n,s,r,o,l){const c=(i-s)/2,h=(f,g,m,v)=>{f<=0||(e?rl(a,f,g,ns,m,o+v,r,l):rl(a,ns,g,f,r,o+v,m,l))};h(t,c,0,i/2-c/2),h(t,c,0,-(i/2-c/2));const d=[...n].sort((f,g)=>f.center-g.center);let u=-t/2;for(const f of d){const m=f.center-f.main/2-u;h(m,s,u+m/2,0),u=f.center+f.main/2}const p=t/2-u;h(p,s,u+p/2,0)}function Tw(a,e,t,i,n,s,r,o,l,c){const h=(i+n)/2,d=n-i,u=(p,f,g,m)=>{p.length===0?f?rl(a,g,d,ns,0,h,m,lf):rl(a,ns,d,g,m,h,0,lf):K4(a,f,g,d,p,s,m,h,lf)};u(r,!0,e*2,-t+ns),u(o,!0,e*2,t-ns),u(l,!1,t*2,-e+ns),u(c,!1,t*2,e-ns),rl(a,e*2,ns,t*2,0,i+ns,0,db),rl(a,e*2,ns,t*2,0,n-ns,0,db)}function gm(a,e,t,i){switch(a){case"front":return{x:0,z:-(t-i)};case"behind":return{x:0,z:t-i};case"left":return{x:-(e-i),z:0};case"right":return{x:e-i,z:0};case"front-left":return{x:-(e-i),z:-qs};case"front-right":return{x:e-i,z:-qs};case"behind-left":return{x:-(e-i),z:qs};case"behind-right":return{x:e-i,z:qs}}}function Iw(a,e,t,i,n,s,r,o){const l=ym();l.scale.setScalar(n),l.rotation.y=Aw[t];const{x:c,z:h}=gm(e,s,r,o);l.position.set(c,i,h),a.add(l)}const vm=6,bm=6,jr=3,ac=1.4,oc=jr*.5,Dw=1.2,Rw=.35,Z4=.75,j4=1.6;function ub(a,e,t,i,n){const s=new Ct,r=Math.max(1,a+1),o=r*jr;Pt(s,new Zi(vm,o,bm),[.55,.54,.5],o/2);const l=vm/2,c=bm/2;for(let h=0;h<r;h++){const d=h*jr+jr/2;Ys(s,ac,oc,$s,0,d,-c-Xs,yn(e,"front")),Ys(s,ac,oc,$s,0,d,c+Xs,yn(e,"behind")),Ys(s,$s,oc,ac,-l-Xs,d,0,yn(e,"left")),Ys(s,$s,oc,ac,l+Xs,d,0,yn(e,"right"))}if(t){const h=Math.min(Math.max(i??0,0),r-1);Iw(s,t,n??t,h*jr,.72,l,c,Dw);const d=u=>yn(e,u)!==void 0?[{main:ac,center:0}]:[];Tw(s,l,c,h*jr,(h+1)*jr,oc,d("front"),d("behind"),d("left"),d("right"))}return s}function pb(){const a=new Ct,e=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[t,i,n,s]of e){const r=new yi(n,10,7);r.scale(1,.85,1),r.translate(t,0,i),Pt(a,r,[.26,.28,.17],s)}return a}function J4(a){const e=new Ct,t=new Zt($t.sizeOf(a),a.bridge).build();Pt(e,t.concrete,[.6,.6,.58],0);const i=Pt(e,t.road,[.2,.2,.21],0),n=Pt(e,t.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=kn;return Pt(e,t.railing,[.5,.52,.55],0),e}function Q4(a){const e=new Ct,t=new ja($t.sizeOf(a),a.wire).build();for(const i of t.strands)Pt(e,i,[.1,.1,.11],0);for(const i of t.poles)Pt(e,i,[.3,.24,.18],0);return e}function fb(){const a=new Ct;return Pt(a,new us(.15,.22,2,8),[.32,.22,.14],1),Pt(a,new Bl(1.4,3,8),[.16,.32,.14],3.5),a}const mb=.275,eR=.35,tR=.9,iR=34,nR=8,sR=1.4;function gb(){const a=new Ct,e=new yi(mb,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,eR/mb,1);const t=$t.repeatOnGrid(e,iR,tR,nR,sR),i=Pt(a,t,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=t.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=e.getAttribute("position").count,e.dispose(),a}function vb(){const a=new Ct,e=new yi(1,7,3,0,Math.PI*2,0,Math.PI/2);return Pt(a,e,[.38,.36,.32],0),a}const rR=[.24,.22,.18],aR=[.14,.17,.08];function oR(){const a=new Ct,e=Pt(a,new Zi(1,1,1),rR,.5),t=Pt(a,new Zi(1,.03,1),aR,1.015);for(const i of[e,t])i.material.side=kn;return a}function bb(a){const e=new Ct;return Pt(e,new us(.05,.08,5,8),[.28,.28,.3],2.5),Pt(e,new yi(.25,12,8),a?Ew:X4,5.1,!0),e}const lR=[.08,.08,.08],Xr=.8,Zo=1,Bs=1.7,cf=.6,ba=.46,sd=1.5,Xo=.8,qs=.5,cR=Bs;function yb(a,e,t,i){const n=new Ct;Pt(n,new Zi(1.8,1.4,4.2),[.45,.14,.14],.7),Pt(n,new Zi(Xr*2,cf,Zo*2),[.4,.12,.12],Bs);for(const r of[-1.4,1.4])for(const o of[-.95,.95]){const l=Pt(n,new us(.4,.4,.3,12),lR,.4);l.rotation.z=Math.PI/2,l.position.x=o,l.position.z=r}const s=a?_w:$4;for(const r of[-.7,.7])Pt(n,new yi(.15,8,6),s,.7,!0).position.set(r,.7,-2.1);if(Ys(n,sd,ba,$s,0,Bs,-Zo-Xs,yn(e,"front")),Ys(n,sd,ba,$s,0,Bs,Zo+Xs,yn(e,"behind")),Ys(n,$s,ba,Xo,-Xr-Xs,Bs,-qs,yn(e,"front-left")),Ys(n,$s,ba,Xo,-Xr-Xs,Bs,qs,yn(e,"behind-left")),Ys(n,$s,ba,Xo,Xr+Xs,Bs,-qs,yn(e,"front-right")),Ys(n,$s,ba,Xo,Xr+Xs,Bs,qs,yn(e,"behind-right")),t){Iw(n,t,i??t,Z4,.5,Xr,Zo,Rw);const r=(c,h)=>{const d=[];return yn(e,c)!==void 0&&d.push({main:Xo,center:-qs}),yn(e,h)!==void 0&&d.push({main:Xo,center:qs}),d},o=yn(e,"front")!==void 0?[{main:sd,center:0}]:[],l=yn(e,"behind")!==void 0?[{main:sd,center:0}]:[];Tw(n,Xr,Zo,Bs-cf/2,Bs+cf/2,ba,o,l,r("front-left","behind-left"),r("front-right","behind-right"))}return n}const Mb=new Map;function wb(a,e){if(!a)return;const t=[[a.lengthM,e.lengthM],[a.heightM,e.heightM],[a.widthM,e.widthM]];for(const[i,n]of t)if(i!==void 0&&n>1e-6)return i/n}function hf(a,e){return e>1e-6?a/e:1}const Cw=[.95,.9,.82],xb=[.72,.74,.78];function Sb(){const a=new Ct;Pt(a,new us(.25,.3,1.5,10),xb,.75),Pt(a,new yi(.26,10,8),xb,1.74);const e=Pt(a,new Bl(.07,.16,8),Cw,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,a}function ym(){const a=new Ct;Pt(a,new us(.25,.3,1.5,10),[.3,.3,.35],.75),Pt(a,new yi(.22,10,8),[.62,.52,.46],1.72);const e=Pt(a,new Bl(.07,.16,8),Cw,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,a}const hR=17,Eb=18.5,df=[.16,.16,.18];function _b(){const a=new Ct,e=Pt(a,new us(1.8,1.8,Eb*2,10),df,0);e.rotation.x=Math.PI/2,Pt(a,new Zi(hR*2,.5,4.5),df,0);const t=Pt(a,new Zi(.4,5.5,4),df,3);return t.position.z=-Eb+2,a}class $t{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound","terrace"]);static groundUnderFootprint(e,t,i,n,s,r=0){const o=$t.sizeOf(e);if(r>o.heightM)return s(t,i);const l=(n??0)*Math.PI/180,c=Math.min(21,Math.max(2,Math.ceil(o.lengthM/.75)+1)),h=Math.min(21,Math.max(2,Math.ceil(o.widthM/.75)+1)),d=$t.GROWS_FROM_GROUND.has(e.kind);let u=d?1/0:-1/0;for(let p=0;p<c;p++){const f=(p/(c-1)-.5)*o.lengthM;for(let g=0;g<h;g++){const m=(g/(h-1)-.5)*o.widthM,v=t+Math.sin(l)*f+Math.cos(l)*m,x=i-Math.cos(l)*f+Math.sin(l)*m;u=d?Math.min(u,s(v,x)):Math.max(u,s(v,x))}}return Number.isFinite(u)?u:s(t,i)}static occupantView(e,t=e.headingDeg){const i=e.observerSide;if(!i)throw new Error("occupantView requires object.observerSide to be set");const{x:n,z:s}=e.kind==="vehicle"?gm(i,Xr,Zo,Rw):gm(i,vm/2,bm/2,Dw),r=e.kind==="vehicle"?cR:(e.occupiedFloor??0)*jr+j4,o=(t??0)-Aw[e.observerFacing??i]/af,l=this.scaleFor(e);return{x:n*l.x,z:s*l.z,eyeY:r*l.y,headingDeg:o}}static BODY_NAME="decor-body";static bodyOf(e){return e.getObjectByName($t.BODY_NAME)??e}static repeatOnGrid(e,t,i,n,s){const r=e.getAttribute("position"),o=e.getAttribute("normal"),l=e.getIndex();if(!l)throw new Error("repeatOnGrid needs an indexed geometry");const c=r.count,h=t*n,d=new Float32Array(c*h*3),u=new Float32Array(c*h*3),p=new Uint32Array(l.count*h),f=-((t-1)*i)/2,g=-((n-1)*s)/2;let m=0;for(let x=0;x<n;x++)for(let y=0;y<t;y++,m++){const b=g+x*s,w=f+y*i;for(let S=0;S<c;S++){const _=(m*c+S)*3;d[_]=r.getX(S)+b,d[_+1]=r.getY(S),d[_+2]=r.getZ(S)+w,u[_]=o.getX(S),u[_+1]=o.getY(S),u[_+2]=o.getZ(S)}for(let S=0;S<l.count;S++)p[m*l.count+S]=l.getX(S)+m*c}const v=new ct;return v.setAttribute("position",new wt(d,3)),v.setAttribute("normal",new wt(u,3)),v.setIndex(new Ym(p,1)),v}static fitTerrace(e,t,i){const n=$t.sizeOf(t),s=n.widthM/2,r=n.lengthM/2,o=i(0,0)+n.heightM,l=Math.min(16,Math.max(1,Math.ceil(n.lengthM/3))),c=$t.bodyOf(e).children.filter(b=>b.isMesh);if(c.length<2)return o;const h=Math.min(10,n.widthM/4),d=[-s];for(const b of[.25,.5,.75,1])d.push(-s+h*b);const u=Math.max(1,Math.ceil((n.widthM-2*h)/3));for(let b=1;b<u;b++)d.push(-s+h+(n.widthM-2*h)*b/u);for(const b of[1,.75,.5,.25,0])d.push(s-h*b);const p=b=>-r+n.lengthM*b/l,f=.8,g=(b,w)=>{const S=Math.min(1,Math.max(0,(s-Math.abs(b))/h)),_=S*S*(3-2*S);return _*o+(1-_)*Math.min(o,i(b,w))},m=[],v=(b,w)=>{const S=i(b[0],b[1])-f,_=i(w[0],w[1])-f,M=Math.max(g(b[0],b[1]),S),T=Math.max(g(w[0],w[1]),_);m.push(b[0],S,b[1],w[0],_,w[1],b[0],M,b[1]),m.push(w[0],_,w[1],w[0],T,w[1],b[0],M,b[1])};for(let b=0;b<d.length-1;b++)v([d[b],-r],[d[b+1],-r]),v([d[b],r],[d[b+1],r]);const x=[];for(let b=0;b<d.length-1;b++)for(let w=0;w<l;w++){const S=[d[b],p(w)],_=[d[b+1],p(w)],M=[d[b],p(w+1)],T=[d[b+1],p(w+1)];for(const[A,R,C]of[[S,M,_],[_,M,T]])for(const k of[A,R,C])x.push(k[0],g(k[0],k[1]),k[1])}const y=(b,w)=>{const S=new ct;S.setAttribute("position",new wt(w,3)),S.computeVertexNormals(),b.geometry.dispose(),b.geometry=S,b.position.y=0};return y(c[0],m),y(c[1],x),o}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new D;e.traverse(n=>{const s=n,r=s.userData.cropBasePositions,o=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!o)return;const l=s.geometry.getAttribute("position"),c=new it().copy(s.matrixWorld).invert();for(let h=0;h<l.count;h+=o){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(s.matrixWorld),i.y=t(i.x,i.z),i.applyMatrix4(c);for(let d=h;d<h+o;d++)l.setY(d,r[d*3+1]+i.y)}l.needsUpdate=!0,s.geometry.computeBoundingBox(),s.geometry.computeBoundingSphere()})}static paint(e,t){e.traverse(i=>{const n=i,s=n.userData;if(!n.isMesh||s?.emissive)return;const r=n.material;r?.color&&r.color.set(t)})}static build(e,t){const i=e.kind==="building"?ub(e.floors??hl,e.windows,e.observerSide,e.occupiedFloor,e.observerFacing):e.kind==="tree"?fb():e.kind==="shrub"?pb():e.kind==="bridge"?J4(e):e.kind==="wire"?Q4(e):e.kind==="crop"?gb():e.kind==="terrace"?oR():e.kind==="mound"?vb():e.kind==="streetlight"?bb(t):e.kind==="vehicle"?yb(t,e.windows,e.observerSide,e.observerFacing):e.kind==="aircraft"?_b():e.kind==="entity"?Sb():ym();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new Ct;return i.name=$t.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*af),this.addLights(s,e.lights),s}static scaleFor(e){const t=e.sizeM;if(!t||e.kind==="bridge"||e.kind==="wire"||e.kind==="terrace")return new D(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new D(t.widthM===void 0?1:hf(t.widthM,i.widthM),t.heightM===void 0?1:hf(t.heightM,i.heightM),t.lengthM===void 0?1:hf(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??hl)+1):0;if(e==="bridge")return Zt.NATURAL_SIZE;if(e==="wire")return ja.NATURAL_SIZE;if(e==="terrace")return{widthM:1,lengthM:1,heightM:1};const n=`${e}:${i}`,s=Mb.get(n);if(s)return s;const r=e==="building"?ub(i-1,void 0,void 0,void 0):e==="tree"?fb():e==="shrub"?pb():e==="crop"?gb():e==="mound"?vb():e==="streetlight"?bb(!1):e==="vehicle"?yb(!1,void 0,void 0):e==="aircraft"?_b():e==="entity"?Sb():ym(),o=new un().setFromObject(r),l={widthM:o.max.x-o.min.x,heightM:o.max.y-o.min.y,lengthM:o.max.z-o.min.z};return this.dispose(r),Mb.set(n,l),l}static usesModel(e){return lu(e)!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new Ct;r.name=$t.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*af,i.updateMatrixWorld(!0);const o=new un().setFromObject(i),l={lengthM:o.max.z-o.min.z,heightM:o.max.y-o.min.y,widthM:o.max.x-o.min.x},c=wb(t.sizeM,l)??wb(n.depictedSizeM,l)??1;i.scale.multiplyScalar(c);const h=o.getCenter(new D).multiplyScalar(c);i.position.x-=h.x,i.position.z-=h.z,i.position.y-=t.kind==="aircraft"?h.y:o.min.y*c,i.traverse(d=>{d instanceof Ae&&(d.castShadow=!0,d.receiveShadow=!0)}),r.add(i),s.parent?(s.parent.add(r),s.removeFromParent()):e.add(r),this.dispose(s)}static sizeOf(e){const t=this.naturalSize(e.kind,e.floors);return{widthM:e.sizeM?.widthM??t.widthM,lengthM:e.sizeM?.lengthM??t.lengthM,heightM:e.sizeM?.heightM??t.heightM}}static addLights(e,t){for(const i of t??[]){const n=W4(i.color),s=Pt(e,new yi(of,8,6),n,i.offsetM.y,!0);s.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),s.userData={emissive:!0,lightId:i.id,lightColor:n},s.visible=!1;const r=s.material;r.blending=Bi,r.transparent=!0,r.depthWrite=!1,r.fog=!1}}static setLights(e,t,i,n,s=0,r=1,o=U4,l=[1,1,1]){if(!t||t.length===0)return;const c=new Map(t.map(p=>[p.id,p])),h=Math.max(1,n*o/of),d=of*h,u=r/(Math.PI*d*d);for(const p of e.children){if(!(p instanceof Ae))continue;const f=p.userData.lightId;if(!f)continue;const g=c.get(f);if(!g)continue;const m=s>0?$y(g,i,i+s):Nx(g,i)?1:0;p.visible=m>0;const v=p.material,x=p.userData.lightColor;if(x){const y=m*B4*(g.intensity??1)*u;v.color.setRGB(x[0]*y*l[0],x[1]*y*l[1],x[2]*y*l[2])}p.scale.setScalar(h)}}static setLit(e,t,i,n=1){const[s,r,o]=t==="streetlight"?[z4,H4,Ew]:[G4,V4,_w],l=i?s*n/(Math.PI*r*r):0,c=[o[0]*l,o[1]*l,o[2]*l];e.traverse(h=>{const d=h.userData;!(h instanceof Ae)||!d.emissive||d.lightId||h.material.color.setRGB(...c)})}static dispose(e){e.traverse(t=>{if(!(t instanceof Ae)||t.userData.sharedModel)return;t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const uf="https://ufoathome.org/models/index.json";class Cc{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??dR()}async entries(e){const t=await this.load();return e?t.filter(i=>[i.kind].flat().includes(e)):t}async entry(e){return(await this.load()).find(t=>t.id===e)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8991
|
-
`);let t=Cc.shared.get(e);return t||(t=this.fetchFirstAvailable(),Cc.shared.set(e,t),t.then(i=>{i.length===0&&Cc.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,e).href})):void 0}catch{return}}}function dR(){const a=`?v=${encodeURIComponent("0.
|
|
8955
|
+
`);let t=Cc.shared.get(e);return t||(t=this.fetchFirstAvailable(),Cc.shared.set(e,t),t.then(i=>{i.length===0&&Cc.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,e).href})):void 0}catch{return}}}function dR(){const a=`?v=${encodeURIComponent("0.105.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==uf?[e,uf]:[uf]).map(t=>t+a)}const Pd=[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new Cc}];async function pf(a){const{GLTFLoader:e}=await je(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BlqKtwJh.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(a,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${a}: ${s instanceof Error?s.message:String(s)}`)))})}const Pw=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class Wn{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Ae(new Sn(2,2),new xt({uniforms:{uColor:{value:new se(0,0,0)},uRadius:{value:1}},vertexShader:Wn.VERTEX,fragmentShader:Wn.FRAGMENT,transparent:!0,depthWrite:!1,blending:Bi,toneMapped:!1})),this.mesh.name=e,this.mesh.frustumCulled=!1,this.mesh.renderOrder=t,this.mesh.visible=!1}shine(e,t,i){this.mesh.visible=!0,this.mesh.position.set(e.x,e.y,e.z),this.mesh.material.uniforms.uRadius.value=t,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(e,t,i,n){const s=Math.max(e,n*Wn.MIN_ANGLE_RAD),r=Wn.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Wn.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(Wn.MAX_SHARE*Wn.FILL*Math.PI))}static VERTEX=`
|
|
8992
8956
|
uniform float uRadius;
|
|
8993
8957
|
varying vec2 vOffset;
|
|
8994
8958
|
void main() {
|
|
@@ -9725,7 +9689,7 @@ rr0-duration-input [hidden] { display: none !important; }
|
|
|
9725
9689
|
.model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
|
|
9726
9690
|
.model-picker .model-name { font-weight: 600; }
|
|
9727
9691
|
.model-picker .model-credit { font-size: .8em; color: #666; }
|
|
9728
|
-
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await je(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-BMvmda-2.js");return{ModelThumbnails:i}},__vite__mapDeps([3,4]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const n=document.createElement("button");n.type="button",n.className="model-picker-button",e.after(n),e.hidden=!0;let s=0;const r=()=>{const l=++s,c=e.selectedOptions[0],h=e.value===""?i?.current():void 0;n.replaceChildren();const d=document.createElement("span");d.textContent=`${h?h.title||h.url:c?.textContent??""} …`,n.title=this.messages().choose,n.append(d);const u=e.value;(h?Promise.resolve({url:h.url}):t(u)).then(p=>Oc.pictureOf(p)).then(p=>{if(!p||l!==s)return;const f=new Image;f.src=p,f.alt="",n.prepend(f)})};e.addEventListener("change",r),new MutationObserver(r).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:l=>{i.apply(l),r()}};n.addEventListener("click",()=>void this.open(e,t,o)),r()}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=Oc.STYLE,t.append(i)}open(e,t,i){const n=this.messages(),s=document.createElement("div");s.className="model-picker-backdrop";const r=document.createElement("div");r.className="model-picker",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=n.title;const l=document.createElement("button");l.type="button",l.className="model-picker-close",l.setAttribute("aria-label",n.close),l.title=n.close,l.textContent="✕";const c=document.createElement("header");c.append(o,l);const h=document.createElement("div");h.className="model-picker-body",r.append(c,h),s.append(r);const d=()=>{s.remove(),document.removeEventListener("keydown",u,!0),je(async()=>{const{ModelViewer:S}=await import("./ModelViewer-O9_A3wzF.js");return{ModelViewer:S}},__vite__mapDeps([5,4]),import.meta.url).then(({ModelViewer:S})=>S.end())},u=S=>{S.key==="Escape"&&(S.stopPropagation(),d())},p=i?.current(),f="\0address",g=S=>S===f&&p?Promise.resolve({url:p.url}):t(S),m=S=>{d(),!(S===f||S===e.value)&&(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let v;const x=new Map,y=S=>{const _=document.createElement("button");_.type="button",_.className="model-card",_.setAttribute("aria-pressed",String(S.value===f||S.value===e.value&&!p));const M=document.createElement("div");M.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=S.textContent,_.append(M,T),S.title){const z=document.createElement("span");z.className="model-credit",z.textContent=S.title,_.append(z)}g(S.value).then(z=>Oc.pictureOf(z)).then(z=>{if(!z)return;const L=new Image;L.src=z,L.alt="",M.append(L)});let A,R=!1;const C=()=>{R&&!(A&&!A.active)||(R=!0,Promise.all([g(S.value),je(()=>import("./ModelViewer-O9_A3wzF.js"),__vite__mapDeps([5,4]),import.meta.url)]).then(([z,{ModelViewer:L}])=>{!z||!R||(A=L.show(M,z))}).catch(()=>{}))},k=()=>{R=!1,A?.stop(),A=void 0};return x.set(_,C),_.addEventListener("pointerenter",C),_.addEventListener("focus",C),_.addEventListener("pointerleave",()=>{document.activeElement!==_&&k()}),_.addEventListener("blur",k),_.addEventListener("click",z=>{if(A?.consumeDrag()){z.preventDefault();return}m(S.value)}),_},b=()=>(v=document.createElement("div"),v.className="model-picker-grid",h.append(v),v);if(p){const S=new Option(p.title||p.url,f);S.title=[p.author,p.license].filter(Boolean).join(" — "),b().append(y(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const _=document.createElement("h3");_.textContent=S.label,h.append(_);const M=b();for(const T of Array.from(S.children))M.append(y(T));v=void 0}else S instanceof HTMLOptionElement&&(v??b()).append(y(S));i&&this.addAddressForm(c,l,r,h,i,n,d),l.addEventListener("click",d),s.addEventListener("click",S=>{S.target===s&&d()}),document.addEventListener("keydown",u,!0),this.root.append(s);const w=r.querySelector('.model-card[aria-pressed="true"]');(w??l).focus(),w&&x.get(w)?.()}addAddressForm(e,t,i,n,s,r,o){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(y,b,w="")=>{const S=document.createElement("label"),_=document.createElement("span");_.textContent=y;const M=document.createElement("input");return M.type=b,M.placeholder=w,S.append(_,M),c.append(S),M},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),g=h(r.addressSource,"url","https://…"),m=document.createElement("p");m.textContent=r.addressIncomplete;const v=document.createElement("button");v.type="submit",v.className="model-picker-use",v.textContent=r.addressUse,c.append(m,v),i.insertBefore(c,n);const x=()=>{v.disabled=d.value.trim()==="",m.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const y of[d,u,p,f,g])y.addEventListener("input",x);l.addEventListener("click",()=>{const y=c.hidden;if(c.hidden=!y,l.setAttribute("aria-expanded",String(y)),!y)return;const b=s.current();d.value=b?.url??"",u.value=b?.title??"",p.value=b?.author??"",f.value=b?.license??"",g.value=b?.source??"",x(),d.focus()}),c.addEventListener("submit",y=>{y.preventDefault(),d.value.trim()!==""&&(s.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:g.value.trim()}),o())}),x()}}class Hu{static of(e,t){const i=Hu.drawnAsModel(e);return{color:t?.color??!i,lit:t?.lit??Hu.litByDefault(e.kind,i),lights:(t?.lights??!0)&&Md.forKind(e.kind).length>0,windows:!i&&Cm(e.kind),floors:!i&&e.kind==="building",observerSide:eo(e.kind)}}static drawnAsModel(e){return lu(e)!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static litByDefault(e,t){return e==="streetlight"||e==="vehicle"&&!t}}class Mg{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=Mg.SPAN_DEG;try{const s=(await this.provider.getElevationGrid({south:e-i,north:e+i,west:t-i,east:t+i},{width:2,height:2})).heights[0];return Number.isFinite(s)?s:void 0}catch{return}}}class f6{formatters=new Map;available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const i=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),n=this.zoneOffsetHours(e,new Date(i));if(n!==void 0)return this.zoneOffsetHours(e,new Date(i-n*36e5))??n}zoneOffsetHours(e,t){let i=this.formatters.get(e);if(i===void 0){try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"})}catch{i=null}this.formatters.set(e,i)}if(i===null)return;const n=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",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}zonesAt(e,t){const i=t?.year!==void 0?t:{year:new Date().getFullYear(),month:1,day:1,hour:12};return this.available().filter(n=>this.offsetHoursAt(n,i)===e)}}function mr(a,e){return a.find(t=>t.id===e)??a[0]}class m6{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const i=new URL(this.endpoint);i.searchParams.set("latitude",String(e)),i.searchParams.set("longitude",String(t)),i.searchParams.set("timezone","auto"),i.searchParams.set("forecast_days","1");try{const n=await fetch(i.toString());if(!n.ok)return;const s=await n.json();return s.timezone&&s.timezone!=="GMT"?s.timezone:void 0}catch{return}}}const g6=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new m6}],vy=new Set;qu();FC();const qo={width:48,height:28},v6=2500,by=40,b6=10,yy=600,My=900,Ko=2e-4,y6=900,M6=-1.46,w6=3,Bf=.2,x6=.5,S6=3,E6=.01,_6=1.6,zf=2e3,A6=250,wy=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),Wr=4,fc="ufo-1",xy=["oval","polygon"],T6={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function I6(a){return a.kind==="oval"?"oval":"polygon"}const D6=-6,R6=21;class Di extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=g6[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new f6;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;durationElement;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=h6();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileSyncTimer;fileApplyTimer;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new kf(l6());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorObserverButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=Pd[0].create();confirmOverlay;confirmMessage;confirmAcceptButton;confirmDeclineButton;confirmAnswer;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelCatalogueNote;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorObserverSideSelect;decorWindowInputs;labelDecorSide;optionObserverSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorObserverSide;labelDecorWindows;optionObserverSideNone;optionDecorBuilding;optionDecorTree;optionDecorShrub;optionDecorBridge;optionDecorWire;optionDecorCrop;optionDecorTerrace;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorObserver;recorder;isRecording=!1;messages=Il;currentAppearance={...T6};currentSourceId=fc;selectedSourceIds=new Set([fc]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;addTraceFileInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;labelTrace;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new ol;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),this.confirmOverlay.hidden||this.answerConfirm(!1),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),wy.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;wy.has(e.key)?this.moveOrResizeSelectedShapes(e):this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0;this.endDrag(),e!==void 0&&this.selectDecor(e)};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Bx}</style>${Ux}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const i of this.shadow.querySelectorAll(iu))i.build();for(const i of this.shadow.querySelectorAll(Bu))i.build();this.sceneElement=document.createElement(Uu),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",i=>{this.ufoElement.sighting.observerMap=i.detail.open,this.dispatchEvent(new CustomEvent("sightingchange"))}),this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",i=>{const{lat:n,lng:s}=i.detail;this.latInput.value=String(Number(n.toFixed(6))),this.lngInput.value=String(Number(s.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.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.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new Sc(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const i of[this.timeStartLabel,this.timeEndLabel])i.addEventListener("click",()=>this.switchTimeDisplay()),i.addEventListener("keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.durationElement=this.shadow.querySelector(Bu),this.durationInput=this.durationElement.input,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.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReference=this.shadow.getElementById("label-reference"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),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.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.addTraceFileInput=this.shadow.getElementById("add-trace-file"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.labelTrace=this.shadow.getElementById("label-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],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.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.confirmOverlay=this.shadow.getElementById("confirm-overlay"),this.confirmMessage=this.shadow.getElementById("confirm-message"),this.confirmAcceptButton=this.shadow.getElementById("confirm-ok"),this.confirmDeclineButton=this.shadow.getElementById("confirm-cancel"),this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.modelPicker=new Oc(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.modelPicker.enhance(this.decorModelSelect,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?ou[n.kind]?.id:void 0;return s!==void 0?this.decorModelProvider.entry(s).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):n===void 0?void 0:{decorKind:n.kind}},{current:()=>{const n=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return n?.url===void 0?void 0:{url:n.url,title:n.credit?.title??"",author:n.credit?.author??"",license:n.credit?.license??"",source:n.credit?.sourceUrl??""}},apply:i=>{this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.title,this.decorModelAuthorInput.value=i.author,this.decorModelLicenseInput.value=i.license,this.decorModelSourceInput.value=i.source,this.shownDecorEntry=void 0,this.decorModelSelect.value="",this.updateDecor()}}),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelCatalogueNote=this.shadow.getElementById("decor-model-catalogue"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorObserverSideSelect=this.shadow.getElementById("decorObserverSide"),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.optionObserverSide={front:this.shadow.getElementById("option-observer-side-front"),behind:this.shadow.getElementById("option-observer-side-behind"),left:this.shadow.getElementById("option-observer-side-left"),right:this.shadow.getElementById("option-observer-side-right"),"front-left":this.shadow.getElementById("option-observer-side-front-left"),"front-right":this.shadow.getElementById("option-observer-side-front-right"),"behind-left":this.shadow.getElementById("option-observer-side-behind-left"),"behind-right":this.shadow.getElementById("option-observer-side-behind-right")},this.optionObserverSideNone=this.shadow.getElementById("option-observer-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),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.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorObserverSide=this.shadow.getElementById("label-decor-observer-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.optionDecorShrub=this.shadow.getElementById("option-decor-shrub"),this.optionDecorBridge=this.shadow.getElementById("option-decor-bridge"),this.optionDecorWire=this.shadow.getElementById("option-decor-wire"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorTerrace=this.shadow.getElementById("option-decor-terrace"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorObserver=this.shadow.getElementById("option-decor-observer"),this.ufoElement.canvasElement.addEventListener("pointerdown",i=>{this.focus({preventScroll:!0}),this.onPointerDown(i)}),this.ufoElement.canvasElement.addEventListener("pointermove",i=>this.onPointerMove(i)),this.ufoElement.canvasElement.addEventListener("contextmenu",i=>this.onContextMenu(i)),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.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.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.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()}),this.lightPollutionInput.addEventListener("input",()=>{const i=this.ufoElement.sighting;i.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),i.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),i.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.narrativeRememberInput.addEventListener("change",()=>this.rememberNarrativeSettings()),this.renderNarrativeSettings(),this.durationElement.addEventListener("durationchange",i=>{const{seconds:n,text:s}=i.detail;this.ufoElement.sighting.event.durationText=s,this.ufoElement.durationSeconds=n,this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.addDecorObserverButton.addEventListener("click",()=>this.addDecor("observer")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const i of this.referenceFields)i.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.addTraceFileInput.addEventListener("change",()=>void this.addTracesFromFile()),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",i=>this.onReferenceWheel(i),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",i=>this.onBodyWheel(i),{passive:!1});for(const i of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])i.addEventListener("input",()=>this.updateDecor());this.decorObserverSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const i of[this.milestoneLabelInput,this.milestoneNoteInput])i.addEventListener("input",()=>this.updateMilestone());this.confirmAcceptButton.addEventListener("click",()=>this.answerConfirm(!0)),this.confirmDeclineButton.addEventListener("click",()=>this.answerConfirm(!1)),this.confirmOverlay.addEventListener("click",i=>{i.target===this.confirmOverlay&&this.answerConfirm(!1)});for(const i of Mo)this.decorWindowInputs[i].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(Uw,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(Fw,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const i of xy)this.presetButtons[i].addEventListener("click",()=>this.setAppearance({presetId:i}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const i of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])i.addEventListener("input",()=>this.updateObserver());for(const i of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])i.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",i=>{i.key==="Enter"&&(i.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("input",()=>this.refreshHeadingPoint()),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const i=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const n=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(s=>[s.t,Ui.fovOf(this.ufoElement.sighting,s.t)]));this.retuneFieldOfView(i),this.retuneExposure(i),Ui.reproject(this.ufoElement.sighting,i,n),this.sceneElement.applyFrameFormat(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const t=i=>this.shadow.querySelector(`${iu}[name="${i}"]`);this.startDate=t("obs-time"),this.endDate=t("obs-end-time"),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.startDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=n})}),this.endDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=n})});for(const i of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])i.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const i of this.weatherFields){if(i===this.iceCrystalAlignmentInput){i.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}i.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const i of this.soundFields)i.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(i=>this.shadow.getElementById(i.getAttribute("aria-controls")));for(const i of this.groupTabs)i.addEventListener("click",()=>this.toggleGroup(i,!this.isGroupOpen(i)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const i of this.subgroupTabs)i.addEventListener("click",()=>this.openSubgroup(i));tn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new dl(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",i=>this.onParamSummaryClick(i)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(i=>i.id==="group-shape")],!0),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=Tx(this.shadow.getElementById("cloud-editor"),this.sceneElement,(i=!0)=>{i&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(i,n)=>{this.headingInput.value=String(this.rounded(i)),this.pitchInput.value=String(this.rounded(n)),this.updateObserver()},Fc(hs.preferencesFor(this),Hc)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),hs.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages(),this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??fc,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.offsetIsAuthors=!1,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership(),this.markClean()}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&JSON.stringify(this.sightingData)!==this.baseline}get edited(){return this.touched}markClean(){this.baseline=JSON.stringify(this.sightingData),this.touched=!1}touch=()=>{this.touched=!0};touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=this.sightingData,t=`${e.observer?.id??"sighting"}-sighting.json`,i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,s.click(),URL.revokeObjectURL(n),this.markClean()}async importFromFile(){const e=this.importFileInput.files?.[0];if(e){if(this.holdLoad(()=>void this.loadFile(e))){this.importFileInput.value="";return}await this.loadFile(e)}}async loadFile(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)}),i=JSON.parse(t);if(Es.isCase(i)){if(this.offerCase(i,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=i,this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importUrlInput.value.trim()){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await Nc.json(e);if(Es.isCase(t)){const n=new URL(e,location.href).href;if(this.offerCase(t,n)){this.importUrlInput.value=n;return}throw new Error("A case has no recording to edit here")}const i=t;this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.importUrlInput.value=new URL(e,location.href).href,this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof xa))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";narrativeProvider=fh[0].create();get narrativeSourceId(){return mr(fh,this.chosenSourceId.get("narrative")).id}narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const i=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:Di.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof Bn&&i.kind==="cancelled";this.narrativeStatus.textContent=n?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!n)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:n,...s}=i,r=i.timeZone?s:i,o=Gs.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=Zf(this.ufoElement.sighting);this.sightingData=Gs.apply(c,hu.loadable(r),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,n=new Set(t);for(const s of e.claims)!n.has(s.path)&&!t.some(r=>s.path.startsWith(`${r}.`))||i.provenance.set(s.path,{basis:s.basis,rationale:s.rationale,of:Di.valueAt(Zf(this.ufoElement.sighting),s.path)})}static valueAt(e,t){let i=e;for(const n of t.split(".")){if(typeof i!="object"||i===null)return;i=i[n]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(n=>n.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[C6[t]]));for(const n of i){const s=document.createElement("div");s.className=`claim ${t}`;const r=document.createElement("code");r.textContent=n.path;const o=document.createElement(t==="stated"?"q":"span");o.textContent=n.rationale,s.append(r,o),this.narrativeReport.append(s)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const i of e.gaps){const n=document.createElement("li");n.textContent=i,t.append(n)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=mr(fh,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(n=>n.required&&(this.narrativeSettingInputs.get(n.id)?.value.trim()??"")===""),i=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t!==void 0||i,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsSetting.replace("{setting}",this.said.read(t.label)??t.id).replace("{source}",e):i?this.messages.narrativeNeedsAsk:"",this.narrativeRememberInput.parentElement.hidden=!this.narrativeProvider.settings.some(n=>n.remembered==="credential");for(const n of this.narrativeProvider.settings){const s=this.narrativeSettingInputs.get(n.id);if(!s||!n.suspect)continue;const r=s.value.trim(),o=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",o!==void 0),s.title=o?this.said.read(o)??"":this.said.read(n.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const n=document.createElement("label"),s=document.createElement("span");s.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const l of i.choices??[]){const c=document.createElement("option");c.value=l.value,c.textContent=this.said.read(l.label)??l.value,r.appendChild(c)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"";r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),n.append(s,document.createTextNode(" "),r),n});this.narrativeSettingsBox.replaceChildren(...t),this.narrativeRememberInput.checked=this.narrativeProvider.settings.some(i=>i.remembered==="credential"&&this.storedNarrativeSetting(i.id)!==void 0),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const n=i.value.trim();n!==""&&(e[t]=n)}return e}narrativeErrorFor(e){if(!(e instanceof Bn))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}rememberNarrativeSettings(){try{for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";(e.remembered==="preference"||e.remembered==="credential"&&this.narrativeRememberInput.checked)&&i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}localStorage.removeItem(Di.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Di.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){try{const t=localStorage.getItem(this.narrativeStorageKey(e));if(t!==null)return t;if(this.narrativeSourceId!=="claude")return;const i=e==="key"?Di.NARRATIVE_KEY_STORAGE:e==="workspace"?Di.NARRATIVE_SCOPE_STORAGE:void 0;return i&&localStorage.getItem(i)||void 0}catch{return}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const i=(e%360+360)%360;return String(i)!==t.value&&(t.value=String(i)),i}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",d6,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",u6,e=>{this.weatherInference=new kf(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",ly,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",fh,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Uf,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,gy,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,Mm,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,Pd,()=>this.applyDecorModelSource()))}sourcePicker(e,t,i){const n=document.createDocumentFragment(),s=document.createElement("select");s.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,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const r=document.createElement("a");r.className="source-credit",r.target="_blank",r.rel="noopener noreferrer";const o=()=>{const l=mr(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),i(mr(t,s.value))}),n.append(s,document.createTextNode(" "),r),n}labelledPicker(e,t,i,n){const s=document.createElement("label"),r=document.createElement("span");return r.textContent=t,s.append(r,this.sourcePicker(e,i,n)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:mr(Uf,this.chosenSourceId.get("elevation")).create(),imagery:mr(gy,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(mr(Mm,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=mr(Pd,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),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 i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates)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)<Ko&&Math.abs(t-this.namedCoordinates.lng)<Ko||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),My))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0||this.timeZoneIsStated())return;const i=this.timeZoneLookedUpAt;i&&Math.abs(e-i.lat)<Ko&&Math.abs(t-i.lng)<Ko||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),My))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const i=await this.timeZoneProvider.zoneAt(e,t);this.placeZone=i??void 0,!(!i||this.timeZoneIsStated())&&this.timeZones.available().includes(i)&&(this.autoFilledTimeZone=i,this.timeZoneSelect.value=i,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange")))}async reversePlace(e,t){const i=++this.placeSearchToken;let n;try{n=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}i===this.placeSearchToken&&(this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=n?.name??"",this.placeNameInput.title=n?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=n?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!n,this.updateObserver())}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),n=this.numberOrUndefined(this.pitchInput.value)??0,s=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,o=Math.max(0,r-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Rt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),g=this.numberOrUndefined(this.fNumberInput.value),m=this.filterSelect.value,v=Si.byId(c.getLatestPoseAt(h-1)?.filter),x=m===Si.NONE.id||m===""?v===Si.NONE?void 0:Si.NONE.id:m,y=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=y===u.exposureSeconds?void 0:y;const b=this.numberOrUndefined(this.focusDistanceInput.value),w=Math.abs(f-Rt.fieldOfViewDeg(u))>.01||g!==u.fNumber||b!==void 0||x!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&o===0&&!w?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:f,fNumber:g,focusDistanceM:b,filter:x}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&Tl({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.sighting.event.durationText=void 0,this.ufoElement.durationSeconds=void 0)}refreshTimeZoneOptions(){let e=this.timeZoneSelect.options[0];if(!e){e=document.createElement("option"),e.value="";const t=this.timeZoneSelect.parentNode,i=this.timeZoneSelect.nextSibling;this.timeZoneSelect.remove(),this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(n=>{const s=document.createElement("option");return s.value=n,s.textContent=n,s})),t?.insertBefore(this.timeZoneSelect,i)}e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.value=this.zoneShown()}zoneShown(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone:e.utcOffsetHours===void 0?"":this.preferredZoneFor(e.utcOffsetHours)??""}updateTimeZone(){const e=this.ufoElement.sighting.event,t=this.stringOrUndefined(this.timeZoneSelect.value);if(e.timeZone=t,this.offsetIsAuthors=!1,t===void 0){e.utcOffsetHours=void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup();return}this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event;if(this.offsetIsAuthors&&e.utcOffsetHours!==void 0){const t=this.preferredZoneFor(e.utcOffsetHours);e.timeZone=t,this.timeZoneSelect.value=t??""}else{const t=e.timeZone?this.timeZones.offsetHoursAt(e.timeZone,this.timeZoneReference()):void 0;t!==void 0&&(e.utcOffsetHours=t)}this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}timeZoneReference(){const e=this.ufoElement.sighting.event.time;return e?.year!==void 0?e:{year:new Date().getFullYear(),month:1,day:1,hour:12}}preferredZoneFor(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference());if(t.length===0)return;const i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const n=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return n&&t.includes(n)?n:t[0]}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.stringOrUndefined(this.observerTitleInput.value),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0};e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes"};e.account=Object.values(i).some(n=>n!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...n]=e.sources??[],{url:s,...r}=i??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...n]:n;e.sources=l.length>0?l:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...hi(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...hi(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(n=>n.id===this.currentReferenceId),t=e!==void 0;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const n of[this.referenceSelect,...this.referenceFields])n.disabled=!t,this.setRowVisible(n,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const n of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(n,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSrcInput.value=i?"":e.src,this.referenceSrcInput.disabled=i,this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>YC?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?this.messages.referenceUnreachable:""}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(s=>{if(s.id!==this.currentReferenceId)return s;const r=s.src.startsWith("data:")?s.src:this.referenceSrcInput.value.trim(),o={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||gd))},l=s.registration,c=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.fovDeg;return{...s,kind:this.referenceKindSelect.value,src:r,title:this.said.write(s.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:o,from:c?this.observerPositionNow()??s.from:s.from}});const n=e.references.find(s=>s.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(n),this.syncReferenceStatus(n),this.ufoElement.refresh()}useObserverPoseForReference(){const e=at(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(e.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=at(this.ufoElement.sighting,this.ufoElement.currentTime);return e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0}addReference(e,t,i={}){const n=this.ufoElement.sighting,s=at(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:$C,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:gd},from:this.observerPositionNow(),...i};n.references=[...n.references,o],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const n=this.sceneElement.referenceAspect(t.id);if(!(n!==void 0&&An.picturePointOf(this.directionAtCanvasPoint(e),t.registration,n)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.sceneElement.referenceAspect(t.id):void 0;if(!t||i===void 0)return;const n=8;for(const s of this.currentLandmarks()){const r=this.canvasPointOfDirection(An.worldDirectionOf(s.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=n)return{landmarkId:s.id,end:"picture"};const o=this.canvasPointOfDirection(An.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=n)return{landmarkId:s.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const n=i.x-t.startPointer.x,s=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(n,s)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+n*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-s*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const n=this.currentReference(),s=n?this.sceneElement.referenceAspect(n.id):void 0;if(!n||s===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:An.aimOf(r)};const l=An.picturePointOf(r,n.registration,s);return l?{...o,picture:l}:o})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||gd,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.sceneElement.referenceAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=An.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:An.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=s,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),n=An.solve(i,t,e.registration.fovDeg);n?(this.referenceFit={n:i.length,residualDeg:n.residualDeg},this.referenceHeadingInput.value=String(this.rounded(n.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(n.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(n.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(n.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return An.worldDirectionOf(e.picture,t.registration,i).angleTo(An.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,r]of t.entries()){const o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(o)}this.currentLandmarkId!==void 0&&!t.some(s=>s.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const n=t.find(s=>s.id===this.currentLandmarkId);this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=n===void 0,this.referenceLandmarkLabelInput.disabled=n===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(n?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(o=>o.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const o=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.sceneElement.referenceAspect(t.id);if(i===void 0)return;const{registration:n}=t,s=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(An.worldDirectionOf(o,n,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(An.worldDirectionOf(o.picture,n,i)),scene:this.canvasPointOfDirection(An.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(An.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,r.filter(o=>o.picture!==void 0),this.landmarkHint())};adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:n}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(n??0)),this.updateObserver();const s=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===s);if(r<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",n??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=at(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),i=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const n=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,i,n)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}const s=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!s,this.referenceStreetAddButton.hidden=!s,this.referenceStatus.textContent=s?"":this.messages.referenceStreetNone.replace("{m}",String(n))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:gd}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t,this.setRowVisible(i,t);this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(n=>n.id!==this.currentTraceId?n:{...n,title:this.said.write(n.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(n.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(n=>n.value===this.currentTraceId),i=e.traces.find(n=>n.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTracesFromFile(){const e=this.addTraceFileInput.files?.[0];if(!e)return;this.addTraceFileInput.value="";let t;try{const{KmlImport:c}=await je(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=()=>u(p.error),p.readAsArrayBuffer(e)});t=await c.fromBytes(new Uint8Array(h))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(t.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const i=this.ufoElement.sighting,n=new Set(i.traces.map(c=>c.id));let s=1;const r=this.said.write(void 0,t.documentName??e.name,this.writingLanguage),o=t.traces.map(c=>{for(;n.has(`trace-${s}`);)s++;const h=`trace-${s}`;return n.add(h),{...c,id:h,title:c.title===void 0?void 0:this.said.write(void 0,c.title,this.writingLanguage),source:r}});i.traces=[...i.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=t.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",t.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",e.name)+l,this.ufoElement.refresh()}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of p2){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(),v6)}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=Dm(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 kf(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(),yy))}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&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const n=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=n,this.labelWeatherInferred.title=n;const s=t&&e!==void 0;if(this.weatherSourceLink.hidden=!s,s){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const r=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""}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&&Yn(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(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=ly[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),yy)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,n=this.lightPollutionProvider,s=e.event.time?.year,r=()=>{e.lightPollution!==void 0&&(e.lightPollution=void 0,e.provenance.clear("lightPollution"),this.lightPollutionInput.value="",this.ufoElement.refresh())};if(!t||t.lat===void 0||t.lng===void 0||s===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(s<n.year){r(),this.lightPollutionLookup={status:"too-early",year:s},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const o=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=Tl(t);this.durationElement.set(i!==void 0?i/1e3:void 0,t.durationText)}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=cx(this.ufoElement.sighting.event);this.durationElement.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 i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[n,s]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])n.title=s,n.setAttribute("aria-label",s);this.refreshTimelineMarks()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[i,n]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${n} — ${t}`:n,i.classList.toggle("switchable",e),e?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}chooseTimeInputMode(){const e=this.ufoElement.sighting.event;this.startDate.setPrecise(Gn.opensPrecise(e.time)),this.endDate.setPrecise(Gn.opensPrecise(e.endTime))}syncObservationTimeFields(){this.startDate.time=this.ufoElement.sighting.event.time}syncObservationEndTimeFields(){this.endDate.time=this.ufoElement.sighting.event.endTime}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,i=t===void 0?void 0:Math.round(t/15),n=e!==void 0&&i!==void 0&&Math.abs(e-i)>w6;this.utcOffsetInput.classList.toggle("invalid",n),this.utcOffsetInput.title=n?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),y6))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ko&&Math.abs(e.lng-i)<Ko}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=mr(Uf,this.chosenSourceId.get("elevation")),s=await new Mg(n.create()).at(e,t);if(i!==this.groundElevationToken||s===void 0)return;this.groundElevationFor={lat:e,lng:t};const r=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(s),this.syncElevationField(r),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(at(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=""}syncObserverMetadataFields(){const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=e.observer?.title??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"",this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=hi(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??Od)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],n=this.shadow.activeElement;n!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),n!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),n!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),n!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),n!==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.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=i.getInterpolatedShapeAt(n,this.currentSourceId),r=this.buildAppearanceShape(e??s?.bounds??this.defaultBounds(),s,t);this.commitShapes(n,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const n=Cg(e,this.currentAppearance);return t?{...n,angle:t.angle,title:t.title,selected:t.selected}:n}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.cloudEditor?.stopManipulation();for(const[i,n]of this.groupTabs.entries()){const s=n===e&&t;n.setAttribute("aria-expanded",String(s)),this.groupPanels[i].hidden=!s}this.syncCanvasMode(),this.refreshTimelineMarks(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>this.syncFileEditor(),()=>this.showFileNote(this.messages.importError))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await je(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-SHzsGZVI.js");return{SightingFileEditor:t}},__vite__mapDeps([6,7]),import.meta.url);return this.fileEditor=new e(this.fileEditorHost,this.fileText(),t=>this.onFileTextEdited(t),this.messages.fileEditorLabel),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}showFileNote(e){this.fileNote.textContent=e??"",this.fileNote.hidden=e===void 0}fileText(){return JSON.stringify(this.sightingData,null,2)}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(){const e=this.fileEditor;if(!(e===void 0||!this.isGroupIdOpen("group-file")||e.focused)){try{JSON.parse(e.text)}catch{return}e.text=this.fileText()}}onFileTextEdited(e){clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e){this.fileApplyTimer=void 0;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t)||JSON.stringify(t)===JSON.stringify(this.sightingData))return;const i=this.ufoElement.currentTime;try{this.sightingData=t,this.ufoElement.currentTime=i,this.showFileNote(void 0)}catch{this.showFileNote(this.messages.importErrorMalformed)}}leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(),0))}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(l,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(c=>!l||c.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(c=>c.t)),n=()=>t(this.messages.observerTrack,e.observerTrack.allKeyframes.map(l=>l.t)),s=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?n():this.isGroupIdOpen("group-weather")?s():this.isGroupIdOpen("group-sound")?r():[...i(!1),...n(),...s(),...r()];for(const l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,this.ufoElement.seekableDuration)}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",n=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,n&&this.ufoElement.refresh(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const s=this.currentReference();s&&this.syncReferenceStatus(s),this.syncStreetSearchAvailability(),this.syncBodiesShown()}syncBodiesShown(){const i=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=i!==void 0,this.sceneElement.interpretation!==i&&(this.sceneElement.interpretation=i),this.accountViewSelect.value=i!==void 0?"bodies":"shapes",this.shadow.getElementById("account-view-row").hidden=this.isReading}chooseAccountView(e){const t=this.groupTabs.find(n=>n.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const i of this.subgroupTabs){if(i.parentElement!==t)continue;const n=i===e;i.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(i.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(i=>i.sync()),this.syncCanvasMode()}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}static SUMMARY_GROUPS=["observation","observer","location","decor","temporal","weather","sound"];panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|");i!==this.paramSummarySignature&&(this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=Di.NESTED_GROUPS,t=[];let i;for(const n of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==n.group&&(i=void 0),e.includes(n.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=n.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=n.group==="assessment"?this.messages.assessmentGroup:n.group==="summary"?this.messages.summaryGroup:Di.tabLabel(this.groupTabs[this.summaryPanelIndex(n.group)]),r.append(o),i={group:n.group,element:r},t.push(r)}const s=this.paramChip(n);i?i.element.append(s):t.push(s)}this.paramSummary.replaceChildren(...t),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),Yy.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return e==="phenomenon"?this.panelIndex("shape"):Di.SUMMARY_GROUPS.indexOf(e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]}};assessmentChips=[];assessmentToken=0;async runAssessments(){const e=++this.assessmentToken,t=await new Lx(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.renderParamSummary())}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const r=Di.QUESTION_FIELDS[s];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,r]of Object.entries(Di.QUESTION_FIELDS))for(const o of Di.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(Di.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.classList.contains("wanted")||(c&&(n=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const s of this.groupTabs){const r=this.panelOf(s),o=i.get(r)??0,l=r===n,c=Di.badgeOn(s);c.hidden=o===0,c.textContent=String(o),c.classList.toggle("optional",!l),s.title=o===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o))}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-chip-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(o=>o.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const n=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const s=t.dataset.field;if(s.startsWith("shape:")){this.selectedSourceIds=new Set([s.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(s.startsWith("body:")){const o=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(l=>l.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.sourceSelect,...Object.values(this.presetButtons)])i.disabled=e,i.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:I6(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,lt.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,lt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(lt.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(lt.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!n)return;const s=this.currentProjection(),r=s.degToPx(e),o=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),l={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-o)/2,width:r,height:o},c=s.ofBounds(l),h=n.kind==="oval"?{...n,bounds:l,angular:c}:{...n,bounds:l,angular:c,points:this.scalePoints(n,l)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,n=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*i,y:s.y*n}))}refreshFilterOptions(){const e={[Si.NONE.id]:this.messages.filterNone,[Si.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Si.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=this.filterSelect.value||Si.NONE.id;this.filterSelect.replaceChildren();for(const i of Si.ALL){const n=document.createElement("option");n.value=i.id,n.textContent=e[i.id]??i.name,this.filterSelect.appendChild(n)}this.filterSelect.value=t}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=Rt.availableAt(t),n=e.instrument,s=i.includes(n)?i:[...i,n],r=this.instrumentSelect.value||n.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=this.naming.instrument(o);l.textContent=i.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===r)?r:n.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Di.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const s=Number(i[1]),r=Number(i[2]);return r>0?s/r:void 0}const n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=at(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Rt.fieldOfViewDeg(t),r=n?Rt.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=n?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=n?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=n!==void 0&&n.focalRangeMm===void 0,this.focalLengthInput.min=String(n?n.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(n?n.focalRangeMm?.maxMm??2e3:179),tn.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":Di.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,n!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=Si.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Rt.fieldOfViewDeg(e),n=Rt.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>E6||t.observerTrack.addKeyframe(s.t,{...s.pose,fovDeg:n})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,n=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!n){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(n.max,Math.max(n.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return at(e,this.ufoElement.currentTime)?.fovDeg??Rt.fieldOfViewDeg(e.instrument)}currentProjection(){return Ts.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=lt.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const n=at(this.ufoElement.sighting,this.ufoElement.currentTime),s=n?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const r=(n?Rt.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,o=n?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Xf*e/l*i.heightMm,h=r*r/(o*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const n=this.numberOrUndefined(this.realWidthInput.value),s=n!==void 0&&(t!==void 0&&n<t||i!==void 0&&n>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),o=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+o+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),n=(g,m)=>Number(g.toFixed(m)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??b6,o=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=o!==void 0&&o<r,c=n(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:n(lt.sizeMAt(c,h),2),lengthM:n(lt.sizeMAt(c,h),2),heightM:n(lt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=je(async()=>{const{BodyEditor:e}=await import("./BodyEditor-CiPDf3PA.js");return{BodyEditor:e}},__vite__mapDeps([8,9]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=i===void 0||i<=0?void 0:lt.sizeMAt(e.distanceM,i);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const n={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=n.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,n=Ts.of(i.instrument,lt.CANVAS_HEIGHT_PX,Ui.fovOf(i,e));i.timeline.addKeyframe(e,t.map(s=>{const r=Ui.aimOf(i,e,s.shape.bounds),o=n.ofBounds(s.shape.bounds);return{...s,shape:r?{...s.shape,aim:r,angular:o}:{...s.shape,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;if(e.sourceIds.length>0||this.currentSourceId===void 0){const t=new Set([...e.sourceIds,this.currentSourceId]);let i=t.size+1;for(;t.has(`ufo-${i}`);)i++;this.currentSourceId=`ufo-${i}`}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 t=this.ufoElement.sighting.timeline.sourceIds.filter(n=>this.selectedSourceIds.has(n));if(t.length===0)return;const i=t.length===1?this.messages.confirmDeleteShape.replace("{name}",this.shapeLabel(t[0])):this.messages.confirmDeleteShapes.replace("{count}",String(t.length));this.askConfirm(i,()=>this.removeShapes(t))}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??fc,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}askConfirm(e,t){this.answerConfirm(!1),this.confirmMessage.textContent=e,this.confirmOverlay.hidden=!1,this.confirmAcceptButton.focus(),this.confirmAnswer=t}answerConfirm(e){const t=this.confirmAnswer;this.confirmAnswer=void 0,this.confirmOverlay.hidden=!0,e&&t?.()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const n=document.createElement("option");n.value=i,n.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(n)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;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,n={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="building"?{floors:hl}:{},windows:Xy(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,e)}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const n=this.ufoElement.sighting.decor.find(s=>s.id===e);!n||n.model||n.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(s=>s.id===e?{...s,model:{id:i.id},sizeM:i.sizeM}:s),this.currentDecorId===e&&this.syncDecorModelFields(this.ufoElement.sighting.decor.find(s=>s.id===e)),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*zf,t=Math.round(e/A6*1e3);return{lights:Md.byId("airliner")?.create(),track:[{t:0,eastM:-zf,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:zf,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.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(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,i=this.decorObserverSideSelect.value;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=eo(n.kind)&&i!==""?i:void 0,r=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=n.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:r,northM:o,altitudeM:l,headingDeg:t},u=c.filter(p=>p.t!==h);return{...n,title:this.said.write(n.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),track:[...u,d].sort((p,f)=>p.t-f.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...n,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),eastM:r,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(n=>n.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?$t.naturalSize(e.kind,e.floors):void 0,i=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[n,s,r]of i)n.value=s===void 0?"":String(this.roundedMeters(s)),n.placeholder=r===void 0?"":String(this.roundedMeters(r))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0,this.showDecorCatalogueModel(e)}async showDecorCatalogueModel(e){const t=e?.model?.url===void 0?e?.model?.id:void 0,i=t===void 0?void 0:await this.decorModelProvider.entry(t).catch(()=>{});e?.id===this.currentDecorId&&(this.shownDecorEntry=i,this.decorModelCatalogueNote.hidden=i===void 0,i&&(this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.credit.title,this.decorModelAuthorInput.value=i.credit.author??"",this.decorModelLicenseInput.value=i.credit.license,this.decorModelSourceInput.value=i.credit.sourceUrl??"",this.syncDecorVisibility()))}shownDecorEntry;modelPicker;async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),i=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],n=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=t&&ou[t.kind]?this.messages.decorModelDefault:this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...i.map(r=>{const o=document.createElement("option");return o.value=r.id,o.textContent=r.name,o.title=`${r.credit.title}${r.credit.author?` — ${r.credit.author}`:""} (${r.credit.license})`,o})),this.decorModelSelect.value=n}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,i=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=this.shownDecorEntry;this.shownDecorEntry=t,this.decorModelCatalogueNote.hidden=t===void 0,this.decorModelUrlInput.value=t?.url??"",this.decorModelTitleInput.value=t?.credit.title??"",this.decorModelAuthorInput.value=t?.credit.author??"",this.decorModelLicenseInput.value=t?.credit.license??"",this.decorModelSourceInput.value=t?.credit.sourceUrl??"";const s=i?.sizeM!==void 0&&n?.sizeM!==void 0&&i.sizeM.widthM===n.sizeM.widthM&&i.sizeM.lengthM===n.sizeM.lengthM&&i.sizeM.heightM===n.sizeM.heightM;if(t?.sizeM&&i&&(!i.sizeM||s)){const r=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[o,l]of r)l!==void 0&&(o.value=String(this.roundedMeters(l)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),i=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&i===void 0?void 0:{widthM:e,lengthM:t,heightM:i}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value),t=this.shownDecorEntry;if(t&&e===t.url&&this.stringOrUndefined(this.decorModelTitleInput.value)===t.credit.title&&this.stringOrUndefined(this.decorModelAuthorInput.value)===t.credit.author&&this.stringOrUndefined(this.decorModelLicenseInput.value)===t.credit.license&&this.stringOrUndefined(this.decorModelSourceInput.value)===t.credit.sourceUrl)return{id:t.id};if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),s=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&s!==void 0?{title:n,license:s,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const i=this.stringOrUndefined(this.decorModelSelect.value);return i===void 0?void 0:{id:i}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=io([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(n=>n.t===e);i&&this.askConfirm(this.messages.confirmDeleteMilestone.replace("{name}",this.said.read(i.label)??""),()=>{t.milestones=t.milestones.filter(n=>n.t!==e),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh()})}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=io(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])i.disabled=!t,this.setRowVisible(i,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}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 i={};for(const n of Mo){const s=this.decorWindowInputs[n];if(s.value==="")continue;const r=Yf(t.kind,n)?0:$f,o=Math.max(r,Math.min(100,Number(s.value)));i[n]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:i}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,i=this.decorLitInput.checked;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=[...(n.litKeyframes??[]).filter(r=>r.t!==t),{t,lit:i}].sort((r,o)=>r.t-o.t);return{...n,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.decorLabel(t),this.decorSelect.appendChild(i)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const i of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorObserverSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])i.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?cu(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??hl),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorObserverSideSelect.value=e?.observerSide??"";for(const i of Mo){const n=e?.windows?.[i];this.decorWindowInputs[i].value=n===void 0?"":String(n)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(h=>h.id===this.currentDecorId),t=e!==void 0,i=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.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t);const n=e?Hu.of(e,this.shownDecorEntry?.id===e.model?.id?this.shownDecorEntry?.parameters:void 0):void 0;this.setRowVisible(this.decorColorInput,n?.color===!0),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!0,this.setRowVisible(this.decorLitInput,n?.lit===!0),this.setRowVisible(this.decorLightRigSelect,n?.lights===!0);const s=n?.windows===!0;this.setRowVisible(this.labelDecorWindows,s);const r=i!==void 0?Rm(i):[];for(const h of Mo)this.decorWindowInputs[h].disabled=!t,this.decorWindowInputs[h].min=String(i!==void 0&&Yf(i,h)?0:$f),this.setRowVisible(this.decorWindowInputs[h],s&&r.includes(h));const o=n?.observerSide===!0;this.setRowVisible(this.decorObserverSideSelect,o);const l=i!==void 0?kx(i):[];for(const h of Mo)this.optionObserverSide[h].hidden=!l.includes(h);const c=n?.floors===!0;this.setRowVisible(this.decorFloorsInput,c),this.setRowVisible(this.decorOccupiedFloorInput,c),this.decorOccupiedFloorInput.max=String(e?.floors??hl)}showDecorPlacement(e){const t=e?tr(e,this.ufoElement.currentTime):void 0,i=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[n,s]of i)this.shadow.activeElement!==n&&(n.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;static reentryArchive=new Rn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Nu;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new qn(["en"]);tagNames=new Kf({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,n=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?Yn(i,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([n?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,hi(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showNovaButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.showFireballButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.eclipseClause(n,r),this.moonClause(n,r),this.satelliteClause(n,r),this.reentryClause(n,r),this.fireballClause(n,r),this.opticsClause(n,r),this.rainbowClause(n,r),this.glowClause(n,r)].filter(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return nn.gainFor(e.instrument,{fNumber:at(e,0)?.fNumber,fieldOfViewDeg:Ui.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ni("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=sa(i,n,s),o=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<M6)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(n))).replace("{eye}",o(sa(i,0,s)));return r<=Pc?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Pc))}showerClause(e,t){const i=oi.observedRatePerHour(oi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=El.activeAt(e);if(n.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const o=El.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:El.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerActive.replace("{name}",this.naming.shower(s.entry.shower)).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",this.naming.towards(s.position.azimuthDeg)).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=kd.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=Fu.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}eclipseClause(e,t){const i=bi.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ni("Sun",i.peak,t),s=r=>r.replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),o=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} s`)}return s(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Ni("Moon",e,t);if(i.altitudeDeg<=0||Ca(e).illuminatedFraction<.97)return;const n=[],s=cn.distanceKm(e,t),r=cn.relativeToMean(cn.radiusAtKm(s)),o=s<=cn.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=cn.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return o&&n.push(o.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(cn.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),zu.isIn(e)&&n.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),n.length>0?n.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=Ms.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.hidden=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=sa(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),o=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),n=i+this.satelliteSpanMs(),s=[i,n,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==s){const c={key:s,status:"loading"};this.reentries=c,Di.reentryArchive.candidates(i,n,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=Ms.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(c=>this.reentryText(c));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,n=new Date(e.timeMs);if(t.precision==="day"){const o=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}const s=this.observerClock(n).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",s).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",s).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",s)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses(),n=i.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=n.length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const r=i[0].peak,l=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",r.object.name).replace("{magnitude}",r.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(r.altitudeDeg))).replace("{bearing}",this.naming.towards(r.azimuthDeg)).replace("{time}",this.observerClock(r.date)),c=this.starlinkTrain(i);return c?`${l}, ${c}`:l}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const n=i.peak.magnitude;if(n===void 0)return!1;const s=Ni("Sun",i.peak.date,t);return n<=sa(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,n]=[...t.entries()].sort((r,o)=>o[1]-r[1])[0]??[];if(!i||!n||n<3)return;const s=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(n)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=at(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=Yn(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.visibleSatellitePasses().filter(n=>this.passTimelineMs(n)<=this.ufoElement.seekableDuration);if(e.length===0)return;const t=e.map(n=>`${n.object.norad}@${n.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>os.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=os.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}fireballTimelineMs(e,t){const{record:i}=e,n=i.from[2]-i.to[2],s=Math.abs(n)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/n));return i.t-t.getTime()+s*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.hidden=!i.some(r=>this.fireballTimelineMs(r,e)<=this.ufoElement.seekableDuration),i.length===0)return;const n=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",n.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(n.record.t))).replace("{altitude}",String(Math.round(n.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(n.peak.azimuthDeg)).replace("{distance}",String(Math.round(n.peak.distanceKm/10)*10)).replace("{stations}",String(n.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const n=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(o=>this.fireballTimelineMs(o,n)<=this.ufoElement.seekableDuration);if(s.length===0)return;const r=s[this.fireballRank++%s.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,n),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=hi(this.ufoElement.sighting,0),n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=bt.deckLitUntilDeg(bt.DECK_HEIGHT_M),o=n.altitudeDeg>-r,l=o?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(bt.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(bt.formsAt(l.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??Od;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=hi(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=n.altitudeDeg>0,o=r?n:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(rn.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=rn.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(rn.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Ca(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ni("Sun",e,t);if(i.altitudeDeg>D6)return;const n=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),s=[];if(n.milkyWay&&s.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(n.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(n.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(n.milkyWay.azimuthDeg))),n.zodiacal){const p=n.zodiacal.sunSeparationDeg<=_t.CONE_SEPARATION_DEG;s.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(n.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(n.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(n.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(n.zodiacal.sunSeparationDeg))))}if(s.length>0)return this.listed(s);const r=this.decimal(n.darkestSkyMagPerArcsec2,1),o=Ni("Moon",e,t),l=n.darkestSkyMagPerArcsec2<R6,c=this.ufoElement.sighting.lightPollution,h=ce.scatteringAt(90-o.altitudeDeg)*ce.moonOutput(ce.phaseAngleOf(Ca(e).illuminatedFraction),o.altitudeDeg)*ce.scatteredFraction(90),d=ce.artificialZenithNanolamberts(c)>h;if(l&&o.altitudeDeg>0&&!d){const p=Math.round(Ca(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=ce.artificialZenithNanolamberts(c)>ce.twilightExcessNanolamberts(i.altitudeDeg);return l&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Ni("Sun",e,t),n=Ni("Moon",e,t);return ce.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(Ca(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new _t;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<kd.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=kd.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Fu.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=tr(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,o=Math.atan2(n-_6,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?Md.forKind(e.kind):[],i=document.createElement("option");i.value="",i.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(i,...t.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=this.naming.lightRig(s),r}));const n=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(r=>r.id).join()===n)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(n=>n.id===this.currentDecorId);if(!t)return;const i=Md.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(n=>n.id===t.id?{...n,lights:i?i.create():void 0}:n),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}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=cu(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of xy)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return Cg(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-qo.width/2,y:e.height/2-qo.height/2,width:qo.width,height:qo.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 UC(this.ufoElement.sighting.timeline,new BC(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=++this.localeToken,t=hs.preferencesFor(this);this.preferences=t;const i=Fc(t,Hc),n=this.narrativeProvider.localize?.(i),[s,r,o]=i==="en"?[Il,{},void 0]:await Promise.all([Hy(i),xx(i),Gy(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new Nu(o),this.said=new qn(t),this.tagNames=new Kf(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new dl(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),this.refreshParamSummary()),l?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===fc&&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.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.labelSizeLock.textContent=e.sizeLock;for(const[n,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=s;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.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.labelObserverAge.textContent=e.observerAge,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[n,s]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const r=this.shadow.getElementById(n);r&&(r.textContent=s)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.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.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorShrub.textContent=e.decorShrub,this.optionDecorBridge.textContent=e.decorBridge,this.optionDecorWire.textContent=e.decorWire,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorTerrace.textContent=e.decorTerrace,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showNovaButton.title=e.showNova,this.showNovaButton.setAttribute("aria-label",e.showNova),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.showFireballButton.title=e.showFireball,this.showFireballButton.setAttribute("aria-label",e.showFireball),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorObserver.textContent=e.decorObserver,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.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.confirmAcceptButton.textContent=e.confirmAccept,this.confirmDeclineButton.textContent=e.confirmDecline,this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[n,s]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=s,n.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.decorModelCatalogueNote.textContent=e.decorModelFromCatalogue,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorObserverSide.textContent=e.decorObserverSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionObserverSideNone.textContent=e.decorObserverSideNone;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 Mo)this.labelDecorSide[n].textContent=t[n],this.optionObserverSide[n].textContent=t[n];this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.bodyEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.startDate.messages=e,this.endDate.messages=e,this.paramSummaryBuilder=new dl(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary();const i=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=i?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=e.addReferenceLandmark,this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.labelTraceImport.textContent=e.traceImport,this.labelTrace.textContent=e.trace,this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)&&this.beginCameraDrag(t);return}if(i==="decor"&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t))return;const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const h=new dp(this.selectedMembers()),d=Tt.hitTestHandle({bounds:h.bounds(),angle:0},t);if(d==="rotate"){if(r)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(d){if(r)return;this.dragState={kind:"group-resize",group:h,handle:d},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(s,this.currentSourceId),d=h?.kind==="polygon"?Tt.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&d!==void 0){if(r)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:d},this.startDragListening();return}const u=h&&Tt.hitTestHandle(h,t);if(h&&u){if(r)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const l=this.ufoElement.shapeAt(t.x,t.y,vy);if(!l){const h=this.pickDecorAt(e);if(h!==void 0){r?this.selectDecor(h):this.beginCameraDrag(t,h);return}r||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),r||!o)return;const c=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===l.sourceId?l.shape:n.getInterpolatedShapeAt(s,h)??l.shape}));this.dragState={kind:"move",sources:c,startPointer:t},this.startDragListening()}revealShapePanel(){const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(s=>this.selectedSourceIds.has(s))){if(i.length>=this.selectedSourceIds.size)return;for(const s of i)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,o)=>s.indexOf(r)-s.indexOf(o)).pop()}}else{for(const s of i)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(n,this.currentSourceId):void 0,o=s?.kind==="polygon"&&Tt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,vy);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 i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(n,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,n=i.filter(p=>this.selectedSourceIds.has(p)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(p=>this.selectedSourceIds.has(p)),o=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?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="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?Tt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=Wy;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds];if(t.length===0){const i=document.createElement("span");i.className="submenu-empty",i.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(i)}for(const i of t){const n=document.createElement("label"),s=document.createElement("input");s.type="checkbox",s.checked=e.occludesSourceIds?.includes(i)??!1,s.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,i,s.checked)),n.appendChild(s),n.appendChild(document.createTextNode(this.shapeLabel(i))),this.contextMasksSubmenu.appendChild(n)}}updateDecorOccludesShape(e,t,i){const n=this.ufoElement.sighting;n.decor=n.decor.map(s=>{if(s.id!==e)return s;const r=i?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(o=>o!==t);return{...s,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Tt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Tt.hitTestVertex(i,e);if(n===void 0)return;const s=Tt.deleteVertex(i,n);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,n,s){this.dragState={kind:e,sourceId:t,original:i,handle:s,startPointer:n},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!n||!i)return!1;i.show(n);const s=i.readingNow(),r=this.skyDirectionOf(e);return!s||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:s.azimuthDeg,bodyAltitudeDeg:s.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const n=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+n,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(by,(e.maxX-e.minX)/2*t.width),n=Math.max(by,(e.maxY-e.minY)/2*t.height),s=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:s-i/2,y:r-n/2,width:i,height:n}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),n=e.reading();if(!i||!n)return!1;const s=Tt.hitTestHandle({bounds:i,angle:0},t);if(!s)return!1;if(s==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...n.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:s,centre:r,startPointer:t,startSizeM:{...n.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(s,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:o}=t,l=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=o==="e"||o==="w",h=o==="n"||o==="s",d=c?l(i.x-n.x,s.x-n.x):h?l(i.y-n.y,s.y-n.y):l(Math.hypot(i.x-n.x,i.y-n.y),Math.hypot(s.x-n.x,s.y-n.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:Bf};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.editableDecor()===void 0?void 0:{sizeM:{widthM:this.decorSizeFieldM(this.decorWidthInput),lengthM:this.decorSizeFieldM(this.decorLengthInput),heightM:this.decorSizeFieldM(this.decorHeightInput)},attitude:{headingDeg:this.numberOrUndefined(this.decorHeadingInput.value)??0,pitchDeg:0,rollDeg:0}},resize:e=>{this.decorWidthInput.value=String(this.roundedMeters(e.widthM)),this.decorLengthInput.value=String(this.roundedMeters(e.lengthM)),this.decorHeightInput.value=String(this.roundedMeters(e.heightM)),this.updateDecor()},turnTo:e=>{this.decorHeadingInput.value=String(this.rounded((e.headingDeg%360+360)%360)),this.updateDecor()},rotateDegPerPx:x6};onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!n||!i||(e.preventDefault(),i.show(n),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorSizeFieldM(e){return this.positiveMeters(e.value)??this.positiveMeters(e.placeholder)??1}beginDecorDrag(e,t){const i=this.editableDecor();if(!i)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.pickDecorAt(e)!==i.id)return!1;const n=this.ndcOf(e),s=n&&this.sceneElement.decorGroundPointAt(i.id,n.x,n.y);return s?(this.dragState={kind:"decor-move",id:i.id,startGround:s,startEastM:Number(this.decorEastInput.value)||0,startNorthM:Number(this.decorNorthInput.value)||0},this.setCanvasCursor("move"),this.startDragListening(),!0):!1}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e),n=i&&this.sceneElement.decorGroundPointAt(t.id,i.x,i.y);n&&(this.decorEastInput.value=String(this.roundedMeters(t.startEastM+n.x-t.startGround.x)),this.decorNorthInput.value=String(this.roundedMeters(t.startNorthM-(n.z-t.startGround.z))),this.updateDecor())}beginCameraDrag(e,t){const i=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,moved:!1,startPointer:e,startHeadingDeg:i?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:i?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:i},i||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&eo(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&eo(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:n,startPointer:s}=this.dragState,r=t.x-s.x,o=t.y-s.y,l=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+o}}}));this.commitShapes(i,l)}else if(this.dragState.kind==="group-resize"){const{group:n,handle:s}=this.dragState;this.commitShapes(i,n.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:n,startPointer:s}=this.dragState;this.commitShapes(i,n.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:n,original:s,vertexIndex:r}=this.dragState,o=Tt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}else{const{kind:n,sourceId:s,original:r,handle:o}=this.dragState,l=n==="resize"?Tt.resizeShape(r,o,t):Tt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:n,startPitchDeg:s,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<S6)return;this.cameraDragState.moved=!0}const o=n+(t.x-i.x)*Bf,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Bf));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!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 i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ta,i.width-Wr);break;case"ArrowRight":i.width+=Wr;break;case"ArrowUp":i.height=Math.max(ta,i.height-Wr);break;case"ArrowDown":i.height+=Wr;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Wr;break;case"ArrowRight":i.x+=Wr;break;case"ArrowUp":i.y-=Wr;break;case"ArrowDown":i.y+=Wr;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:n,shape:s}=i[0];this.commitShapes(t,[{sourceId:n,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const n=new dp(i),s=this.nudgeBounds(n.bounds(),e);this.commitShapes(t,n.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const l=r?this.bodyCanvasBounds():void 0,c=l&&Tt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r){const l=this.decorCanvasBounds(),c=l&&Tt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);if(this.pickDecorAt(e)===this.currentDecorId)return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=Tt.hitTestHandle({bounds:new dp(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&Tt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&Tt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Tt.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),n=e.clientX-i.left,s=e.clientY-i.top;this.recorder?.onPointerMove(n,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(Ay(this.buildPrototype({x:0,y:0,width:qo.width,height:qo.height}),n,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const C6={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},Sy="rr0-sighting-editor",Ey="rr0-ufo-recorder";class P6 extends Di{}function Hw(){Fy(),GC(),qu(),customElements.get(Sy)||customElements.define(Sy,Di),customElements.get(Ey)||customElements.define(Ey,P6)}const wm={recording:"Recording",untitledReading:"Reading {n}",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an observation",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"A JSON file",sourceUrl:"An address",observerField:"Observer",fileField:"File",urlField:"Address",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",caseTitle:"Title",caseTime:"When",recordingsHeading:"Observations",add:"Add",addHint:"Add",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},L6=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:wm},Symbol.toStringTag,{value:"Module"})),_y="rr0-case-editor",k6=`
|
|
9692
|
+
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await je(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-BMvmda-2.js");return{ModelThumbnails:i}},__vite__mapDeps([3,4]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const n=document.createElement("button");n.type="button",n.className="model-picker-button",e.after(n),e.hidden=!0;let s=0;const r=()=>{const l=++s,c=e.selectedOptions[0],h=e.value===""?i?.current():void 0;n.replaceChildren();const d=document.createElement("span");d.textContent=`${h?h.title||h.url:c?.textContent??""} …`,n.title=this.messages().choose,n.append(d);const u=e.value;(h?Promise.resolve({url:h.url}):t(u)).then(p=>Oc.pictureOf(p)).then(p=>{if(!p||l!==s)return;const f=new Image;f.src=p,f.alt="",n.prepend(f)})};e.addEventListener("change",r),new MutationObserver(r).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:l=>{i.apply(l),r()}};n.addEventListener("click",()=>void this.open(e,t,o)),r()}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=Oc.STYLE,t.append(i)}open(e,t,i){const n=this.messages(),s=document.createElement("div");s.className="model-picker-backdrop";const r=document.createElement("div");r.className="model-picker",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=n.title;const l=document.createElement("button");l.type="button",l.className="model-picker-close",l.setAttribute("aria-label",n.close),l.title=n.close,l.textContent="✕";const c=document.createElement("header");c.append(o,l);const h=document.createElement("div");h.className="model-picker-body",r.append(c,h),s.append(r);const d=()=>{s.remove(),document.removeEventListener("keydown",u,!0),je(async()=>{const{ModelViewer:S}=await import("./ModelViewer-O9_A3wzF.js");return{ModelViewer:S}},__vite__mapDeps([5,4]),import.meta.url).then(({ModelViewer:S})=>S.end())},u=S=>{S.key==="Escape"&&(S.stopPropagation(),d())},p=i?.current(),f="\0address",g=S=>S===f&&p?Promise.resolve({url:p.url}):t(S),m=S=>{d(),!(S===f||S===e.value)&&(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let v;const x=new Map,y=S=>{const _=document.createElement("button");_.type="button",_.className="model-card",_.setAttribute("aria-pressed",String(S.value===f||S.value===e.value&&!p));const M=document.createElement("div");M.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=S.textContent,_.append(M,T),S.title){const z=document.createElement("span");z.className="model-credit",z.textContent=S.title,_.append(z)}g(S.value).then(z=>Oc.pictureOf(z)).then(z=>{if(!z)return;const L=new Image;L.src=z,L.alt="",M.append(L)});let A,R=!1;const C=()=>{R&&!(A&&!A.active)||(R=!0,Promise.all([g(S.value),je(()=>import("./ModelViewer-O9_A3wzF.js"),__vite__mapDeps([5,4]),import.meta.url)]).then(([z,{ModelViewer:L}])=>{!z||!R||(A=L.show(M,z))}).catch(()=>{}))},k=()=>{R=!1,A?.stop(),A=void 0};return x.set(_,C),_.addEventListener("pointerenter",C),_.addEventListener("focus",C),_.addEventListener("pointerleave",()=>{document.activeElement!==_&&k()}),_.addEventListener("blur",k),_.addEventListener("click",z=>{if(A?.consumeDrag()){z.preventDefault();return}m(S.value)}),_},b=()=>(v=document.createElement("div"),v.className="model-picker-grid",h.append(v),v);if(p){const S=new Option(p.title||p.url,f);S.title=[p.author,p.license].filter(Boolean).join(" — "),b().append(y(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const _=document.createElement("h3");_.textContent=S.label,h.append(_);const M=b();for(const T of Array.from(S.children))M.append(y(T));v=void 0}else S instanceof HTMLOptionElement&&(v??b()).append(y(S));i&&this.addAddressForm(c,l,r,h,i,n,d),l.addEventListener("click",d),s.addEventListener("click",S=>{S.target===s&&d()}),document.addEventListener("keydown",u,!0),this.root.append(s);const w=r.querySelector('.model-card[aria-pressed="true"]');(w??l).focus(),w&&x.get(w)?.()}addAddressForm(e,t,i,n,s,r,o){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(y,b,w="")=>{const S=document.createElement("label"),_=document.createElement("span");_.textContent=y;const M=document.createElement("input");return M.type=b,M.placeholder=w,S.append(_,M),c.append(S),M},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),g=h(r.addressSource,"url","https://…"),m=document.createElement("p");m.textContent=r.addressIncomplete;const v=document.createElement("button");v.type="submit",v.className="model-picker-use",v.textContent=r.addressUse,c.append(m,v),i.insertBefore(c,n);const x=()=>{v.disabled=d.value.trim()==="",m.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const y of[d,u,p,f,g])y.addEventListener("input",x);l.addEventListener("click",()=>{const y=c.hidden;if(c.hidden=!y,l.setAttribute("aria-expanded",String(y)),!y)return;const b=s.current();d.value=b?.url??"",u.value=b?.title??"",p.value=b?.author??"",f.value=b?.license??"",g.value=b?.source??"",x(),d.focus()}),c.addEventListener("submit",y=>{y.preventDefault(),d.value.trim()!==""&&(s.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:g.value.trim()}),o())}),x()}}class Hu{static of(e,t){const i=Hu.drawnAsModel(e);return{color:t?.color??!i,lit:t?.lit??Hu.litByDefault(e.kind,i),lights:(t?.lights??!0)&&Md.forKind(e.kind).length>0,windows:!i&&Cm(e.kind),floors:!i&&e.kind==="building",observerSide:eo(e.kind)}}static drawnAsModel(e){return lu(e)!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static litByDefault(e,t){return e==="streetlight"||e==="vehicle"&&!t}}class Mg{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=Mg.SPAN_DEG;try{const s=(await this.provider.getElevationGrid({south:e-i,north:e+i,west:t-i,east:t+i},{width:2,height:2})).heights[0];return Number.isFinite(s)?s:void 0}catch{return}}}class f6{formatters=new Map;available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const i=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),n=this.zoneOffsetHours(e,new Date(i));if(n!==void 0)return this.zoneOffsetHours(e,new Date(i-n*36e5))??n}zoneOffsetHours(e,t){let i=this.formatters.get(e);if(i===void 0){try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"})}catch{i=null}this.formatters.set(e,i)}if(i===null)return;const n=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",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}zonesAt(e,t){const i=t?.year!==void 0?t:{year:new Date().getFullYear(),month:1,day:1,hour:12};return this.available().filter(n=>this.offsetHoursAt(n,i)===e)}}function mr(a,e){return a.find(t=>t.id===e)??a[0]}class m6{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const i=new URL(this.endpoint);i.searchParams.set("latitude",String(e)),i.searchParams.set("longitude",String(t)),i.searchParams.set("timezone","auto"),i.searchParams.set("forecast_days","1");try{const n=await fetch(i.toString());if(!n.ok)return;const s=await n.json();return s.timezone&&s.timezone!=="GMT"?s.timezone:void 0}catch{return}}}const g6=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new m6}],vy=new Set;qu();FC();const qo={width:48,height:28},v6=2500,by=40,b6=10,yy=600,My=900,Ko=2e-4,y6=900,M6=-1.46,w6=3,Bf=.2,x6=.5,S6=3,E6=.01,_6=1.6,zf=2e3,A6=250,wy=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),Wr=4,fc="ufo-1",xy=["oval","polygon"],T6={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function I6(a){return a.kind==="oval"?"oval":"polygon"}const D6=-6,R6=21;class Di extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=g6[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new f6;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;durationElement;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=h6();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileSyncTimer;fileApplyTimer;historySnapshot;historyTimer;historyAnswering=!1;undoButton;redoButton;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new kf(l6());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorObserverButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=Pd[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelCatalogueNote;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorObserverSideSelect;decorWindowInputs;labelDecorSide;optionObserverSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorObserverSide;labelDecorWindows;optionObserverSideNone;optionDecorBuilding;optionDecorTree;optionDecorShrub;optionDecorBridge;optionDecorWire;optionDecorCrop;optionDecorTerrace;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorObserver;recorder;isRecording=!1;messages=Il;currentAppearance={...T6};currentSourceId=fc;selectedSourceIds=new Set([fc]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;addTraceFileInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;labelTrace;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new ol;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),(e.ctrlKey||e.metaKey)&&!e.altKey&&["z","y"].includes(e.key.toLowerCase())){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;e.preventDefault(),e.key.toLowerCase()==="y"||e.shiftKey?this.redo():this.undo();return}if(wy.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;wy.has(e.key)?this.moveOrResizeSelectedShapes(e):this.canvasMode()==="decor"?this.deleteDecor():this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0;this.endDrag(),e!==void 0&&this.selectDecor(e)};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Bx}</style>${Ux}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const i of this.shadow.querySelectorAll(iu))i.build();for(const i of this.shadow.querySelectorAll(Bu))i.build();this.sceneElement=document.createElement(Uu),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",i=>{this.ufoElement.sighting.observerMap=i.detail.open,this.dispatchEvent(new CustomEvent("sightingchange"))}),this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",i=>{const{lat:n,lng:s}=i.detail;this.latInput.value=String(Number(n.toFixed(6))),this.lngInput.value=String(Number(s.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.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.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new Sc(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const i of[this.timeStartLabel,this.timeEndLabel])i.addEventListener("click",()=>this.switchTimeDisplay()),i.addEventListener("keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.durationElement=this.shadow.querySelector(Bu),this.durationInput=this.durationElement.input,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.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.refreshFilterOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReference=this.shadow.getElementById("label-reference"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),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.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.addTraceFileInput=this.shadow.getElementById("add-trace-file"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.labelTrace=this.shadow.getElementById("label-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],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.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.modelPicker=new Oc(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.modelPicker.enhance(this.decorModelSelect,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?ou[n.kind]?.id:void 0;return s!==void 0?this.decorModelProvider.entry(s).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):n===void 0?void 0:{decorKind:n.kind}},{current:()=>{const n=this.ufoElement.sighting.decor.find(s=>s.id===this.currentDecorId)?.model;return n?.url===void 0?void 0:{url:n.url,title:n.credit?.title??"",author:n.credit?.author??"",license:n.credit?.license??"",source:n.credit?.sourceUrl??""}},apply:i=>{this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.title,this.decorModelAuthorInput.value=i.author,this.decorModelLicenseInput.value=i.license,this.decorModelSourceInput.value=i.source,this.shownDecorEntry=void 0,this.decorModelSelect.value="",this.updateDecor()}}),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelCatalogueNote=this.shadow.getElementById("decor-model-catalogue"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorObserverSideSelect=this.shadow.getElementById("decorObserverSide"),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.optionObserverSide={front:this.shadow.getElementById("option-observer-side-front"),behind:this.shadow.getElementById("option-observer-side-behind"),left:this.shadow.getElementById("option-observer-side-left"),right:this.shadow.getElementById("option-observer-side-right"),"front-left":this.shadow.getElementById("option-observer-side-front-left"),"front-right":this.shadow.getElementById("option-observer-side-front-right"),"behind-left":this.shadow.getElementById("option-observer-side-behind-left"),"behind-right":this.shadow.getElementById("option-observer-side-behind-right")},this.optionObserverSideNone=this.shadow.getElementById("option-observer-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),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.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorObserverSide=this.shadow.getElementById("label-decor-observer-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.optionDecorShrub=this.shadow.getElementById("option-decor-shrub"),this.optionDecorBridge=this.shadow.getElementById("option-decor-bridge"),this.optionDecorWire=this.shadow.getElementById("option-decor-wire"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorTerrace=this.shadow.getElementById("option-decor-terrace"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorObserver=this.shadow.getElementById("option-decor-observer"),this.ufoElement.canvasElement.addEventListener("pointerdown",i=>{this.focus({preventScroll:!0}),this.onPointerDown(i)}),this.ufoElement.canvasElement.addEventListener("pointermove",i=>this.onPointerMove(i)),this.ufoElement.canvasElement.addEventListener("contextmenu",i=>this.onContextMenu(i)),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.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.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.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()}),this.lightPollutionInput.addEventListener("input",()=>{const i=this.ufoElement.sighting;i.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),i.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),i.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.narrativeRememberInput.addEventListener("change",()=>this.rememberNarrativeSettings()),this.renderNarrativeSettings(),this.durationElement.addEventListener("durationchange",i=>{const{seconds:n,text:s}=i.detail;this.ufoElement.sighting.event.durationText=s,this.ufoElement.durationSeconds=n,this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.addDecorObserverButton.addEventListener("click",()=>this.addDecor("observer")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const i of this.referenceFields)i.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.addTraceFileInput.addEventListener("change",()=>void this.addTracesFromFile()),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",i=>this.onReferenceWheel(i),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",i=>this.onBodyWheel(i),{passive:!1});for(const i of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])i.addEventListener("input",()=>this.updateDecor());this.decorObserverSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const i of[this.milestoneLabelInput,this.milestoneNoteInput])i.addEventListener("input",()=>this.updateMilestone());for(const i of Mo)this.decorWindowInputs[i].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(Uw,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(Fw,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const i of xy)this.presetButtons[i].addEventListener("click",()=>this.setAppearance({presetId:i}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const i of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])i.addEventListener("input",()=>this.updateObserver());for(const i of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])i.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",i=>{i.key==="Enter"&&(i.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("input",()=>this.refreshHeadingPoint()),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const i=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const n=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(s=>[s.t,Ui.fovOf(this.ufoElement.sighting,s.t)]));this.retuneFieldOfView(i),this.retuneExposure(i),Ui.reproject(this.ufoElement.sighting,i,n),this.sceneElement.applyFrameFormat(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const t=i=>this.shadow.querySelector(`${iu}[name="${i}"]`);this.startDate=t("obs-time"),this.endDate=t("obs-end-time"),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.startDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=n})}),this.endDate.addEventListener("datechange",i=>{const{time:n}=i.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=n})});for(const i of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])i.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const i of this.weatherFields){if(i===this.iceCrystalAlignmentInput){i.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}i.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const i of this.soundFields)i.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(i=>this.shadow.getElementById(i.getAttribute("aria-controls")));for(const i of this.groupTabs)i.addEventListener("click",()=>this.toggleGroup(i,!this.isGroupOpen(i)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const i of this.subgroupTabs)i.addEventListener("click",()=>this.openSubgroup(i));tn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new dl(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",i=>this.onParamSummaryClick(i)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(i=>i.id==="group-shape")],!0),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=Tx(this.shadow.getElementById("cloud-editor"),this.sceneElement,(i=!0)=>{i&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(i,n)=>{this.headingInput.value=String(this.rounded(i)),this.pitchInput.value=String(this.rounded(n)),this.updateObserver()},Fc(hs.preferencesFor(this),Hc)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),hs.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages(),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??fc,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.offsetIsAuthors=!1,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership(),this.markClean()}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&JSON.stringify(this.sightingData)!==this.baseline}get edited(){return this.touched}markClean(){this.baseline=JSON.stringify(this.sightingData),this.touched=!1}touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>this.syncHistoryButtons(),()=>{})};scheduleHistoryRecord=()=>{this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.text=t,this.syncHistoryButtons())}undo(){this.stepHistory(e=>e.undo())}redo(){this.stepHistory(e=>e.redo())}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text),this.historyAnswering=!0,this.syncHistoryButtons())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=this.sightingData,t=`${e.observer?.id??"sighting"}-sighting.json`,i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,s.click(),URL.revokeObjectURL(n),this.markClean()}async importFromFile(){const e=this.importFileInput.files?.[0];if(e){if(this.holdLoad(()=>void this.loadFile(e))){this.importFileInput.value="";return}await this.loadFile(e)}}async loadFile(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)}),i=JSON.parse(t);if(Es.isCase(i)){if(this.offerCase(i,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=i,this.resetHistory(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importUrlInput.value.trim()){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await Nc.json(e);if(Es.isCase(t)){const n=new URL(e,location.href).href;if(this.offerCase(t,n)){this.importUrlInput.value=n;return}throw new Error("A case has no recording to edit here")}const i=t;this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.resetHistory(),this.importUrlInput.value=new URL(e,location.href).href,this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof xa))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";narrativeProvider=fh[0].create();get narrativeSourceId(){return mr(fh,this.chosenSourceId.get("narrative")).id}narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const i=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:Di.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof Bn&&i.kind==="cancelled";this.narrativeStatus.textContent=n?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!n)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:n,...s}=i,r=i.timeZone?s:i,o=Gs.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=Zf(this.ufoElement.sighting);this.sightingData=Gs.apply(c,hu.loadable(r),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,n=new Set(t);for(const s of e.claims)!n.has(s.path)&&!t.some(r=>s.path.startsWith(`${r}.`))||i.provenance.set(s.path,{basis:s.basis,rationale:s.rationale,of:Di.valueAt(Zf(this.ufoElement.sighting),s.path)})}static valueAt(e,t){let i=e;for(const n of t.split(".")){if(typeof i!="object"||i===null)return;i=i[n]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(n=>n.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[C6[t]]));for(const n of i){const s=document.createElement("div");s.className=`claim ${t}`;const r=document.createElement("code");r.textContent=n.path;const o=document.createElement(t==="stated"?"q":"span");o.textContent=n.rationale,s.append(r,o),this.narrativeReport.append(s)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const i of e.gaps){const n=document.createElement("li");n.textContent=i,t.append(n)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=mr(fh,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(n=>n.required&&(this.narrativeSettingInputs.get(n.id)?.value.trim()??"")===""),i=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t!==void 0||i,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsSetting.replace("{setting}",this.said.read(t.label)??t.id).replace("{source}",e):i?this.messages.narrativeNeedsAsk:"",this.narrativeRememberInput.parentElement.hidden=!this.narrativeProvider.settings.some(n=>n.remembered==="credential");for(const n of this.narrativeProvider.settings){const s=this.narrativeSettingInputs.get(n.id);if(!s||!n.suspect)continue;const r=s.value.trim(),o=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",o!==void 0),s.title=o?this.said.read(o)??"":this.said.read(n.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const n=document.createElement("label"),s=document.createElement("span");s.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const l of i.choices??[]){const c=document.createElement("option");c.value=l.value,c.textContent=this.said.read(l.label)??l.value,r.appendChild(c)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"";r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),n.append(s,document.createTextNode(" "),r),n});this.narrativeSettingsBox.replaceChildren(...t),this.narrativeRememberInput.checked=this.narrativeProvider.settings.some(i=>i.remembered==="credential"&&this.storedNarrativeSetting(i.id)!==void 0),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const n=i.value.trim();n!==""&&(e[t]=n)}return e}narrativeErrorFor(e){if(!(e instanceof Bn))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}rememberNarrativeSettings(){try{for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";(e.remembered==="preference"||e.remembered==="credential"&&this.narrativeRememberInput.checked)&&i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}localStorage.removeItem(Di.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Di.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){try{const t=localStorage.getItem(this.narrativeStorageKey(e));if(t!==null)return t;if(this.narrativeSourceId!=="claude")return;const i=e==="key"?Di.NARRATIVE_KEY_STORAGE:e==="workspace"?Di.NARRATIVE_SCOPE_STORAGE:void 0;return i&&localStorage.getItem(i)||void 0}catch{return}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const i=(e%360+360)%360;return String(i)!==t.value&&(t.value=String(i)),i}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",d6,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",u6,e=>{this.weatherInference=new kf(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",ly,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",fh,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Uf,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,gy,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,Mm,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,Pd,()=>this.applyDecorModelSource()))}sourcePicker(e,t,i){const n=document.createDocumentFragment(),s=document.createElement("select");s.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,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const r=document.createElement("a");r.className="source-credit",r.target="_blank",r.rel="noopener noreferrer";const o=()=>{const l=mr(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),i(mr(t,s.value))}),n.append(s,document.createTextNode(" "),r),n}labelledPicker(e,t,i,n){const s=document.createElement("label"),r=document.createElement("span");return r.textContent=t,s.append(r,this.sourcePicker(e,i,n)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:mr(Uf,this.chosenSourceId.get("elevation")).create(),imagery:mr(gy,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(mr(Mm,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=mr(Pd,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),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 i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates)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)<Ko&&Math.abs(t-this.namedCoordinates.lng)<Ko||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),My))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0||this.timeZoneIsStated())return;const i=this.timeZoneLookedUpAt;i&&Math.abs(e-i.lat)<Ko&&Math.abs(t-i.lng)<Ko||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),My))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const i=await this.timeZoneProvider.zoneAt(e,t);this.placeZone=i??void 0,!(!i||this.timeZoneIsStated())&&this.timeZones.available().includes(i)&&(this.autoFilledTimeZone=i,this.timeZoneSelect.value=i,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange")))}async reversePlace(e,t){const i=++this.placeSearchToken;let n;try{n=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}i===this.placeSearchToken&&(this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=n?.name??"",this.placeNameInput.title=n?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=n?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!n,this.updateObserver())}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),n=this.numberOrUndefined(this.pitchInput.value)??0,s=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,o=Math.max(0,r-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Rt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),g=this.numberOrUndefined(this.fNumberInput.value),m=this.filterSelect.value,v=Si.byId(c.getLatestPoseAt(h-1)?.filter),x=m===Si.NONE.id||m===""?v===Si.NONE?void 0:Si.NONE.id:m,y=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=y===u.exposureSeconds?void 0:y;const b=this.numberOrUndefined(this.focusDistanceInput.value),w=Math.abs(f-Rt.fieldOfViewDeg(u))>.01||g!==u.fNumber||b!==void 0||x!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&o===0&&!w?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:f,fNumber:g,focusDistanceM:b,filter:x}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&Tl({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.sighting.event.durationText=void 0,this.ufoElement.durationSeconds=void 0)}refreshTimeZoneOptions(){let e=this.timeZoneSelect.options[0];if(!e){e=document.createElement("option"),e.value="";const t=this.timeZoneSelect.parentNode,i=this.timeZoneSelect.nextSibling;this.timeZoneSelect.remove(),this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(n=>{const s=document.createElement("option");return s.value=n,s.textContent=n,s})),t?.insertBefore(this.timeZoneSelect,i)}e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.value=this.zoneShown()}zoneShown(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone:e.utcOffsetHours===void 0?"":this.preferredZoneFor(e.utcOffsetHours)??""}updateTimeZone(){const e=this.ufoElement.sighting.event,t=this.stringOrUndefined(this.timeZoneSelect.value);if(e.timeZone=t,this.offsetIsAuthors=!1,t===void 0){e.utcOffsetHours=void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup();return}this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event;if(this.offsetIsAuthors&&e.utcOffsetHours!==void 0){const t=this.preferredZoneFor(e.utcOffsetHours);e.timeZone=t,this.timeZoneSelect.value=t??""}else{const t=e.timeZone?this.timeZones.offsetHoursAt(e.timeZone,this.timeZoneReference()):void 0;t!==void 0&&(e.utcOffsetHours=t)}this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}timeZoneReference(){const e=this.ufoElement.sighting.event.time;return e?.year!==void 0?e:{year:new Date().getFullYear(),month:1,day:1,hour:12}}preferredZoneFor(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference());if(t.length===0)return;const i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const n=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return n&&t.includes(n)?n:t[0]}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.stringOrUndefined(this.observerTitleInput.value),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0};e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes"};e.account=Object.values(i).some(n=>n!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...n]=e.sources??[],{url:s,...r}=i??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...n]:n;e.sources=l.length>0?l:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...hi(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...hi(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(n=>n.id===this.currentReferenceId),t=e!==void 0;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const n of[this.referenceSelect,...this.referenceFields])n.disabled=!t,this.setRowVisible(n,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const n of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(n,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSrcInput.value=i?"":e.src,this.referenceSrcInput.disabled=i,this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>YC?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?this.messages.referenceUnreachable:""}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(s=>{if(s.id!==this.currentReferenceId)return s;const r=s.src.startsWith("data:")?s.src:this.referenceSrcInput.value.trim(),o={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||gd))},l=s.registration,c=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.fovDeg;return{...s,kind:this.referenceKindSelect.value,src:r,title:this.said.write(s.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:o,from:c?this.observerPositionNow()??s.from:s.from}});const n=e.references.find(s=>s.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(n),this.syncReferenceStatus(n),this.ufoElement.refresh()}useObserverPoseForReference(){const e=at(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(e.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=at(this.ufoElement.sighting,this.ufoElement.currentTime);return e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0}addReference(e,t,i={}){const n=this.ufoElement.sighting,s=at(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:$C,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:gd},from:this.observerPositionNow(),...i};n.references=[...n.references,o],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const n=this.sceneElement.referenceAspect(t.id);if(!(n!==void 0&&An.picturePointOf(this.directionAtCanvasPoint(e),t.registration,n)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.sceneElement.referenceAspect(t.id):void 0;if(!t||i===void 0)return;const n=8;for(const s of this.currentLandmarks()){const r=this.canvasPointOfDirection(An.worldDirectionOf(s.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=n)return{landmarkId:s.id,end:"picture"};const o=this.canvasPointOfDirection(An.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=n)return{landmarkId:s.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const n=i.x-t.startPointer.x,s=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(n,s)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+n*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-s*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const n=this.currentReference(),s=n?this.sceneElement.referenceAspect(n.id):void 0;if(!n||s===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:An.aimOf(r)};const l=An.picturePointOf(r,n.registration,s);return l?{...o,picture:l}:o})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||gd,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.sceneElement.referenceAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=An.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:An.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=s,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),n=An.solve(i,t,e.registration.fovDeg);n?(this.referenceFit={n:i.length,residualDeg:n.residualDeg},this.referenceHeadingInput.value=String(this.rounded(n.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(n.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(n.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(n.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return An.worldDirectionOf(e.picture,t.registration,i).angleTo(An.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,r]of t.entries()){const o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(o)}this.currentLandmarkId!==void 0&&!t.some(s=>s.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const n=t.find(s=>s.id===this.currentLandmarkId);this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=n===void 0,this.referenceLandmarkLabelInput.disabled=n===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(n?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(o=>o.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const o=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.sceneElement.referenceAspect(t.id);if(i===void 0)return;const{registration:n}=t,s=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(An.worldDirectionOf(o,n,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(An.worldDirectionOf(o.picture,n,i)),scene:this.canvasPointOfDirection(An.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(An.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,r.filter(o=>o.picture!==void 0),this.landmarkHint())};adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:n}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(n??0)),this.updateObserver();const s=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===s);if(r<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",n??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=at(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),i=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const n=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,i,n)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}const s=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!s,this.referenceStreetAddButton.hidden=!s,this.referenceStatus.textContent=s?"":this.messages.referenceStreetNone.replace("{m}",String(n))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:gd}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t,this.setRowVisible(i,t);this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(n=>n.id!==this.currentTraceId?n:{...n,title:this.said.write(n.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(n.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(n=>n.value===this.currentTraceId),i=e.traces.find(n=>n.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTracesFromFile(){const e=this.addTraceFileInput.files?.[0];if(!e)return;this.addTraceFileInput.value="";let t;try{const{KmlImport:c}=await je(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=()=>u(p.error),p.readAsArrayBuffer(e)});t=await c.fromBytes(new Uint8Array(h))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(t.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const i=this.ufoElement.sighting,n=new Set(i.traces.map(c=>c.id));let s=1;const r=this.said.write(void 0,t.documentName??e.name,this.writingLanguage),o=t.traces.map(c=>{for(;n.has(`trace-${s}`);)s++;const h=`trace-${s}`;return n.add(h),{...c,id:h,title:c.title===void 0?void 0:this.said.write(void 0,c.title,this.writingLanguage),source:r}});i.traces=[...i.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=t.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",t.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",e.name)+l,this.ufoElement.refresh()}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of p2){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(),v6)}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=Dm(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 kf(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(),yy))}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&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const n=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=n,this.labelWeatherInferred.title=n;const s=t&&e!==void 0;if(this.weatherSourceLink.hidden=!s,s){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const r=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""}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&&Yn(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(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=ly[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),yy)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,n=this.lightPollutionProvider,s=e.event.time?.year,r=()=>{e.lightPollution!==void 0&&(e.lightPollution=void 0,e.provenance.clear("lightPollution"),this.lightPollutionInput.value="",this.ufoElement.refresh())};if(!t||t.lat===void 0||t.lng===void 0||s===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(s<n.year){r(),this.lightPollutionLookup={status:"too-early",year:s},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const o=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=Tl(t);this.durationElement.set(i!==void 0?i/1e3:void 0,t.durationText)}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=cx(this.ufoElement.sighting.event);this.durationElement.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 i=t?e?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[n,s]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])n.title=s,n.setAttribute("aria-label",s);this.refreshTimelineMarks()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[i,n]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${n} — ${t}`:n,i.classList.toggle("switchable",e),e?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}chooseTimeInputMode(){const e=this.ufoElement.sighting.event;this.startDate.setPrecise(Gn.opensPrecise(e.time)),this.endDate.setPrecise(Gn.opensPrecise(e.endTime))}syncObservationTimeFields(){this.startDate.time=this.ufoElement.sighting.event.time}syncObservationEndTimeFields(){this.endDate.time=this.ufoElement.sighting.event.endTime}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,i=t===void 0?void 0:Math.round(t/15),n=e!==void 0&&i!==void 0&&Math.abs(e-i)>w6;this.utcOffsetInput.classList.toggle("invalid",n),this.utcOffsetInput.title=n?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),y6))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Ko&&Math.abs(e.lng-i)<Ko}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=mr(Uf,this.chosenSourceId.get("elevation")),s=await new Mg(n.create()).at(e,t);if(i!==this.groundElevationToken||s===void 0)return;this.groundElevationFor={lat:e,lng:t};const r=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(s),this.syncElevationField(r),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(at(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=""}syncObserverMetadataFields(){const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=e.observer?.title??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"",this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=hi(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??Od)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],n=this.shadow.activeElement;n!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),n!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),n!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),n!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),n!==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.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=i.getInterpolatedShapeAt(n,this.currentSourceId),r=this.buildAppearanceShape(e??s?.bounds??this.defaultBounds(),s,t);this.commitShapes(n,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const n=Cg(e,this.currentAppearance);return t?{...n,angle:t.angle,title:t.title,selected:t.selected}:n}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.cloudEditor?.stopManipulation();for(const[i,n]of this.groupTabs.entries()){const s=n===e&&t;n.setAttribute("aria-expanded",String(s)),this.groupPanels[i].hidden=!s}this.syncCanvasMode(),this.refreshTimelineMarks(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>this.syncFileEditor(),()=>this.showFileNote(this.messages.importError))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await je(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-BUpjvTYf.js");return{SightingFileEditor:t}},__vite__mapDeps([6,7]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}showFileNote(e){this.fileNote.textContent=e??"",this.fileNote.hidden=e===void 0}fileText(){return JSON.stringify(this.sightingData,null,2)}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(){const e=this.fileEditor;if(!(e===void 0||!this.isGroupIdOpen("group-file")||e.focused)&&!this.historyAnswering){try{JSON.parse(e.text)}catch{return}e.text=this.fileText()}}onFileTextEdited(e){clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e){this.fileApplyTimer=void 0;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t)||JSON.stringify(t)===JSON.stringify(this.sightingData))return;const i=this.ufoElement.currentTime;try{this.sightingData=t,this.ufoElement.currentTime=i,this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch{this.showFileNote(this.messages.importErrorMalformed)}}leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(),0))}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(l,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(c=>!l||c.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(c=>c.t)),n=()=>t(this.messages.observerTrack,e.observerTrack.allKeyframes.map(l=>l.t)),s=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?n():this.isGroupIdOpen("group-weather")?s():this.isGroupIdOpen("group-sound")?r():[...i(!1),...n(),...s(),...r()];for(const l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,this.ufoElement.seekableDuration)}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",n=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,n&&this.ufoElement.refresh(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const s=this.currentReference();s&&this.syncReferenceStatus(s),this.syncStreetSearchAvailability(),this.syncBodiesShown()}syncBodiesShown(){const i=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=i!==void 0,this.sceneElement.interpretation!==i&&(this.sceneElement.interpretation=i),this.accountViewSelect.value=i!==void 0?"bodies":"shapes",this.shadow.getElementById("account-view-row").hidden=this.isReading}chooseAccountView(e){const t=this.groupTabs.find(n=>n.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const i of this.subgroupTabs){if(i.parentElement!==t)continue;const n=i===e;i.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(i.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(i=>i.sync()),this.syncCanvasMode()}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}static SUMMARY_GROUPS=["observation","observer","location","decor","temporal","weather","sound"];panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|");i!==this.paramSummarySignature&&(this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=Di.NESTED_GROUPS,t=[];let i;for(const n of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==n.group&&(i=void 0),e.includes(n.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=n.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=n.group==="assessment"?this.messages.assessmentGroup:n.group==="summary"?this.messages.summaryGroup:Di.tabLabel(this.groupTabs[this.summaryPanelIndex(n.group)]),r.append(o),i={group:n.group,element:r},t.push(r)}const s=this.paramChip(n);i?i.element.append(s):t.push(s)}this.paramSummary.replaceChildren(...t),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),Yy.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return e==="phenomenon"?this.panelIndex("shape"):Di.SUMMARY_GROUPS.indexOf(e)}static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]}};assessmentChips=[];assessmentToken=0;async runAssessments(){const e=++this.assessmentToken,t=await new Lx(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.renderParamSummary())}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const r=Di.QUESTION_FIELDS[s];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,r]of Object.entries(Di.QUESTION_FIELDS))for(const o of Di.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(Di.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.classList.contains("wanted")||(c&&(n=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const s of this.groupTabs){const r=this.panelOf(s),o=i.get(r)??0,l=r===n,c=Di.badgeOn(s);c.hidden=o===0,c.textContent=String(o),c.classList.toggle("optional",!l),s.title=o===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o))}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-chip-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(o=>o.field==="description")?.full,this.syncDescription();return}const i=Number(t.dataset.panel);if(i<0)return;const n=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const s=t.dataset.field;if(s.startsWith("shape:")){this.selectedSourceIds=new Set([s.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(s.startsWith("body:")){const o=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");o&&this.openSubgroup(o),this.loadBodyEditor().then(l=>l.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.sourceSelect,...Object.values(this.presetButtons)])i.disabled=e,i.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:I6(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,lt.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,lt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(lt.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(lt.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!n)return;const s=this.currentProjection(),r=s.degToPx(e),o=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),l={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-o)/2,width:r,height:o},c=s.ofBounds(l),h=n.kind==="oval"?{...n,bounds:l,angular:c}:{...n,bounds:l,angular:c,points:this.scalePoints(n,l)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,n=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*i,y:s.y*n}))}refreshFilterOptions(){const e={[Si.NONE.id]:this.messages.filterNone,[Si.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[Si.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=this.filterSelect.value||Si.NONE.id;this.filterSelect.replaceChildren();for(const i of Si.ALL){const n=document.createElement("option");n.value=i.id,n.textContent=e[i.id]??i.name,this.filterSelect.appendChild(n)}this.filterSelect.value=t}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=Rt.availableAt(t),n=e.instrument,s=i.includes(n)?i:[...i,n],r=this.instrumentSelect.value||n.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=this.naming.instrument(o);l.textContent=i.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===r)?r:n.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Di.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const s=Number(i[1]),r=Number(i[2]);return r>0?s/r:void 0}const n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=at(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Rt.fieldOfViewDeg(t),r=n?Rt.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=n?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=n?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=n!==void 0&&n.focalRangeMm===void 0,this.focalLengthInput.min=String(n?n.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(n?n.focalRangeMm?.maxMm??2e3:179),tn.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":Di.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,n!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=Si.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Rt.fieldOfViewDeg(e),n=Rt.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>E6||t.observerTrack.addKeyframe(s.t,{...s.pose,fovDeg:n})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,n=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!n){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(n.max,Math.max(n.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return at(e,this.ufoElement.currentTime)?.fovDeg??Rt.fieldOfViewDeg(e.instrument)}currentProjection(){return Ts.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=lt.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const n=at(this.ufoElement.sighting,this.ufoElement.currentTime),s=n?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const r=(n?Rt.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,o=n?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Xf*e/l*i.heightMm,h=r*r/(o*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const n=this.numberOrUndefined(this.realWidthInput.value),s=n!==void 0&&(t!==void 0&&n<t||i!==void 0&&n>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),o=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+o+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),n=(g,m)=>Number(g.toFixed(m)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??b6,o=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=o!==void 0&&o<r,c=n(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:n(lt.sizeMAt(c,h),2),lengthM:n(lt.sizeMAt(c,h),2),heightM:n(lt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=je(async()=>{const{BodyEditor:e}=await import("./BodyEditor-CiPDf3PA.js");return{BodyEditor:e}},__vite__mapDeps([8,9]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,modelProvider:()=>this.decorModelProvider,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=i===void 0||i<=0?void 0:lt.sizeMAt(e.distanceM,i);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const n={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=n.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,n=Ts.of(i.instrument,lt.CANVAS_HEIGHT_PX,Ui.fovOf(i,e));i.timeline.addKeyframe(e,t.map(s=>{const r=Ui.aimOf(i,e,s.shape.bounds),o=n.ofBounds(s.shape.bounds);return{...s,shape:r?{...s.shape,aim:r,angular:o}:{...s.shape,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;if(e.sourceIds.length>0||this.currentSourceId===void 0){const t=new Set([...e.sourceIds,this.currentSourceId]);let i=t.size+1;for(;t.has(`ufo-${i}`);)i++;this.currentSourceId=`ufo-${i}`}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 t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??fc,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const n=document.createElement("option");n.value=i,n.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(n)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;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,n={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="building"?{floors:hl}:{},windows:Xy(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,e)}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const n=this.ufoElement.sighting.decor.find(s=>s.id===e);!n||n.model||n.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(s=>s.id===e?{...s,model:{id:i.id},sizeM:i.sizeM}:s),this.currentDecorId===e&&this.syncDecorModelFields(this.ufoElement.sighting.decor.find(s=>s.id===e)),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*zf,t=Math.round(e/A6*1e3);return{lights:Md.byId("airliner")?.create(),track:[{t:0,eastM:-zf,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:zf,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??e} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.decorSelect.value=e,this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,i=this.decorObserverSideSelect.value;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=eo(n.kind)&&i!==""?i:void 0,r=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=n.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:r,northM:o,altitudeM:l,headingDeg:t},u=c.filter(p=>p.t!==h);return{...n,title:this.said.write(n.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),track:[...u,d].sort((p,f)=>p.t-f.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...n,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),eastM:r,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(n=>n.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?$t.naturalSize(e.kind,e.floors):void 0,i=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[n,s,r]of i)n.value=s===void 0?"":String(this.roundedMeters(s)),n.placeholder=r===void 0?"":String(this.roundedMeters(r))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0,this.showDecorCatalogueModel(e)}async showDecorCatalogueModel(e){const t=e?.model?.url===void 0?e?.model?.id:void 0,i=t===void 0?void 0:await this.decorModelProvider.entry(t).catch(()=>{});e?.id===this.currentDecorId&&(this.shownDecorEntry=i,this.decorModelCatalogueNote.hidden=i===void 0,i&&(this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.credit.title,this.decorModelAuthorInput.value=i.credit.author??"",this.decorModelLicenseInput.value=i.credit.license,this.decorModelSourceInput.value=i.credit.sourceUrl??"",this.syncDecorVisibility()))}shownDecorEntry;modelPicker;async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),i=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],n=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=t&&ou[t.kind]?this.messages.decorModelDefault:this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...i.map(r=>{const o=document.createElement("option");return o.value=r.id,o.textContent=r.name,o.title=`${r.credit.title}${r.credit.author?` — ${r.credit.author}`:""} (${r.credit.license})`,o})),this.decorModelSelect.value=n}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,i=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=this.shownDecorEntry;this.shownDecorEntry=t,this.decorModelCatalogueNote.hidden=t===void 0,this.decorModelUrlInput.value=t?.url??"",this.decorModelTitleInput.value=t?.credit.title??"",this.decorModelAuthorInput.value=t?.credit.author??"",this.decorModelLicenseInput.value=t?.credit.license??"",this.decorModelSourceInput.value=t?.credit.sourceUrl??"";const s=i?.sizeM!==void 0&&n?.sizeM!==void 0&&i.sizeM.widthM===n.sizeM.widthM&&i.sizeM.lengthM===n.sizeM.lengthM&&i.sizeM.heightM===n.sizeM.heightM;if(t?.sizeM&&i&&(!i.sizeM||s)){const r=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[o,l]of r)l!==void 0&&(o.value=String(this.roundedMeters(l)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),i=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&i===void 0?void 0:{widthM:e,lengthM:t,heightM:i}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value),t=this.shownDecorEntry;if(t&&e===t.url&&this.stringOrUndefined(this.decorModelTitleInput.value)===t.credit.title&&this.stringOrUndefined(this.decorModelAuthorInput.value)===t.credit.author&&this.stringOrUndefined(this.decorModelLicenseInput.value)===t.credit.license&&this.stringOrUndefined(this.decorModelSourceInput.value)===t.credit.sourceUrl)return{id:t.id};if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),s=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&s!==void 0?{title:n,license:s,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const i=this.stringOrUndefined(this.decorModelSelect.value);return i===void 0?void 0:{id:i}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=io([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(n=>n.t===e);i&&(t.milestones=t.milestones.filter(n=>n.t!==i.t),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh())}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=io(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])i.disabled=!t,this.setRowVisible(i,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}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 i={};for(const n of Mo){const s=this.decorWindowInputs[n];if(s.value==="")continue;const r=Yf(t.kind,n)?0:$f,o=Math.max(r,Math.min(100,Number(s.value)));i[n]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:i}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,i=this.decorLitInput.checked;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=[...(n.litKeyframes??[]).filter(r=>r.t!==t),{t,lit:i}].sort((r,o)=>r.t-o.t);return{...n,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.decorLabel(t),this.decorSelect.appendChild(i)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const i of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorObserverSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])i.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?cu(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??hl),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorObserverSideSelect.value=e?.observerSide??"";for(const i of Mo){const n=e?.windows?.[i];this.decorWindowInputs[i].value=n===void 0?"":String(n)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(h=>h.id===this.currentDecorId),t=e!==void 0,i=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.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t);const n=e?Hu.of(e,this.shownDecorEntry?.id===e.model?.id?this.shownDecorEntry?.parameters:void 0):void 0;this.setRowVisible(this.decorColorInput,n?.color===!0),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!0,this.setRowVisible(this.decorLitInput,n?.lit===!0),this.setRowVisible(this.decorLightRigSelect,n?.lights===!0);const s=n?.windows===!0;this.setRowVisible(this.labelDecorWindows,s);const r=i!==void 0?Rm(i):[];for(const h of Mo)this.decorWindowInputs[h].disabled=!t,this.decorWindowInputs[h].min=String(i!==void 0&&Yf(i,h)?0:$f),this.setRowVisible(this.decorWindowInputs[h],s&&r.includes(h));const o=n?.observerSide===!0;this.setRowVisible(this.decorObserverSideSelect,o);const l=i!==void 0?kx(i):[];for(const h of Mo)this.optionObserverSide[h].hidden=!l.includes(h);const c=n?.floors===!0;this.setRowVisible(this.decorFloorsInput,c),this.setRowVisible(this.decorOccupiedFloorInput,c),this.decorOccupiedFloorInput.max=String(e?.floors??hl)}showDecorPlacement(e){const t=e?tr(e,this.ufoElement.currentTime):void 0,i=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[n,s]of i)this.shadow.activeElement!==n&&(n.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;static reentryArchive=new Rn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Nu;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new qn(["en"]);tagNames=new Kf({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,n=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?Yn(i,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([n?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,hi(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showNovaButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.showFireballButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.eclipseClause(n,r),this.moonClause(n,r),this.satelliteClause(n,r),this.reentryClause(n,r),this.fireballClause(n,r),this.opticsClause(n,r),this.rainbowClause(n,r),this.glowClause(n,r)].filter(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return nn.gainFor(e.instrument,{fNumber:at(e,0)?.fNumber,fieldOfViewDeg:Ui.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ni("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=sa(i,n,s),o=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<M6)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(n))).replace("{eye}",o(sa(i,0,s)));return r<=Pc?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",o(Pc))}showerClause(e,t){const i=oi.observedRatePerHour(oi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=El.activeAt(e);if(n.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const o=El.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:El.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerActive.replace("{name}",this.naming.shower(s.entry.shower)).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",this.naming.towards(s.position.azimuthDeg)).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=kd.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=Fu.brightestAt(e,t);if(!i||i.magnitude>Fl){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}eclipseClause(e,t){const i=bi.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ni("Sun",i.peak,t),s=r=>r.replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),o=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${o} s`)}return s(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Ni("Moon",e,t);if(i.altitudeDeg<=0||Ca(e).illuminatedFraction<.97)return;const n=[],s=cn.distanceKm(e,t),r=cn.relativeToMean(cn.radiusAtKm(s)),o=s<=cn.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=cn.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return o&&n.push(o.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(cn.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),zu.isIn(e)&&n.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),n.length>0?n.join(" · "):void 0}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=Ms.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.hidden=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=sa(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),o=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),n=i+this.satelliteSpanMs(),s=[i,n,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==s){const c={key:s,status:"loading"};this.reentries=c,Di.reentryArchive.candidates(i,n,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=Ms.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(c=>this.reentryText(c));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,n=new Date(e.timeMs);if(t.precision==="day"){const o=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}const s=this.observerClock(n).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",s).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",s).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",s)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses(),n=i.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=n.length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const r=i[0].peak,l=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",r.object.name).replace("{magnitude}",r.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(r.altitudeDeg))).replace("{bearing}",this.naming.towards(r.azimuthDeg)).replace("{time}",this.observerClock(r.date)),c=this.starlinkTrain(i);return c?`${l}, ${c}`:l}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const n=i.peak.magnitude;if(n===void 0)return!1;const s=Ni("Sun",i.peak.date,t);return n<=sa(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,n]=[...t.entries()].sort((r,o)=>o[1]-r[1])[0]??[];if(!i||!n||n<3)return;const s=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(n)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=at(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=Yn(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.visibleSatellitePasses().filter(n=>this.passTimelineMs(n)<=this.ufoElement.seekableDuration);if(e.length===0)return;const t=e.map(n=>`${n.object.norad}@${n.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>os.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=os.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}fireballTimelineMs(e,t){const{record:i}=e,n=i.from[2]-i.to[2],s=Math.abs(n)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/n));return i.t-t.getTime()+s*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.hidden=!i.some(r=>this.fireballTimelineMs(r,e)<=this.ufoElement.seekableDuration),i.length===0)return;const n=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",n.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(n.record.t))).replace("{altitude}",String(Math.round(n.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(n.peak.azimuthDeg)).replace("{distance}",String(Math.round(n.peak.distanceKm/10)*10)).replace("{stations}",String(n.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const n=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(o=>this.fireballTimelineMs(o,n)<=this.ufoElement.seekableDuration);if(s.length===0)return;const r=s[this.fireballRank++%s.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,n),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=hi(this.ufoElement.sighting,0),n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=bt.deckLitUntilDeg(bt.DECK_HEIGHT_M),o=n.altitudeDeg>-r,l=o?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(bt.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(bt.formsAt(l.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??Od;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=hi(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ni("Sun",e,t),s=Ni("Moon",e,t),r=n.altitudeDeg>0,o=r?n:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(rn.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=rn.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(rn.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(Ca(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ni("Sun",e,t);if(i.altitudeDeg>D6)return;const n=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),s=[];if(n.milkyWay&&s.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(n.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(n.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(n.milkyWay.azimuthDeg))),n.zodiacal){const p=n.zodiacal.sunSeparationDeg<=_t.CONE_SEPARATION_DEG;s.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(n.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(n.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(n.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(n.zodiacal.sunSeparationDeg))))}if(s.length>0)return this.listed(s);const r=this.decimal(n.darkestSkyMagPerArcsec2,1),o=Ni("Moon",e,t),l=n.darkestSkyMagPerArcsec2<R6,c=this.ufoElement.sighting.lightPollution,h=ce.scatteringAt(90-o.altitudeDeg)*ce.moonOutput(ce.phaseAngleOf(Ca(e).illuminatedFraction),o.altitudeDeg)*ce.scatteredFraction(90),d=ce.artificialZenithNanolamberts(c)>h;if(l&&o.altitudeDeg>0&&!d){const p=Math.round(Ca(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=ce.artificialZenithNanolamberts(c)>ce.twilightExcessNanolamberts(i.altitudeDeg);return l&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Ni("Sun",e,t),n=Ni("Moon",e,t);return ce.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(Ca(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new _t;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<kd.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=kd.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Yn(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Fu.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=tr(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,o=Math.atan2(n-_6,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?Md.forKind(e.kind):[],i=document.createElement("option");i.value="",i.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(i,...t.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=this.naming.lightRig(s),r}));const n=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(r=>r.id).join()===n)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(n=>n.id===this.currentDecorId);if(!t)return;const i=Md.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(n=>n.id===t.id?{...n,lights:i?i.create():void 0}:n),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}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=cu(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of xy)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return Cg(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-qo.width/2,y:e.height/2-qo.height/2,width:qo.width,height:qo.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 UC(this.ufoElement.sighting.timeline,new BC(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=++this.localeToken,t=hs.preferencesFor(this);this.preferences=t;const i=Fc(t,Hc),n=this.narrativeProvider.localize?.(i),[s,r,o]=i==="en"?[Il,{},void 0]:await Promise.all([Hy(i),xx(i),Gy(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new Nu(o),this.said=new qn(t),this.tagNames=new Kf(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new dl(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),this.refreshParamSummary()),l?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===fc&&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.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.labelSizeLock.textContent=e.sizeLock;for(const[n,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=s;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.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.labelObserverAge.textContent=e.observerAge,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[n,s]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const r=this.shadow.getElementById(n);r&&(r.textContent=s)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.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.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorShrub.textContent=e.decorShrub,this.optionDecorBridge.textContent=e.decorBridge,this.optionDecorWire.textContent=e.decorWire,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorTerrace.textContent=e.decorTerrace,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showNovaButton.title=e.showNova,this.showNovaButton.setAttribute("aria-label",e.showNova),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.showFireballButton.title=e.showFireball,this.showFireballButton.setAttribute("aria-label",e.showFireball),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorObserver.textContent=e.decorObserver,this.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.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.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[n,s]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=s,n.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.decorModelCatalogueNote.textContent=e.decorModelFromCatalogue,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorObserverSide.textContent=e.decorObserverSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionObserverSideNone.textContent=e.decorObserverSideNone;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 Mo)this.labelDecorSide[n].textContent=t[n],this.optionObserverSide[n].textContent=t[n];this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.bodyEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.startDate.messages=e,this.endDate.messages=e,this.paramSummaryBuilder=new dl(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),this.refreshParamSummary();const i=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=i?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=e.addReferenceLandmark,this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.labelTraceImport.textContent=e.traceImport,this.labelTrace.textContent=e.trace,this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)&&this.beginCameraDrag(t);return}if(i==="decor"&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t))return;const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const h=new dp(this.selectedMembers()),d=Tt.hitTestHandle({bounds:h.bounds(),angle:0},t);if(d==="rotate"){if(r)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(d){if(r)return;this.dragState={kind:"group-resize",group:h,handle:d},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(s,this.currentSourceId),d=h?.kind==="polygon"?Tt.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&d!==void 0){if(r)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:d},this.startDragListening();return}const u=h&&Tt.hitTestHandle(h,t);if(h&&u){if(r)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const l=this.ufoElement.shapeAt(t.x,t.y,vy);if(!l){const h=this.pickDecorAt(e);if(h!==void 0){r?this.selectDecor(h):this.beginCameraDrag(t,h);return}r||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),r||!o)return;const c=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===l.sourceId?l.shape:n.getInterpolatedShapeAt(s,h)??l.shape}));this.dragState={kind:"move",sources:c,startPointer:t},this.startDragListening()}revealShapePanel(){const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(s=>this.selectedSourceIds.has(s))){if(i.length>=this.selectedSourceIds.size)return;for(const s of i)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,o)=>s.indexOf(r)-s.indexOf(o)).pop()}}else{for(const s of i)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(n,this.currentSourceId):void 0,o=s?.kind==="polygon"&&Tt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,vy);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 i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(n,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,n=i.filter(p=>this.selectedSourceIds.has(p)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(p=>this.selectedSourceIds.has(p)),o=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?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="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?Tt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=Wy;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";const t=[...this.ufoElement.sighting.timeline.sourceIds];if(t.length===0){const i=document.createElement("span");i.className="submenu-empty",i.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(i)}for(const i of t){const n=document.createElement("label"),s=document.createElement("input");s.type="checkbox",s.checked=e.occludesSourceIds?.includes(i)??!1,s.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,i,s.checked)),n.appendChild(s),n.appendChild(document.createTextNode(this.shapeLabel(i))),this.contextMasksSubmenu.appendChild(n)}}updateDecorOccludesShape(e,t,i){const n=this.ufoElement.sighting;n.decor=n.decor.map(s=>{if(s.id!==e)return s;const r=i?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(o=>o!==t);return{...s,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Tt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=Tt.hitTestVertex(i,e);if(n===void 0)return;const s=Tt.deleteVertex(i,n);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,n,s){this.dragState={kind:e,sourceId:t,original:i,handle:s,startPointer:n},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!n||!i)return!1;i.show(n);const s=i.readingNow(),r=this.skyDirectionOf(e);return!s||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:s.azimuthDeg,bodyAltitudeDeg:s.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const n=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+n,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(by,(e.maxX-e.minX)/2*t.width),n=Math.max(by,(e.maxY-e.minY)/2*t.height),s=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:s-i/2,y:r-n/2,width:i,height:n}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),n=e.reading();if(!i||!n)return!1;const s=Tt.hitTestHandle({bounds:i,angle:0},t);if(!s)return!1;if(s==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...n.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:s,centre:r,startPointer:t,startSizeM:{...n.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(s,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:o}=t,l=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=o==="e"||o==="w",h=o==="n"||o==="s",d=c?l(i.x-n.x,s.x-n.x):h?l(i.y-n.y,s.y-n.y):l(Math.hypot(i.x-n.x,i.y-n.y),Math.hypot(s.x-n.x,s.y-n.y));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:Bf};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.editableDecor()===void 0?void 0:{sizeM:{widthM:this.decorSizeFieldM(this.decorWidthInput),lengthM:this.decorSizeFieldM(this.decorLengthInput),heightM:this.decorSizeFieldM(this.decorHeightInput)},attitude:{headingDeg:this.numberOrUndefined(this.decorHeadingInput.value)??0,pitchDeg:0,rollDeg:0}},resize:e=>{this.decorWidthInput.value=String(this.roundedMeters(e.widthM)),this.decorLengthInput.value=String(this.roundedMeters(e.lengthM)),this.decorHeightInput.value=String(this.roundedMeters(e.heightM)),this.updateDecor()},turnTo:e=>{this.decorHeadingInput.value=String(this.rounded((e.headingDeg%360+360)%360)),this.updateDecor()},rotateDegPerPx:x6};onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!n||!i||(e.preventDefault(),i.show(n),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorSizeFieldM(e){return this.positiveMeters(e.value)??this.positiveMeters(e.placeholder)??1}beginDecorDrag(e,t){const i=this.editableDecor();if(!i)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.pickDecorAt(e)!==i.id)return!1;const n=this.ndcOf(e),s=n&&this.sceneElement.decorGroundPointAt(i.id,n.x,n.y);return s?(this.dragState={kind:"decor-move",id:i.id,startGround:s,startEastM:Number(this.decorEastInput.value)||0,startNorthM:Number(this.decorNorthInput.value)||0},this.setCanvasCursor("move"),this.startDragListening(),!0):!1}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e),n=i&&this.sceneElement.decorGroundPointAt(t.id,i.x,i.y);n&&(this.decorEastInput.value=String(this.roundedMeters(t.startEastM+n.x-t.startGround.x)),this.decorNorthInput.value=String(this.roundedMeters(t.startNorthM-(n.z-t.startGround.z))),this.updateDecor())}beginCameraDrag(e,t){const i=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,moved:!1,startPointer:e,startHeadingDeg:i?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:i?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:i},i||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&eo(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&eo(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:n,startPointer:s}=this.dragState,r=t.x-s.x,o=t.y-s.y,l=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+o}}}));this.commitShapes(i,l)}else if(this.dragState.kind==="group-resize"){const{group:n,handle:s}=this.dragState;this.commitShapes(i,n.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:n,startPointer:s}=this.dragState;this.commitShapes(i,n.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:n,original:s,vertexIndex:r}=this.dragState,o=Tt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}else{const{kind:n,sourceId:s,original:r,handle:o}=this.dragState,l=n==="resize"?Tt.resizeShape(r,o,t):Tt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:n,startPitchDeg:s,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<S6)return;this.cameraDragState.moved=!0}const o=n+(t.x-i.x)*Bf,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Bf));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!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 i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(ta,i.width-Wr);break;case"ArrowRight":i.width+=Wr;break;case"ArrowUp":i.height=Math.max(ta,i.height-Wr);break;case"ArrowDown":i.height+=Wr;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=Wr;break;case"ArrowRight":i.x+=Wr;break;case"ArrowUp":i.y-=Wr;break;case"ArrowDown":i.y+=Wr;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:n,shape:s}=i[0];this.commitShapes(t,[{sourceId:n,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const n=new dp(i),s=this.nudgeBounds(n.bounds(),e);this.commitShapes(t,n.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const l=r?this.bodyCanvasBounds():void 0,c=l&&Tt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}if(i==="decor"&&r){const l=this.decorCanvasBounds(),c=l&&Tt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);if(this.pickDecorAt(e)===this.currentDecorId)return"move"}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=Tt.hitTestHandle({bounds:new dp(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&Tt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&Tt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${Tt.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),n=e.clientX-i.left,s=e.clientY-i.top;this.recorder?.onPointerMove(n,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(Ay(this.buildPrototype({x:0,y:0,width:qo.width,height:qo.height}),n,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const C6={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},Sy="rr0-sighting-editor",Ey="rr0-ufo-recorder";class P6 extends Di{}function Hw(){Fy(),GC(),qu(),customElements.get(Sy)||customElements.define(Sy,Di),customElements.get(Ey)||customElements.define(Ey,P6)}const wm={recording:"Recording",untitledReading:"Reading {n}",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an observation",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"A JSON file",sourceUrl:"An address",observerField:"Observer",fileField:"File",urlField:"Address",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",caseTitle:"Title",caseTime:"When",recordingsHeading:"Observations",add:"Add",addHint:"Add",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},L6=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:wm},Symbol.toStringTag,{value:"Module"})),_y="rr0-case-editor",k6=`
|
|
9729
9693
|
<style>
|
|
9730
9694
|
:host { display: block; }
|
|
9731
9695
|
[hidden] { display: none !important; }
|